LLVM 24.0.0git
InstCombineCompares.cpp
Go to the documentation of this file.
1//===- InstCombineCompares.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 visitICmp and visitFCmp functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APSInt.h"
16#include "llvm/ADT/SetVector.h"
17#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/Loads.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
35#include <bitset>
36
37using namespace llvm;
38using namespace PatternMatch;
39
40#define DEBUG_TYPE "instcombine"
41
42// How many times is a select replaced by one of its operands?
43STATISTIC(NumSel, "Number of select opts");
44
45namespace llvm {
47}
48
49/// Compute Result = In1+In2, returning true if the result overflowed for this
50/// type.
51static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
52 bool IsSigned = false) {
53 bool Overflow;
54 if (IsSigned)
55 Result = In1.sadd_ov(In2, Overflow);
56 else
57 Result = In1.uadd_ov(In2, Overflow);
58
59 return Overflow;
60}
61
62/// Compute Result = In1-In2, returning true if the result overflowed for this
63/// type.
64static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
65 bool IsSigned = false) {
66 bool Overflow;
67 if (IsSigned)
68 Result = In1.ssub_ov(In2, Overflow);
69 else
70 Result = In1.usub_ov(In2, Overflow);
71
72 return Overflow;
73}
74
75/// Given an icmp instruction, return true if any use of this comparison is a
76/// branch on sign bit comparison.
77static bool hasBranchUse(ICmpInst &I) {
78 for (auto *U : I.users())
79 if (isa<CondBrInst>(U))
80 return true;
81 return false;
82}
83
84/// Returns true if the exploded icmp can be expressed as a signed comparison
85/// to zero and updates the predicate accordingly.
86/// The signedness of the comparison is preserved.
87/// TODO: Refactor with decomposeBitTestICmp()?
88static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
89 if (!ICmpInst::isSigned(Pred))
90 return false;
91
92 if (C.isZero())
93 return ICmpInst::isRelational(Pred);
94
95 if (C.isOne()) {
96 if (Pred == ICmpInst::ICMP_SLT) {
97 Pred = ICmpInst::ICMP_SLE;
98 return true;
99 }
100 } else if (C.isAllOnes()) {
101 if (Pred == ICmpInst::ICMP_SGT) {
102 Pred = ICmpInst::ICMP_SGE;
103 return true;
104 }
105 }
106
107 return false;
108}
109
110/// This is called when we see this pattern:
111/// cmp pred (load (gep GV, ...)), cmpcst
112/// where GV is a global variable with a constant initializer. Try to simplify
113/// this into some simple computation that does not need the load. For example
114/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
115///
116/// If AndCst is non-null, then the loaded value is masked with that constant
117/// before doing the comparison. This handles cases like "A[i]&4 == 0".
118///
119/// We allow multi-use cases in this fold, even though it can increase
120/// instruction count, because it appears to be mostly beneficial in practice.
121/// Even if there are multiple uses, they can often be sunk into the block
122/// guarded by the icmp.
124 LoadInst *LI, GetElementPtrInst *GEP, CmpInst &ICI, ConstantInt *AndCst) {
126 if (LI->isVolatile() || !GV || !GV->isConstant() ||
127 !GV->hasDefinitiveInitializer())
128 return nullptr;
129
130 Type *EltTy = LI->getType();
131 TypeSize EltSize = DL.getTypeStoreSize(EltTy);
132 if (EltSize.isScalable())
133 return nullptr;
134
136 if (!Expr.Index || Expr.BasePtr != GV || Expr.Offset.getBitWidth() > 64)
137 return nullptr;
138
139 Constant *Init = GV->getInitializer();
140 TypeSize GlobalSize = DL.getTypeAllocSize(Init->getType());
141
142 Value *Idx = Expr.Index;
143 const APInt &Stride = Expr.Scale;
144 const APInt &ConstOffset = Expr.Offset;
145
146 // Allow an additional context offset, but only within the stride.
147 if (!ConstOffset.ult(Stride))
148 return nullptr;
149
150 // Don't handle overlapping loads for now.
151 if (!Stride.uge(EltSize.getFixedValue()))
152 return nullptr;
153
154 // Don't blow up on huge arrays.
155 uint64_t ArrayElementCount =
156 divideCeil((GlobalSize.getFixedValue() - ConstOffset.getZExtValue()),
157 Stride.getZExtValue());
158 if (ArrayElementCount > MaxArraySizeForCombine)
159 return nullptr;
160
161 enum { Overdefined = -3, Undefined = -2 };
162
163 // Variables for our state machines.
164
165 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
166 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
167 // and 87 is the second (and last) index. FirstTrueElement is -2 when
168 // undefined, otherwise set to the first true element. SecondTrueElement is
169 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
170 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
171
172 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
173 // form "i != 47 & i != 87". Same state transitions as for true elements.
174 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
175
176 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
177 /// define a state machine that triggers for ranges of values that the index
178 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
179 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
180 /// index in the range (inclusive). We use -2 for undefined here because we
181 /// use relative comparisons and don't want 0-1 to match -1.
182 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
183
184 // MagicBitvector - This is a magic bitvector where we set a bit if the
185 // comparison is true for element 'i'. If there are 64 elements or less in
186 // the array, this will fully represent all the comparison results.
187 uint64_t MagicBitvector = 0;
188
189 // Scan the array and see if one of our patterns matches.
190 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
191 APInt Offset = ConstOffset;
192 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i, Offset += Stride) {
194 if (!Elt)
195 return nullptr;
196
197 // If the element is masked, handle it.
198 if (AndCst) {
199 Elt = ConstantFoldBinaryOpOperands(Instruction::And, Elt, AndCst, DL);
200 if (!Elt)
201 return nullptr;
202 }
203
204 // Find out if the comparison would be true or false for the i'th element.
206 CompareRHS, DL, &TLI);
207 if (!C)
208 return nullptr;
209
210 // If the result is undef for this element, ignore it.
211 if (isa<UndefValue>(C)) {
212 // Extend range state machines to cover this element in case there is an
213 // undef in the middle of the range.
214 if (TrueRangeEnd == (int)i - 1)
215 TrueRangeEnd = i;
216 if (FalseRangeEnd == (int)i - 1)
217 FalseRangeEnd = i;
218 continue;
219 }
220
221 // If we can't compute the result for any of the elements, we have to give
222 // up evaluating the entire conditional.
223 if (!isa<ConstantInt>(C))
224 return nullptr;
225
226 // Otherwise, we know if the comparison is true or false for this element,
227 // update our state machines.
228 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
229
230 // State machine for single/double/range index comparison.
231 if (IsTrueForElt) {
232 // Update the TrueElement state machine.
233 if (FirstTrueElement == Undefined)
234 FirstTrueElement = TrueRangeEnd = i; // First true element.
235 else {
236 // Update double-compare state machine.
237 if (SecondTrueElement == Undefined)
238 SecondTrueElement = i;
239 else
240 SecondTrueElement = Overdefined;
241
242 // Update range state machine.
243 if (TrueRangeEnd == (int)i - 1)
244 TrueRangeEnd = i;
245 else
246 TrueRangeEnd = Overdefined;
247 }
248 } else {
249 // Update the FalseElement state machine.
250 if (FirstFalseElement == Undefined)
251 FirstFalseElement = FalseRangeEnd = i; // First false element.
252 else {
253 // Update double-compare state machine.
254 if (SecondFalseElement == Undefined)
255 SecondFalseElement = i;
256 else
257 SecondFalseElement = Overdefined;
258
259 // Update range state machine.
260 if (FalseRangeEnd == (int)i - 1)
261 FalseRangeEnd = i;
262 else
263 FalseRangeEnd = Overdefined;
264 }
265 }
266
267 // If this element is in range, update our magic bitvector.
268 if (i < 64 && IsTrueForElt)
269 MagicBitvector |= 1ULL << i;
270
271 // If all of our states become overdefined, bail out early. Since the
272 // predicate is expensive, only check it every 8 elements. This is only
273 // really useful for really huge arrays.
274 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
275 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
276 FalseRangeEnd == Overdefined)
277 return nullptr;
278 }
279
280 // Now that we've scanned the entire array, emit our new comparison(s). We
281 // order the state machines in complexity of the generated code.
282
283 // If inbounds keyword is not present, Idx * Stride can overflow.
284 // Let's assume that Stride is 2 and the wanted value is at offset 0.
285 // Then, there are two possible values for Idx to match offset 0:
286 // 0x00..00, 0x80..00.
287 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
288 // comparison is false if Idx was 0x80..00.
289 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
290 auto MaskIdx = [&](Value *Idx) {
291 if (!Expr.Flags.isInBounds() && Stride.countr_zero() != 0) {
293 Mask = Builder.CreateLShr(Mask, Stride.countr_zero());
294 Idx = Builder.CreateAnd(Idx, Mask);
295 }
296 return Idx;
297 };
298
299 // If the comparison is only true for one or two elements, emit direct
300 // comparisons.
301 if (SecondTrueElement != Overdefined) {
302 Idx = MaskIdx(Idx);
303 // None true -> false.
304 if (FirstTrueElement == Undefined)
305 return replaceInstUsesWith(ICI, Builder.getFalse());
306
307 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
308
309 // True for one element -> 'i == 47'.
310 if (SecondTrueElement == Undefined)
311 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
312
313 // True for two elements -> 'i == 47 | i == 72'.
314 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
315 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
316 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
317 return BinaryOperator::CreateOr(C1, C2);
318 }
319
320 // If the comparison is only false for one or two elements, emit direct
321 // comparisons.
322 if (SecondFalseElement != Overdefined) {
323 Idx = MaskIdx(Idx);
324 // None false -> true.
325 if (FirstFalseElement == Undefined)
326 return replaceInstUsesWith(ICI, Builder.getTrue());
327
328 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
329
330 // False for one element -> 'i != 47'.
331 if (SecondFalseElement == Undefined)
332 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
333
334 // False for two elements -> 'i != 47 & i != 72'.
335 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
336 Value *SecondFalseIdx =
337 ConstantInt::get(Idx->getType(), SecondFalseElement);
338 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
339 return BinaryOperator::CreateAnd(C1, C2);
340 }
341
342 // If the comparison can be replaced with a range comparison for the elements
343 // where it is true, emit the range check.
344 if (TrueRangeEnd != Overdefined) {
345 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
346 Idx = MaskIdx(Idx);
347
348 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
349 if (FirstTrueElement) {
350 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstTrueElement);
351 Idx = Builder.CreateAdd(Idx, Offs);
352 }
353
354 Value *End =
355 ConstantInt::get(Idx->getType(), TrueRangeEnd - FirstTrueElement + 1);
356 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
357 }
358
359 // False range check.
360 if (FalseRangeEnd != Overdefined) {
361 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
362 Idx = MaskIdx(Idx);
363 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
364 if (FirstFalseElement) {
365 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstFalseElement);
366 Idx = Builder.CreateAdd(Idx, Offs);
367 }
368
369 Value *End =
370 ConstantInt::get(Idx->getType(), FalseRangeEnd - FirstFalseElement);
371 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
372 }
373
374 // If a magic bitvector captures the entire comparison state
375 // of this load, replace it with computation that does:
376 // ((magic_cst >> i) & 1) != 0
377 {
378 Type *Ty = nullptr;
379
380 // Look for an appropriate type:
381 // - The type of Idx if the magic fits
382 // - The smallest fitting legal type
383 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
384 Ty = Idx->getType();
385 else
386 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
387
388 if (Ty) {
389 Idx = MaskIdx(Idx);
390 Value *V = Builder.CreateIntCast(Idx, Ty, false);
391 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
392 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
393 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
394 }
395 }
396
397 return nullptr;
398}
399
400/// Returns true if we can rewrite Start as a GEP with pointer Base
401/// and some integer offset. The nodes that need to be re-written
402/// for this transformation will be added to Explored.
404 const DataLayout &DL,
405 SetVector<Value *> &Explored) {
406 SmallVector<Value *, 16> WorkList(1, Start);
407 Explored.insert(Base);
408
409 // The following traversal gives us an order which can be used
410 // when doing the final transformation. Since in the final
411 // transformation we create the PHI replacement instructions first,
412 // we don't have to get them in any particular order.
413 //
414 // However, for other instructions we will have to traverse the
415 // operands of an instruction first, which means that we have to
416 // do a post-order traversal.
417 while (!WorkList.empty()) {
419
420 while (!WorkList.empty()) {
421 if (Explored.size() >= 100)
422 return false;
423
424 Value *V = WorkList.back();
425
426 if (Explored.contains(V)) {
427 WorkList.pop_back();
428 continue;
429 }
430
432 // We've found some value that we can't explore which is different from
433 // the base. Therefore we can't do this transformation.
434 return false;
435
436 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
437 // Only allow inbounds GEPs with at most one variable offset.
438 auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(V); };
439 if (!GEP->isInBounds() || count_if(GEP->indices(), IsNonConst) > 1)
440 return false;
441
442 NW = NW.intersectForOffsetAdd(GEP->getNoWrapFlags());
443 if (!Explored.contains(GEP->getOperand(0)))
444 WorkList.push_back(GEP->getOperand(0));
445 }
446
447 if (WorkList.back() == V) {
448 WorkList.pop_back();
449 // We've finished visiting this node, mark it as such.
450 Explored.insert(V);
451 }
452
453 if (auto *PN = dyn_cast<PHINode>(V)) {
454 // We cannot transform PHIs on unsplittable basic blocks.
455 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
456 return false;
457 Explored.insert(PN);
458 PHIs.insert(PN);
459 }
460 }
461
462 // Explore the PHI nodes further.
463 for (auto *PN : PHIs)
464 for (Value *Op : PN->incoming_values())
465 if (!Explored.contains(Op))
466 WorkList.push_back(Op);
467 }
468
469 // Make sure that we can do this. Since we can't insert GEPs in a basic
470 // block before a PHI node, we can't easily do this transformation if
471 // we have PHI node users of transformed instructions.
472 for (Value *Val : Explored) {
473 for (Value *Use : Val->uses()) {
474
475 auto *PHI = dyn_cast<PHINode>(Use);
476 auto *Inst = dyn_cast<Instruction>(Val);
477
478 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
479 !Explored.contains(PHI))
480 continue;
481
482 if (PHI->getParent() == Inst->getParent())
483 return false;
484 }
485 }
486 return true;
487}
488
489// Sets the appropriate insert point on Builder where we can add
490// a replacement Instruction for V (if that is possible).
491static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
492 bool Before = true) {
493 if (auto *PHI = dyn_cast<PHINode>(V)) {
494 BasicBlock *Parent = PHI->getParent();
495 Builder.SetInsertPoint(Parent, Parent->getFirstInsertionPt());
496 return;
497 }
498 if (auto *I = dyn_cast<Instruction>(V)) {
499 if (!Before)
500 I = &*std::next(I->getIterator());
501 Builder.SetInsertPoint(I);
502 return;
503 }
504 if (auto *A = dyn_cast<Argument>(V)) {
505 // Set the insertion point in the entry block.
506 BasicBlock &Entry = A->getParent()->getEntryBlock();
507 Builder.SetInsertPoint(&Entry, Entry.getFirstInsertionPt());
508 return;
509 }
510 // Otherwise, this is a constant and we don't need to set a new
511 // insertion point.
512 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
513}
514
515/// Returns a re-written value of Start as an indexed GEP using Base as a
516/// pointer.
518 const DataLayout &DL,
519 SetVector<Value *> &Explored,
520 InstCombiner &IC) {
521 // Perform all the substitutions. This is a bit tricky because we can
522 // have cycles in our use-def chains.
523 // 1. Create the PHI nodes without any incoming values.
524 // 2. Create all the other values.
525 // 3. Add the edges for the PHI nodes.
526 // 4. Emit GEPs to get the original pointers.
527 // 5. Remove the original instructions.
528 Type *IndexType = IntegerType::get(
529 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
530
532 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
533
534 // Create the new PHI nodes, without adding any incoming values.
535 for (Value *Val : Explored) {
536 if (Val == Base)
537 continue;
538 // Create empty phi nodes. This avoids cyclic dependencies when creating
539 // the remaining instructions.
540 if (auto *PHI = dyn_cast<PHINode>(Val))
541 NewInsts[PHI] =
542 PHINode::Create(IndexType, PHI->getNumIncomingValues(),
543 PHI->getName() + ".idx", PHI->getIterator());
544 }
545 IRBuilder<> Builder(Base->getContext());
546
547 // Create all the other instructions.
548 for (Value *Val : Explored) {
549 if (NewInsts.contains(Val))
550 continue;
551
552 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
553 setInsertionPoint(Builder, GEP);
554 Value *Op = NewInsts[GEP->getOperand(0)];
555 Value *OffsetV = emitGEPOffset(&Builder, DL, GEP);
557 NewInsts[GEP] = OffsetV;
558 else
559 NewInsts[GEP] = Builder.CreateAdd(
560 Op, OffsetV, GEP->getOperand(0)->getName() + ".add",
561 /*NUW=*/NW.hasNoUnsignedWrap(),
562 /*NSW=*/NW.hasNoUnsignedSignedWrap());
563 continue;
564 }
565 if (isa<PHINode>(Val))
566 continue;
567
568 llvm_unreachable("Unexpected instruction type");
569 }
570
571 // Add the incoming values to the PHI nodes.
572 for (Value *Val : Explored) {
573 if (Val == Base)
574 continue;
575 // All the instructions have been created, we can now add edges to the
576 // phi nodes.
577 if (auto *PHI = dyn_cast<PHINode>(Val)) {
578 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
579 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
580 Value *NewIncoming = PHI->getIncomingValue(I);
581
582 auto It = NewInsts.find(NewIncoming);
583 if (It != NewInsts.end())
584 NewIncoming = It->second;
585
586 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
587 }
588 }
589 }
590
591 for (Value *Val : Explored) {
592 if (Val == Base)
593 continue;
594
595 setInsertionPoint(Builder, Val, false);
596 // Create GEP for external users.
597 Value *NewVal = Builder.CreateGEP(Builder.getInt8Ty(), Base, NewInsts[Val],
598 Val->getName() + ".ptr", NW);
599 IC.replaceInstUsesWith(*cast<Instruction>(Val), NewVal);
600 // Add old instruction to worklist for DCE. We don't directly remove it
601 // here because the original compare is one of the users.
603 }
604
605 return NewInsts[Start];
606}
607
608/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
609/// We can look through PHIs, GEPs and casts in order to determine a common base
610/// between GEPLHS and RHS.
613 const DataLayout &DL,
614 InstCombiner &IC) {
615 // FIXME: Support vector of pointers.
616 if (GEPLHS->getType()->isVectorTy())
617 return nullptr;
618
619 if (!GEPLHS->hasAllConstantIndices())
620 return nullptr;
621
622 APInt Offset(DL.getIndexTypeSizeInBits(GEPLHS->getType()), 0);
623 Value *PtrBase =
625 /*AllowNonInbounds*/ false);
626
627 // Bail if we looked through addrspacecast.
628 if (PtrBase->getType() != GEPLHS->getType())
629 return nullptr;
630
631 // The set of nodes that will take part in this transformation.
632 SetVector<Value *> Nodes;
633 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags();
634 if (!canRewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes))
635 return nullptr;
636
637 // We know we can re-write this as
638 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
639 // Since we've only looked through inbouds GEPs we know that we
640 // can't have overflow on either side. We can therefore re-write
641 // this as:
642 // OFFSET1 cmp OFFSET2
643 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes, IC);
644
645 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
646 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
647 // offset. Since Index is the offset of LHS to the base pointer, we will now
648 // compare the offsets instead of comparing the pointers.
650 IC.Builder.getInt(Offset), NewRHS);
651}
652
653/// Fold comparisons between a GEP instruction and something else. At this point
654/// we know that the GEP is on the LHS of the comparison.
657 // Don't transform signed compares of GEPs into index compares. Even if the
658 // GEP is inbounds, the final add of the base pointer can have signed overflow
659 // and would change the result of the icmp.
660 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
661 // the maximum signed value for the pointer type.
663 return nullptr;
664
665 // Look through bitcasts and addrspacecasts. We do not however want to remove
666 // 0 GEPs.
667 if (!isa<GetElementPtrInst>(RHS))
668 RHS = RHS->stripPointerCasts();
669
670 auto CanFold = [Cond](GEPNoWrapFlags NW) {
672 return true;
673
674 // Unsigned predicates can be folded if the GEPs have *any* nowrap flags.
676 return NW != GEPNoWrapFlags::none();
677 };
678
679 auto NewICmp = [Cond](GEPNoWrapFlags NW, Value *Op1, Value *Op2) {
680 if (!NW.hasNoUnsignedWrap()) {
681 // Convert signed to unsigned comparison.
682 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Op1, Op2);
683 }
684
685 auto *I = new ICmpInst(Cond, Op1, Op2);
686 I->setSameSign(NW.hasNoUnsignedSignedWrap());
687 return I;
688 };
689
691 if (Base.Ptr == RHS && CanFold(Base.LHSNW) && !Base.isExpensive()) {
692 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
693 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
694 Value *Offset =
695 EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy, /*RewriteGEPs=*/true);
696 return NewICmp(Base.LHSNW, Offset,
697 Constant::getNullValue(Offset->getType()));
698 }
699
700 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
702 !NullPointerIsDefined(I.getFunction(),
703 RHS->getType()->getPointerAddressSpace())) {
704 // For most address spaces, an allocation can't be placed at null, but null
705 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
706 // the only valid inbounds address derived from null, is null itself.
707 // Thus, we have four cases to consider:
708 // 1) Base == nullptr, Offset == 0 -> inbounds, null
709 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
710 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
711 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
712 //
713 // (Note if we're indexing a type of size 0, that simply collapses into one
714 // of the buckets above.)
715 //
716 // In general, we're allowed to make values less poison (i.e. remove
717 // sources of full UB), so in this case, we just select between the two
718 // non-poison cases (1 and 4 above).
719 //
720 // For vectors, we apply the same reasoning on a per-lane basis.
721 auto *Base = GEPLHS->getPointerOperand();
722 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
723 auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
724 Base = Builder.CreateVectorSplat(EC, Base);
725 }
726 return new ICmpInst(Cond, Base,
728 cast<Constant>(RHS), Base->getType()));
729 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
730 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags() & GEPRHS->getNoWrapFlags();
731
732 // If the base pointers are different, but the indices are the same, just
733 // compare the base pointer.
734 if (GEPLHS->getOperand(0) != GEPRHS->getOperand(0)) {
735 bool IndicesTheSame =
736 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
737 GEPLHS->getPointerOperand()->getType() ==
738 GEPRHS->getPointerOperand()->getType() &&
739 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
740 if (IndicesTheSame)
741 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
742 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
743 IndicesTheSame = false;
744 break;
745 }
746
747 // If all indices are the same, just compare the base pointers.
748 Type *BaseType = GEPLHS->getOperand(0)->getType();
749 if (IndicesTheSame &&
750 CmpInst::makeCmpResultType(BaseType) == I.getType() && CanFold(NW))
751 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
752
753 // If we're comparing GEPs with two base pointers that only differ in type
754 // and both GEPs have only constant indices or just one use, then fold
755 // the compare with the adjusted indices.
756 // FIXME: Support vector of pointers.
757 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
758 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
759 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
760 GEPLHS->getOperand(0)->stripPointerCasts() ==
761 GEPRHS->getOperand(0)->stripPointerCasts() &&
762 !GEPLHS->getType()->isVectorTy()) {
763 Value *LOffset = EmitGEPOffset(GEPLHS);
764 Value *ROffset = EmitGEPOffset(GEPRHS);
765
766 // If we looked through an addrspacecast between different sized address
767 // spaces, the LHS and RHS pointers are different sized
768 // integers. Truncate to the smaller one.
769 Type *LHSIndexTy = LOffset->getType();
770 Type *RHSIndexTy = ROffset->getType();
771 if (LHSIndexTy != RHSIndexTy) {
772 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
773 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
774 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
775 } else
776 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
777 }
778
780 LOffset, ROffset);
781 return replaceInstUsesWith(I, Cmp);
782 }
783 }
784
785 if (GEPLHS->getOperand(0) == GEPRHS->getOperand(0) &&
786 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
787 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
788 // If the GEPs only differ by one index, compare it.
789 unsigned NumDifferences = 0; // Keep track of # differences.
790 unsigned DiffOperand = 0; // The operand that differs.
791 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
792 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
793 Type *LHSType = GEPLHS->getOperand(i)->getType();
794 Type *RHSType = GEPRHS->getOperand(i)->getType();
795 // FIXME: Better support for vector of pointers.
796 if (LHSType->getPrimitiveSizeInBits() !=
797 RHSType->getPrimitiveSizeInBits() ||
798 (GEPLHS->getType()->isVectorTy() &&
799 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
800 // Irreconcilable differences.
801 NumDifferences = 2;
802 break;
803 }
804
805 if (NumDifferences++)
806 break;
807 DiffOperand = i;
808 }
809
810 if (NumDifferences == 0) // SAME GEP?
811 return replaceInstUsesWith(
812 I, // No comparison is needed here.
813 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
814 // If two GEPs only differ by an index, compare them.
815 // Note that nowrap flags are always needed when comparing two indices.
816 else if (NumDifferences == 1 && NW != GEPNoWrapFlags::none()) {
817 Value *LHSV = GEPLHS->getOperand(DiffOperand);
818 Value *RHSV = GEPRHS->getOperand(DiffOperand);
819 return NewICmp(NW, LHSV, RHSV);
820 }
821 }
822
823 if (Base.Ptr && !Base.isExpensive()) {
824 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
825 bool DoFold = CanFold(Base.LHSNW & Base.RHSNW);
826
827 if (!DoFold && Base.Ptr->getType()->isPointerTy()) {
828 // Without the flags, we can still fold if the offsets are constant and
829 // they cross the base's alignment boundary the same number of times, so
830 // either both arguments will wrap, or none of them will.
831 unsigned BW = DL.getIndexTypeSizeInBits(GEPLHS->getType());
832 APInt Alignment = APInt(BW, Base.Ptr->getPointerAlignment(DL).value());
833 APInt LOff(BW, 0);
834 APInt ROff(BW, 0);
836 DL, LOff, /*AllowNonInbounds=*/true) == Base.Ptr &&
837 RHS->stripAndAccumulateConstantOffsets(
838 DL, ROff, /*AllowNonInbounds=*/true) == Base.Ptr)
839 DoFold =
842 }
843
844 if (DoFold) {
845 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
846 Value *L = EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy,
847 /*RewriteGEP=*/true);
848 Value *R = EmitGEPOffsets(Base.RHSGEPs, Base.RHSNW, IdxTy,
849 /*RewriteGEP=*/true);
850 return NewICmp(Base.LHSNW & Base.RHSNW, L, R);
851 }
852 }
853 }
854
855 // Try convert this to an indexed compare by looking through PHIs/casts as a
856 // last resort.
857 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
858}
859
861 // It would be tempting to fold away comparisons between allocas and any
862 // pointer not based on that alloca (e.g. an argument). However, even
863 // though such pointers cannot alias, they can still compare equal.
864 //
865 // But LLVM doesn't specify where allocas get their memory, so if the alloca
866 // doesn't escape we can argue that it's impossible to guess its value, and we
867 // can therefore act as if any such guesses are wrong.
868 //
869 // However, we need to ensure that this folding is consistent: We can't fold
870 // one comparison to false, and then leave a different comparison against the
871 // same value alone (as it might evaluate to true at runtime, leading to a
872 // contradiction). As such, this code ensures that all comparisons are folded
873 // at the same time, and there are no other escapes.
874
875 struct CmpCaptureTracker : public CaptureTracker {
876 AllocaInst *Alloca;
877 bool Captured = false;
878 /// The value of the map is a bit mask of which icmp operands the alloca is
879 /// used in.
881
882 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
883
884 void tooManyUses() override { Captured = true; }
885
886 Action captured(const Use *U, UseCaptureInfo CI) override {
887 // TODO(captures): Use UseCaptureInfo.
888 auto *ICmp = dyn_cast<ICmpInst>(U->getUser());
889 // We need to check that U is based *only* on the alloca, and doesn't
890 // have other contributions from a select/phi operand.
891 // TODO: We could check whether getUnderlyingObjects() reduces to one
892 // object, which would allow looking through phi nodes.
893 if (ICmp && ICmp->isEquality() && getUnderlyingObject(*U) == Alloca) {
894 // Collect equality icmps of the alloca, and don't treat them as
895 // captures.
896 ICmps[ICmp] |= 1u << U->getOperandNo();
897 return Continue;
898 }
899
900 Captured = true;
901 return Stop;
902 }
903 };
904
905 CmpCaptureTracker Tracker(Alloca);
906 PointerMayBeCaptured(Alloca, &Tracker);
907 if (Tracker.Captured)
908 return false;
909
910 bool Changed = false;
911 for (auto [ICmp, Operands] : Tracker.ICmps) {
912 switch (Operands) {
913 case 1:
914 case 2: {
915 // The alloca is only used in one icmp operand. Assume that the
916 // equality is false.
917 auto *Res = ConstantInt::get(ICmp->getType(),
918 ICmp->getPredicate() == ICmpInst::ICMP_NE);
919 replaceInstUsesWith(*ICmp, Res);
921 Changed = true;
922 break;
923 }
924 case 3:
925 // Both icmp operands are based on the alloca, so this is comparing
926 // pointer offsets, without leaking any information about the address
927 // of the alloca. Ignore such comparisons.
928 break;
929 default:
930 llvm_unreachable("Cannot happen");
931 }
932 }
933
934 return Changed;
935}
936
937/// Fold "icmp pred (X+C), X".
939 CmpPredicate Pred) {
940 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
941 // so the values can never be equal. Similarly for all other "or equals"
942 // operators.
943 assert(!!C && "C should not be zero!");
944
945 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
946 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
947 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
948 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
949 Constant *R =
950 ConstantInt::get(X->getType(), APInt::getMaxValue(C.getBitWidth()) - C);
951 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
952 }
953
954 // (X+1) >u X --> X <u (0-1) --> X != 255
955 // (X+2) >u X --> X <u (0-2) --> X <u 254
956 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
957 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
958 return new ICmpInst(ICmpInst::ICMP_ULT, X,
959 ConstantInt::get(X->getType(), -C));
960
961 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
962
963 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
964 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
965 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
966 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
967 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
968 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
969 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
970 return new ICmpInst(ICmpInst::ICMP_SGT, X,
971 ConstantInt::get(X->getType(), SMax - C));
972
973 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
974 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
975 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
976 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
977 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
978 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
979
980 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
981 return new ICmpInst(ICmpInst::ICMP_SLT, X,
982 ConstantInt::get(X->getType(), SMax - (C - 1)));
983}
984
985/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
986/// (icmp eq/ne A, Log2(AP2/AP1)) ->
987/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
989 const APInt &AP1,
990 const APInt &AP2) {
991 assert(I.isEquality() && "Cannot fold icmp gt/lt");
992
993 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
994 if (I.getPredicate() == I.ICMP_NE)
995 Pred = CmpInst::getInversePredicate(Pred);
996 return new ICmpInst(Pred, LHS, RHS);
997 };
998
999 // Don't bother doing any work for cases which InstSimplify handles.
1000 if (AP2.isZero())
1001 return nullptr;
1002
1003 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
1004 if (IsAShr) {
1005 if (AP2.isAllOnes())
1006 return nullptr;
1007 if (AP2.isNegative() != AP1.isNegative())
1008 return nullptr;
1009 if (AP2.sgt(AP1))
1010 return nullptr;
1011 }
1012
1013 if (!AP1)
1014 // 'A' must be large enough to shift out the highest set bit.
1015 return getICmp(I.ICMP_UGT, A,
1016 ConstantInt::get(A->getType(), AP2.logBase2()));
1017
1018 if (AP1 == AP2)
1019 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1020
1021 int Shift;
1022 if (IsAShr && AP1.isNegative())
1023 Shift = AP1.countl_one() - AP2.countl_one();
1024 else
1025 Shift = AP1.countl_zero() - AP2.countl_zero();
1026
1027 if (Shift > 0) {
1028 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1029 // There are multiple solutions if we are comparing against -1 and the LHS
1030 // of the ashr is not a power of two.
1031 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1032 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1033 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1034 } else if (AP1 == AP2.lshr(Shift)) {
1035 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1036 }
1037 }
1038
1039 // Shifting const2 will never be equal to const1.
1040 // FIXME: This should always be handled by InstSimplify?
1041 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1042 return replaceInstUsesWith(I, TorF);
1043}
1044
1045/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1046/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1048 const APInt &AP1,
1049 const APInt &AP2) {
1050 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1051
1052 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1053 if (I.getPredicate() == I.ICMP_NE)
1054 Pred = CmpInst::getInversePredicate(Pred);
1055 return new ICmpInst(Pred, LHS, RHS);
1056 };
1057
1058 // Don't bother doing any work for cases which InstSimplify handles.
1059 if (AP2.isZero())
1060 return nullptr;
1061
1062 unsigned AP2TrailingZeros = AP2.countr_zero();
1063
1064 if (!AP1 && AP2TrailingZeros != 0)
1065 return getICmp(
1066 I.ICMP_UGE, A,
1067 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1068
1069 if (AP1 == AP2)
1070 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1071
1072 // Get the distance between the lowest bits that are set.
1073 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1074
1075 if (Shift > 0 && AP2.shl(Shift) == AP1)
1076 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1077
1078 // Shifting const2 will never be equal to const1.
1079 // FIXME: This should always be handled by InstSimplify?
1080 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1081 return replaceInstUsesWith(I, TorF);
1082}
1083
1084/// The caller has matched a pattern of the form:
1085/// I = icmp ugt (add (add A, B), CI2), CI1
1086/// If this is of the form:
1087/// sum = a + b
1088/// if (sum+128 >u 255)
1089/// Then replace it with llvm.sadd.with.overflow.i8.
1090///
1092 ConstantInt *CI2, ConstantInt *CI1,
1093 InstCombinerImpl &IC) {
1094 // The transformation we're trying to do here is to transform this into an
1095 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1096 // with a narrower add, and discard the add-with-constant that is part of the
1097 // range check (if we can't eliminate it, this isn't profitable).
1098
1099 // In order to eliminate the add-with-constant, the compare can be its only
1100 // use.
1101 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1102 if (!AddWithCst->hasOneUse())
1103 return nullptr;
1104
1105 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1106 if (!CI2->getValue().isPowerOf2())
1107 return nullptr;
1108 unsigned NewWidth = CI2->getValue().countr_zero();
1109 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1110 return nullptr;
1111
1112 // The width of the new add formed is 1 more than the bias.
1113 ++NewWidth;
1114
1115 // Check to see that CI1 is an all-ones value with NewWidth bits.
1116 if (CI1->getBitWidth() == NewWidth ||
1117 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1118 return nullptr;
1119
1120 // This is only really a signed overflow check if the inputs have been
1121 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1122 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1123 if (IC.ComputeMaxSignificantBits(A, &I) > NewWidth ||
1124 IC.ComputeMaxSignificantBits(B, &I) > NewWidth)
1125 return nullptr;
1126
1127 // In order to replace the original add with a narrower
1128 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1129 // and truncates that discard the high bits of the add. Verify that this is
1130 // the case.
1131 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1132 for (User *U : OrigAdd->users()) {
1133 if (U == AddWithCst)
1134 continue;
1135
1136 // Only accept truncates for now. We would really like a nice recursive
1137 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1138 // chain to see which bits of a value are actually demanded. If the
1139 // original add had another add which was then immediately truncated, we
1140 // could still do the transformation.
1142 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1143 return nullptr;
1144 }
1145
1146 // If the pattern matches, truncate the inputs to the narrower type and
1147 // use the sadd_with_overflow intrinsic to efficiently compute both the
1148 // result and the overflow bit.
1149 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1151 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1152
1153 InstCombiner::BuilderTy &Builder = IC.Builder;
1154
1155 // Put the new code above the original add, in case there are any uses of the
1156 // add between the add and the compare.
1157 Builder.SetInsertPoint(OrigAdd);
1158
1159 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1160 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1161 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1162 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1163 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1164
1165 // The inner add was the result of the narrow add, zero extended to the
1166 // wider type. Replace it with the result computed by the intrinsic.
1167 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1168 IC.eraseInstFromFunction(*OrigAdd);
1169
1170 // The original icmp gets replaced with the overflow value.
1171 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1172}
1173
1174/// If we have:
1175/// icmp eq/ne (urem/srem %x, %y), 0
1176/// iff %y is a power-of-two, we can replace this with a bit test:
1177/// icmp eq/ne (and %x, (add %y, -1)), 0
1179 // This fold is only valid for equality predicates.
1180 if (!I.isEquality())
1181 return nullptr;
1182 CmpPredicate Pred;
1183 Value *X, *Y, *Zero;
1184 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1185 m_CombineAnd(m_Zero(), m_Value(Zero)))))
1186 return nullptr;
1187 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, &I))
1188 return nullptr;
1189 // This may increase instruction count, we don't enforce that Y is a constant.
1190 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1191 Value *Masked = Builder.CreateAnd(X, Mask);
1192 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1193}
1194
1195/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1196/// by one-less-than-bitwidth into a sign test on the original value.
1198 Instruction *Val;
1199 CmpPredicate Pred;
1200 if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1201 return nullptr;
1202
1203 Value *X;
1204 Type *XTy;
1205
1206 Constant *C;
1207 if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1208 XTy = X->getType();
1209 unsigned XBitWidth = XTy->getScalarSizeInBits();
1211 APInt(XBitWidth, XBitWidth - 1))))
1212 return nullptr;
1213 } else if (isa<BinaryOperator>(Val) &&
1215 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1216 /*AnalyzeForSignBitExtraction=*/true))) {
1217 XTy = X->getType();
1218 } else
1219 return nullptr;
1220
1221 return ICmpInst::Create(Instruction::ICmp,
1225}
1226
1227// Handle icmp pred X, 0
1229 CmpInst::Predicate Pred = Cmp.getPredicate();
1230 if (!match(Cmp.getOperand(1), m_Zero()))
1231 return nullptr;
1232
1233 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1234 if (Pred == ICmpInst::ICMP_SGT) {
1235 Value *A, *B;
1236 if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1237 if (isKnownPositive(A, SQ.getWithInstruction(&Cmp)))
1238 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1239 if (isKnownPositive(B, SQ.getWithInstruction(&Cmp)))
1240 return new ICmpInst(Pred, A, Cmp.getOperand(1));
1241 }
1242 }
1243
1245 return New;
1246
1247 // Given:
1248 // icmp eq/ne (urem %x, %y), 0
1249 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1250 // icmp eq/ne %x, 0
1251 Value *X, *Y;
1252 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1253 ICmpInst::isEquality(Pred)) {
1254 KnownBits XKnown = computeKnownBits(X, &Cmp);
1255 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1256 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1257 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1258 }
1259
1260 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1261 // odd/non-zero/there is no overflow.
1262 if (match(Cmp.getOperand(0), m_Mul(m_Value(X), m_Value(Y))) &&
1263 ICmpInst::isEquality(Pred)) {
1264
1265 KnownBits XKnown = computeKnownBits(X, &Cmp);
1266 // if X % 2 != 0
1267 // (icmp eq/ne Y)
1268 if (XKnown.countMaxTrailingZeros() == 0)
1269 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1270
1271 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1272 // if Y % 2 != 0
1273 // (icmp eq/ne X)
1274 if (YKnown.countMaxTrailingZeros() == 0)
1275 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1276
1277 auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1278 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1279 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
1280 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1281 // but to avoid unnecessary work, first just if this is an obvious case.
1282
1283 // if X non-zero and NoOverflow(X * Y)
1284 // (icmp eq/ne Y)
1285 if (!XKnown.One.isZero() || isKnownNonZero(X, Q))
1286 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1287
1288 // if Y non-zero and NoOverflow(X * Y)
1289 // (icmp eq/ne X)
1290 if (!YKnown.One.isZero() || isKnownNonZero(Y, Q))
1291 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1292 }
1293 // Note, we are skipping cases:
1294 // if Y % 2 != 0 AND X % 2 != 0
1295 // (false/true)
1296 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1297 // (false/true)
1298 // Those can be simplified later as we would have already replaced the (icmp
1299 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1300 // will fold to a constant elsewhere.
1301 }
1302
1303 // (icmp eq/ne f(X), 0) -> (icmp eq/ne X, 0)
1304 // where f(X) == 0 if and only if X == 0
1305 if (ICmpInst::isEquality(Pred))
1306 if (Value *Stripped = stripNullTest(Cmp.getOperand(0)))
1307 return new ICmpInst(Pred, Stripped,
1308 Constant::getNullValue(Stripped->getType()));
1309
1310 return nullptr;
1311}
1312
1313/// Fold icmp eq (num + mask) & ~mask, num
1314/// to
1315/// icmp eq (and num, mask), 0
1316/// Where mask is a low bit mask.
1318 Value *Num;
1319 CmpPredicate Pred;
1320 const APInt *Mask, *Neg;
1321
1322 if (!match(&Cmp,
1323 m_c_ICmp(Pred, m_Value(Num),
1325 m_LowBitMask(Mask))),
1326 m_APInt(Neg))))))
1327 return nullptr;
1328
1329 if (*Neg != ~*Mask)
1330 return nullptr;
1331
1332 if (!ICmpInst::isEquality(Pred))
1333 return nullptr;
1334
1335 // Create new icmp eq (num & mask), 0
1336 auto *NewAnd = Builder.CreateAnd(Num, *Mask);
1337 auto *Zero = Constant::getNullValue(Num->getType());
1338
1339 return new ICmpInst(Pred, NewAnd, Zero);
1340}
1341
1342/// Fold icmp Pred X, C.
1343/// TODO: This code structure does not make sense. The saturating add fold
1344/// should be moved to some other helper and extended as noted below (it is also
1345/// possible that code has been made unnecessary - do we canonicalize IR to
1346/// overflow/saturating intrinsics or not?).
1348 // Match the following pattern, which is a common idiom when writing
1349 // overflow-safe integer arithmetic functions. The source performs an addition
1350 // in wider type and explicitly checks for overflow using comparisons against
1351 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1352 //
1353 // TODO: This could probably be generalized to handle other overflow-safe
1354 // operations if we worked out the formulas to compute the appropriate magic
1355 // constants.
1356 //
1357 // sum = a + b
1358 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1359 CmpInst::Predicate Pred = Cmp.getPredicate();
1360 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1361 Value *A, *B;
1362 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1363 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1364 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1365 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1366 return Res;
1367
1368 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1370 if (!C)
1371 return nullptr;
1372
1373 if (auto *Phi = dyn_cast<PHINode>(Op0))
1374 if (all_of(Phi->operands(), IsaPred<Constant>)) {
1376 for (Value *V : Phi->incoming_values()) {
1377 Constant *Res =
1379 if (!Res)
1380 return nullptr;
1381 Ops.push_back(Res);
1382 }
1383 Builder.SetInsertPoint(Phi);
1384 PHINode *NewPhi = Builder.CreatePHI(Cmp.getType(), Phi->getNumOperands());
1385 for (auto [V, Pred] : zip(Ops, Phi->blocks()))
1386 NewPhi->addIncoming(V, Pred);
1387 return replaceInstUsesWith(Cmp, NewPhi);
1388 }
1389
1391 return R;
1392
1393 return nullptr;
1394}
1395
1396/// Canonicalize icmp instructions based on dominating conditions.
1398 // We already checked simple implication in InstSimplify, only handle complex
1399 // cases here.
1400 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1401 const APInt *C;
1402 if (!match(Y, m_APInt(C)))
1403 return nullptr;
1404
1405 CmpInst::Predicate Pred = Cmp.getPredicate();
1407
1408 auto handleDomCond = [&](ICmpInst::Predicate DomPred,
1409 const APInt *DomC) -> Instruction * {
1410 // We have 2 compares of a variable with constants. Calculate the constant
1411 // ranges of those compares to see if we can transform the 2nd compare:
1412 // DomBB:
1413 // DomCond = icmp DomPred X, DomC
1414 // br DomCond, CmpBB, FalseBB
1415 // CmpBB:
1416 // Cmp = icmp Pred X, C
1417 ConstantRange DominatingCR =
1418 ConstantRange::makeExactICmpRegion(DomPred, *DomC);
1419 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1420 ConstantRange Difference = DominatingCR.difference(CR);
1421 if (Intersection.isEmptySet())
1422 return replaceInstUsesWith(Cmp, Builder.getFalse());
1423 if (Difference.isEmptySet())
1424 return replaceInstUsesWith(Cmp, Builder.getTrue());
1425
1426 // Canonicalizing a sign bit comparison that gets used in a branch,
1427 // pessimizes codegen by generating branch on zero instruction instead
1428 // of a test and branch. So we avoid canonicalizing in such situations
1429 // because test and branch instruction has better branch displacement
1430 // than compare and branch instruction.
1431 bool UnusedBit;
1432 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1433 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1434 return nullptr;
1435
1436 // Avoid an infinite loop with min/max canonicalization.
1437 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1438 if (Cmp.hasOneUse() &&
1439 match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1440 return nullptr;
1441
1442 if (const APInt *EqC = Intersection.getSingleElement())
1443 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1444 if (const APInt *NeC = Difference.getSingleElement())
1445 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1446 return nullptr;
1447 };
1448
1449 for (CondBrInst *BI : DC.conditionsFor(X)) {
1450 CmpPredicate DomPred;
1451 const APInt *DomC;
1452 if (!match(BI->getCondition(),
1453 m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))))
1454 continue;
1455
1456 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1457 if (DT.dominates(Edge0, Cmp.getParent())) {
1458 if (auto *V = handleDomCond(DomPred, DomC))
1459 return V;
1460 } else {
1461 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1462 if (DT.dominates(Edge1, Cmp.getParent()))
1463 if (auto *V =
1464 handleDomCond(CmpInst::getInversePredicate(DomPred), DomC))
1465 return V;
1466 }
1467 }
1468
1469 return nullptr;
1470}
1471
1472/// Fold icmp (trunc X), C.
1474 TruncInst *Trunc,
1475 const APInt &C) {
1476 ICmpInst::Predicate Pred = Cmp.getPredicate();
1477 Value *X = Trunc->getOperand(0);
1478 Type *SrcTy = X->getType();
1479 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1480 SrcBits = SrcTy->getScalarSizeInBits();
1481
1482 // Match (icmp pred (trunc nuw/nsw X), C)
1483 // Which we can convert to (icmp pred X, (sext/zext C))
1484 if (shouldChangeType(Trunc->getType(), SrcTy)) {
1485 if (Trunc->hasNoSignedWrap())
1486 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.sext(SrcBits)));
1487 if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())
1488 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.zext(SrcBits)));
1489 }
1490
1491 if (C.isOne() && C.getBitWidth() > 1) {
1492 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1493 Value *V = nullptr;
1494 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1495 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1496 ConstantInt::get(V->getType(), 1));
1497 }
1498
1499 // TODO: Handle non-equality predicates.
1500 Value *Y;
1501 const APInt *Pow2;
1502 if (Cmp.isEquality() && match(X, m_Shl(m_Power2(Pow2), m_Value(Y))) &&
1503 DstBits > Pow2->logBase2()) {
1504 // (trunc (Pow2 << Y) to iN) == 0 --> Y u>= N - log2(Pow2)
1505 // (trunc (Pow2 << Y) to iN) != 0 --> Y u< N - log2(Pow2)
1506 // iff N > log2(Pow2)
1507 if (C.isZero()) {
1508 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1509 return new ICmpInst(NewPred, Y,
1510 ConstantInt::get(SrcTy, DstBits - Pow2->logBase2()));
1511 }
1512 // (trunc (Pow2 << Y) to iN) == 2**C --> Y == C - log2(Pow2)
1513 // (trunc (Pow2 << Y) to iN) != 2**C --> Y != C - log2(Pow2)
1514 if (C.isPowerOf2())
1515 return new ICmpInst(
1516 Pred, Y, ConstantInt::get(SrcTy, C.logBase2() - Pow2->logBase2()));
1517 }
1518
1519 if (Cmp.isEquality() && (Trunc->hasOneUse() || Trunc->hasNoUnsignedWrap())) {
1520 // Canonicalize to a mask and wider compare if the wide type is suitable:
1521 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1522 if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1523 Constant *Mask =
1524 ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1525 Value *And = Trunc->hasNoUnsignedWrap() ? X : Builder.CreateAnd(X, Mask);
1526 Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1527 return new ICmpInst(Pred, And, WideC);
1528 }
1529
1530 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1531 // of the high bits truncated out of x are known.
1533
1534 // If all the high bits are known, we can do this xform.
1535 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1536 // Pull in the high bits from known-ones set.
1537 APInt NewRHS = C.zext(SrcBits);
1538 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1539 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1540 }
1541 }
1542
1543 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1544 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1545 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1546 Value *ShOp;
1547 uint64_t ShAmt;
1548 bool TrueIfSigned;
1549 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1550 match(X, m_Shr(m_Value(ShOp), m_ConstantInt(ShAmt))) &&
1551 DstBits == SrcBits - ShAmt) {
1552 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1554 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1556 }
1557
1558 return nullptr;
1559}
1560
1561/// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
1562/// Fold icmp (trunc nuw/nsw X), (zext/sext Y).
1565 const SimplifyQuery &Q) {
1566 Value *X, *Y;
1567 CmpPredicate Pred;
1568 bool YIsSExt = false;
1569 // Try to match icmp (trunc X), (trunc Y)
1570 if (match(&Cmp, m_ICmp(Pred, m_Trunc(m_Value(X)), m_Trunc(m_Value(Y))))) {
1571 unsigned NoWrapFlags = cast<TruncInst>(Cmp.getOperand(0))->getNoWrapKind() &
1572 cast<TruncInst>(Cmp.getOperand(1))->getNoWrapKind();
1573 if (Cmp.isSigned()) {
1574 // For signed comparisons, both truncs must be nsw.
1575 if (!(NoWrapFlags & TruncInst::NoSignedWrap))
1576 return nullptr;
1577 } else {
1578 // For unsigned and equality comparisons, either both must be nuw or
1579 // both must be nsw, we don't care which.
1580 if (!NoWrapFlags)
1581 return nullptr;
1582 }
1583
1584 if (X->getType() != Y->getType() &&
1585 (!Cmp.getOperand(0)->hasOneUse() || !Cmp.getOperand(1)->hasOneUse()))
1586 return nullptr;
1587 if (!isDesirableIntType(X->getType()->getScalarSizeInBits()) &&
1588 isDesirableIntType(Y->getType()->getScalarSizeInBits())) {
1589 std::swap(X, Y);
1590 Pred = Cmp.getSwappedPredicate(Pred);
1591 }
1592 YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);
1593 }
1594 // Try to match icmp (trunc nuw X), (zext Y)
1595 else if (!Cmp.isSigned() &&
1596 match(&Cmp, m_c_ICmp(Pred, m_NUWTrunc(m_Value(X)),
1597 m_OneUse(m_ZExt(m_Value(Y)))))) {
1598 // Can fold trunc nuw + zext for unsigned and equality predicates.
1599 }
1600 // Try to match icmp (trunc nsw X), (sext Y)
1601 else if (match(&Cmp, m_c_ICmp(Pred, m_NSWTrunc(m_Value(X)),
1603 // Can fold trunc nsw + zext/sext for all predicates.
1604 YIsSExt =
1605 isa<SExtInst>(Cmp.getOperand(0)) || isa<SExtInst>(Cmp.getOperand(1));
1606 } else
1607 return nullptr;
1608
1609 Type *TruncTy = Cmp.getOperand(0)->getType();
1610 unsigned TruncBits = TruncTy->getScalarSizeInBits();
1611
1612 // If this transform will end up changing from desirable types -> undesirable
1613 // types skip it.
1614 if (isDesirableIntType(TruncBits) &&
1615 !isDesirableIntType(X->getType()->getScalarSizeInBits()))
1616 return nullptr;
1617
1618 Value *NewY = Builder.CreateIntCast(Y, X->getType(), YIsSExt);
1619 return new ICmpInst(Pred, X, NewY);
1620}
1621
1622/// Fold icmp (xor X, Y), C.
1625 const APInt &C) {
1626 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1627 return I;
1628
1629 Value *X = Xor->getOperand(0);
1630 Value *Y = Xor->getOperand(1);
1631 const APInt *XorC;
1632 if (!match(Y, m_APInt(XorC)))
1633 return nullptr;
1634
1635 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1636 // fold the xor.
1637 ICmpInst::Predicate Pred = Cmp.getPredicate();
1638 bool TrueIfSigned = false;
1639 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1640
1641 // If the sign bit of the XorCst is not set, there is no change to
1642 // the operation, just stop using the Xor.
1643 if (!XorC->isNegative())
1644 return replaceOperand(Cmp, 0, X);
1645
1646 // Emit the opposite comparison.
1647 if (TrueIfSigned)
1648 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1649 ConstantInt::getAllOnesValue(X->getType()));
1650 else
1651 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1652 ConstantInt::getNullValue(X->getType()));
1653 }
1654
1655 if (Xor->hasOneUse()) {
1656 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1657 if (!Cmp.isEquality() && XorC->isSignMask()) {
1658 Pred = Cmp.getFlippedSignednessPredicate();
1659 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1660 }
1661
1662 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1663 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1664 Pred = Cmp.getFlippedSignednessPredicate();
1665 Pred = Cmp.getSwappedPredicate(Pred);
1666 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1667 }
1668 }
1669
1670 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1671 if (Pred == ICmpInst::ICMP_UGT) {
1672 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1673 if (*XorC == ~C && (C + 1).isPowerOf2())
1674 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1675 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1676 if (*XorC == C && (C + 1).isPowerOf2())
1677 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1678 }
1679 if (Pred == ICmpInst::ICMP_ULT) {
1680 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1681 if (*XorC == -C && C.isPowerOf2())
1682 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1683 ConstantInt::get(X->getType(), ~C));
1684 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1685 if (*XorC == C && (-C).isPowerOf2())
1686 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1687 ConstantInt::get(X->getType(), ~C));
1688 }
1689 return nullptr;
1690}
1691
1692/// For power-of-2 C:
1693/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1694/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1697 const APInt &C) {
1698 CmpInst::Predicate Pred = Cmp.getPredicate();
1699 APInt PowerOf2;
1700 if (Pred == ICmpInst::ICMP_ULT)
1701 PowerOf2 = C;
1702 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1703 PowerOf2 = C + 1;
1704 else
1705 return nullptr;
1706 if (!PowerOf2.isPowerOf2())
1707 return nullptr;
1708 Value *X;
1709 const APInt *ShiftC;
1711 m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1712 return nullptr;
1713 uint64_t Shift = ShiftC->getLimitedValue();
1714 Type *XType = X->getType();
1715 if (Shift == 0 || PowerOf2.isMinSignedValue())
1716 return nullptr;
1717 Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1718 APInt Bound =
1719 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1720 return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1721}
1722
1723/// Fold icmp (and (sh X, Y), C2), C1.
1726 const APInt &C1,
1727 const APInt &C2) {
1728 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1729 if (!Shift || !Shift->isShift())
1730 return nullptr;
1731
1732 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1733 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1734 // code produced by the clang front-end, for bitfield access.
1735 // This seemingly simple opportunity to fold away a shift turns out to be
1736 // rather complicated. See PR17827 for details.
1737 unsigned ShiftOpcode = Shift->getOpcode();
1738 bool IsShl = ShiftOpcode == Instruction::Shl;
1739 const APInt *C3;
1740 if (match(Shift->getOperand(1), m_APInt(C3))) {
1741 APInt NewAndCst, NewCmpCst;
1742 bool AnyCmpCstBitsShiftedOut;
1743 if (ShiftOpcode == Instruction::Shl) {
1744 // For a left shift, we can fold if the comparison is not signed. We can
1745 // also fold a signed comparison if the mask value and comparison value
1746 // are not negative. These constraints may not be obvious, but we can
1747 // prove that they are correct using an SMT solver.
1748 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1749 return nullptr;
1750
1751 NewCmpCst = C1.lshr(*C3);
1752 NewAndCst = C2.lshr(*C3);
1753 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1754 } else if (ShiftOpcode == Instruction::LShr) {
1755 // For a logical right shift, we can fold if the comparison is not signed.
1756 // We can also fold a signed comparison if the shifted mask value and the
1757 // shifted comparison value are not negative. These constraints may not be
1758 // obvious, but we can prove that they are correct using an SMT solver.
1759 NewCmpCst = C1.shl(*C3);
1760 NewAndCst = C2.shl(*C3);
1761 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1762 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1763 return nullptr;
1764 } else {
1765 // For an arithmetic shift, check that both constants don't use (in a
1766 // signed sense) the top bits being shifted out.
1767 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1768 NewCmpCst = C1.shl(*C3);
1769 NewAndCst = C2.shl(*C3);
1770 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1771 if (NewAndCst.ashr(*C3) != C2)
1772 return nullptr;
1773 }
1774
1775 if (AnyCmpCstBitsShiftedOut) {
1776 // If we shifted bits out, the fold is not going to work out. As a
1777 // special case, check to see if this means that the result is always
1778 // true or false now.
1779 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1780 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1781 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1782 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1783 } else {
1784 Value *NewAnd = Builder.CreateAnd(
1785 Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1786 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1787 ConstantInt::get(And->getType(), NewCmpCst));
1788 }
1789 }
1790
1791 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1792 // preferable because it allows the C2 << Y expression to be hoisted out of a
1793 // loop if Y is invariant and X is not.
1794 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1795 !Shift->isArithmeticShift() &&
1796 ((!IsShl && C2.isOne()) || !isa<Constant>(Shift->getOperand(0)))) {
1797 // Compute C2 << Y.
1798 Value *NewShift =
1799 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1800 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1801
1802 // Compute X & (C2 << Y).
1803 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1804 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1805 }
1806
1807 return nullptr;
1808}
1809
1810/// Fold icmp (and X, C2), C1.
1813 const APInt &C1) {
1814 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1815
1816 // icmp ne (and X, 1), 0 --> trunc X to i1
1817 if (isICMP_NE && C1.isZero() && match(And->getOperand(1), m_One()))
1818 return new TruncInst(And->getOperand(0), Cmp.getType());
1819
1820 const APInt *C2;
1821 Value *X;
1822 if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1823 return nullptr;
1824
1825 // (and X, highmask) s> [0, ~highmask] --> X s> ~highmask
1826 if (Cmp.getPredicate() == ICmpInst::ICMP_SGT && C1.ule(~*C2) &&
1827 C2->isNegatedPowerOf2())
1828 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1829 ConstantInt::get(X->getType(), ~*C2));
1830 // (and X, highmask) s< [1, -highmask] --> X s< -highmask
1831 if (Cmp.getPredicate() == ICmpInst::ICMP_SLT && !C1.isSignMask() &&
1832 (C1 - 1).ule(~*C2) && C2->isNegatedPowerOf2() && !C2->isSignMask())
1833 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1834 ConstantInt::get(X->getType(), -*C2));
1835
1836 // Don't perform the following transforms if the AND has multiple uses
1837 if (!And->hasOneUse())
1838 return nullptr;
1839
1840 if (Cmp.isEquality() && C1.isZero()) {
1841 // Restrict this fold to single-use 'and' (PR10267).
1842 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1843 if (C2->isSignMask()) {
1844 Constant *Zero = Constant::getNullValue(X->getType());
1845 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1846 return new ICmpInst(NewPred, X, Zero);
1847 }
1848
1849 APInt NewC2 = *C2;
1850 KnownBits Know = computeKnownBits(And->getOperand(0), And);
1851 // Set high zeros of C2 to allow matching negated power-of-2.
1852 NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
1853 Know.countMinLeadingZeros());
1854
1855 // Restrict this fold only for single-use 'and' (PR10267).
1856 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1857 if (NewC2.isNegatedPowerOf2()) {
1858 Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1859 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1860 return new ICmpInst(NewPred, X, NegBOC);
1861 }
1862 }
1863
1864 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1865 // the input width without changing the value produced, eliminate the cast:
1866 //
1867 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1868 //
1869 // We can do this transformation if the constants do not have their sign bits
1870 // set or if it is an equality comparison. Extending a relational comparison
1871 // when we're checking the sign bit would not work.
1872 Value *W;
1873 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1874 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1875 // TODO: Is this a good transform for vectors? Wider types may reduce
1876 // throughput. Should this transform be limited (even for scalars) by using
1877 // shouldChangeType()?
1878 if (!Cmp.getType()->isVectorTy()) {
1879 Type *WideType = W->getType();
1880 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1881 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1882 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1883 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1884 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1885 }
1886 }
1887
1888 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1889 return I;
1890
1891 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1892 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1893 //
1894 // iff pred isn't signed
1895 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1896 match(And->getOperand(1), m_One())) {
1897 Constant *One = cast<Constant>(And->getOperand(1));
1898 Value *Or = And->getOperand(0);
1899 Value *A, *B, *LShr;
1900 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1901 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1902 unsigned UsesRemoved = 0;
1903 if (And->hasOneUse())
1904 ++UsesRemoved;
1905 if (Or->hasOneUse())
1906 ++UsesRemoved;
1907 if (LShr->hasOneUse())
1908 ++UsesRemoved;
1909
1910 // Compute A & ((1 << B) | 1)
1911 unsigned RequireUsesRemoved = match(B, m_ImmConstant()) ? 1 : 3;
1912 if (UsesRemoved >= RequireUsesRemoved) {
1913 Value *NewOr =
1914 Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1915 /*HasNUW=*/true),
1916 One, Or->getName());
1917 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1918 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1919 }
1920 }
1921 }
1922
1923 // (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->
1924 // llvm.is.fpclass(X, fcInf|fcNan)
1925 // (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->
1926 // llvm.is.fpclass(X, ~(fcInf|fcNan))
1927 // (icmp eq (and (bitcast X to int), ExponentMask), 0) -->
1928 // llvm.is.fpclass(X, fcSubnormal|fcZero)
1929 // (icmp ne (and (bitcast X to int), ExponentMask), 0) -->
1930 // llvm.is.fpclass(X, ~(fcSubnormal|fcZero))
1931 Value *V;
1932 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1933 Attribute::NoImplicitFloat) &&
1934 Cmp.isEquality() &&
1936 Type *FPType = V->getType()->getScalarType();
1937 if (FPType->isIEEELikeFPTy() && (C1.isZero() || C1 == *C2)) {
1938 APInt ExponentMask =
1939 APFloat::getInf(FPType->getFltSemantics()).bitcastToAPInt();
1940 if (*C2 == ExponentMask) {
1941 unsigned Mask = C1.isZero()
1944 if (isICMP_NE)
1945 Mask = ~Mask & fcAllFlags;
1946 return replaceInstUsesWith(Cmp, Builder.createIsFPClass(V, Mask));
1947 }
1948 }
1949 }
1950
1951 return nullptr;
1952}
1953
1954/// Fold icmp (and X, Y), C.
1957 const APInt &C) {
1958 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1959 return I;
1960
1961 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1962 bool TrueIfNeg;
1963 if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1964 // ((X - 1) & ~X) < 0 --> X == 0
1965 // ((X - 1) & ~X) >= 0 --> X != 0
1966 Value *X;
1967 if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1968 match(And->getOperand(1), m_Not(m_Specific(X)))) {
1969 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1970 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1971 }
1972 // (X & -X) < 0 --> X == MinSignedC
1973 // (X & -X) > -1 --> X != MinSignedC
1974 if (match(And, m_c_And(m_Neg(m_Value(X)), m_Deferred(X)))) {
1975 Constant *MinSignedC = ConstantInt::get(
1976 X->getType(),
1977 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits()));
1978 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1979 return new ICmpInst(NewPred, X, MinSignedC);
1980 }
1981 }
1982
1983 // TODO: These all require that Y is constant too, so refactor with the above.
1984
1985 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1986 Value *X = And->getOperand(0);
1987 Value *Y = And->getOperand(1);
1988 if (auto *C2 = dyn_cast<ConstantInt>(Y))
1989 if (auto *LI = dyn_cast<LoadInst>(X))
1990 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1991 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(LI, GEP, Cmp, C2))
1992 return Res;
1993
1994 if (!Cmp.isEquality())
1995 return nullptr;
1996
1997 // (X & -X) == 0 --> X == 0
1998 // (X & -X) != 0 --> X != 0
1999 // (X & -X) == 1 --> trunc X to i1
2000 // (X & -X) != 1 --> !(trunc X to i1)
2001 // Cmp is == or != by the check above.
2002 Value *MatchedX;
2003 // Match X & -X in either operand order.
2004 if (C.getBitWidth() > 1 && (C.isZero() || C.isOne()) &&
2005 match(And, m_c_And(m_Neg(m_Value(MatchedX)), m_Deferred(MatchedX)))) {
2006 // Preserve the predicate: (X & -X) ==/!= 0 --> X ==/!= 0.
2007 if (C.isZero())
2008 return new ICmpInst(Pred, MatchedX, Cmp.getOperand(1));
2009
2010 // (X & -X) == 1 iff the low bit of X is set.
2011 if (Pred == CmpInst::ICMP_EQ)
2012 return new TruncInst(MatchedX, Cmp.getType());
2013
2014 // The remaining case needs a trunc and not. Require the original and
2015 // to become dead to avoid increasing the instruction count.
2016 if (And->hasOneUse()) {
2017 Value *Trunc = Builder.CreateTrunc(MatchedX, Cmp.getType());
2018 return BinaryOperator::CreateNot(Trunc);
2019 }
2020 }
2021
2022 // X & -C == -C -> X > u ~C
2023 // X & -C != -C -> X <= u ~C
2024 // iff C is a power of 2
2025 if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
2026 auto NewPred =
2028 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
2029 }
2030
2031 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
2032 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
2033 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
2034 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
2036 X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
2037 Value *TruncY = Builder.CreateTrunc(Y, X->getType());
2038 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
2039 Value *And = Builder.CreateAnd(TruncY, X);
2041 }
2042 return BinaryOperator::CreateAnd(TruncY, X);
2043 }
2044
2045 // (icmp eq/ne (and (shl -1, X), Y), 0)
2046 // -> (icmp eq/ne (lshr Y, X), 0)
2047 // We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems
2048 // highly unlikely the non-zero case will ever show up in code.
2049 if (C.isZero() &&
2051 m_Value(Y))))) {
2052 Value *LShr = Builder.CreateLShr(Y, X);
2053 return new ICmpInst(Pred, LShr, Constant::getNullValue(LShr->getType()));
2054 }
2055
2056 // (icmp eq/ne (and (add A, Addend), Msk), C)
2057 // -> (icmp eq/ne (and A, Msk), (and (sub C, Addend), Msk))
2058 {
2059 Value *A;
2060 const APInt *Addend, *Msk;
2062 m_LowBitMask(Msk)))) &&
2063 C.ule(*Msk)) {
2064 APInt NewComperand = (C - *Addend) & *Msk;
2065 Value *MaskA = Builder.CreateAnd(A, ConstantInt::get(A->getType(), *Msk));
2066 return new ICmpInst(Pred, MaskA,
2067 ConstantInt::get(MaskA->getType(), NewComperand));
2068 }
2069 }
2070
2071 return nullptr;
2072}
2073
2074/// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
2076 InstCombiner::BuilderTy &Builder) {
2077 // Are we using xors or subs to bitwise check for a pair or pairs of
2078 // (in)equalities? Convert to a shorter form that has more potential to be
2079 // folded even further.
2080 // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
2081 // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
2082 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
2083 // (X1 == X2) && (X3 == X4) && (X5 == X6)
2084 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
2085 // (X1 != X2) || (X3 != X4) || (X5 != X6)
2087 SmallVector<Value *, 16> WorkList(1, Or);
2088
2089 while (!WorkList.empty()) {
2090 auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
2091 Value *Lhs, *Rhs;
2092
2093 if (match(OrOperatorArgument,
2094 m_OneUse(m_Xor(m_Value(Lhs), m_Value(Rhs))))) {
2095 CmpValues.emplace_back(Lhs, Rhs);
2096 return;
2097 }
2098
2099 if (match(OrOperatorArgument,
2100 m_OneUse(m_Sub(m_Value(Lhs), m_Value(Rhs))))) {
2101 CmpValues.emplace_back(Lhs, Rhs);
2102 return;
2103 }
2104
2105 WorkList.push_back(OrOperatorArgument);
2106 };
2107
2108 Value *CurrentValue = WorkList.pop_back_val();
2109 Value *OrOperatorLhs, *OrOperatorRhs;
2110
2111 if (!match(CurrentValue,
2112 m_Or(m_Value(OrOperatorLhs), m_Value(OrOperatorRhs)))) {
2113 return nullptr;
2114 }
2115
2116 MatchOrOperatorArgument(OrOperatorRhs);
2117 MatchOrOperatorArgument(OrOperatorLhs);
2118 }
2119
2120 ICmpInst::Predicate Pred = Cmp.getPredicate();
2121 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2122 Value *LhsCmp = Builder.CreateICmp(Pred, CmpValues.rbegin()->first,
2123 CmpValues.rbegin()->second);
2124
2125 for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
2126 Value *RhsCmp = Builder.CreateICmp(Pred, It->first, It->second);
2127 LhsCmp = Builder.CreateBinOp(BOpc, LhsCmp, RhsCmp);
2128 }
2129
2130 return LhsCmp;
2131}
2132
2133/// Fold icmp (or X, Y), C.
2136 const APInt &C) {
2137 ICmpInst::Predicate Pred = Cmp.getPredicate();
2138 if (C.isOne()) {
2139 // icmp slt signum(V) 1 --> icmp slt V, 1
2140 Value *V = nullptr;
2141 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
2142 return new ICmpInst(ICmpInst::ICMP_SLT, V,
2143 ConstantInt::get(V->getType(), 1));
2144 }
2145
2146 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
2147
2148 // (icmp eq/ne (or disjoint x, C0), C1)
2149 // -> (icmp eq/ne x, C0^C1)
2150 if (Cmp.isEquality() && match(OrOp1, m_ImmConstant()) &&
2151 cast<PossiblyDisjointInst>(Or)->isDisjoint()) {
2152 Value *NewC =
2153 Builder.CreateXor(OrOp1, ConstantInt::get(OrOp1->getType(), C));
2154 return new ICmpInst(Pred, OrOp0, NewC);
2155 }
2156
2157 const APInt *MaskC;
2158 if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
2159 if (*MaskC == C && (C + 1).isPowerOf2()) {
2160 // X | C == C --> X <=u C
2161 // X | C != C --> X >u C
2162 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
2164 return new ICmpInst(Pred, OrOp0, OrOp1);
2165 }
2166
2167 // More general: canonicalize 'equality with set bits mask' to
2168 // 'equality with clear bits mask'.
2169 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2170 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2171 if (Or->hasOneUse()) {
2172 Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
2173 Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
2174 return new ICmpInst(Pred, And, NewC);
2175 }
2176 }
2177
2178 // (X | (X-1)) s< 0 --> X s< 1
2179 // (X | (X-1)) s> -1 --> X s> 0
2180 Value *X;
2181 bool TrueIfSigned;
2182 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
2184 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2185 Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
2186 return new ICmpInst(NewPred, X, NewC);
2187 }
2188
2189 const APInt *OrC;
2190 // icmp(X | OrC, C) --> icmp(X, 0)
2191 if (C.isNonNegative() && match(Or, m_Or(m_Value(X), m_APInt(OrC)))) {
2192 switch (Pred) {
2193 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2194 case ICmpInst::ICMP_SLT:
2195 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2196 case ICmpInst::ICMP_SGE:
2197 if (OrC->sge(C))
2198 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2199 break;
2200 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2201 case ICmpInst::ICMP_SLE:
2202 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2203 case ICmpInst::ICMP_SGT:
2204 if (OrC->sgt(C))
2206 ConstantInt::getNullValue(X->getType()));
2207 break;
2208 default:
2209 break;
2210 }
2211 }
2212
2213 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2214 return nullptr;
2215
2216 Value *P, *Q;
2218 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2219 // -> and (icmp eq P, null), (icmp eq Q, null).
2220 Value *CmpP =
2221 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
2222 Value *CmpQ =
2223 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
2224 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2225 return BinaryOperator::Create(BOpc, CmpP, CmpQ);
2226 }
2227
2228 if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2229 return replaceInstUsesWith(Cmp, V);
2230
2231 return nullptr;
2232}
2233
2234/// Fold icmp (mul X, Y), C.
2237 const APInt &C) {
2238 ICmpInst::Predicate Pred = Cmp.getPredicate();
2239 Type *MulTy = Mul->getType();
2240 Value *X = Mul->getOperand(0);
2241
2242 // If comparing a square with a constant, try simplifying to comparing square
2243 // roots.
2244 if (X == Mul->getOperand(1) && !Cmp.isSigned()) {
2245 APInt R = C.sqrtFloor();
2246 bool IsSqr = C == R * R;
2247
2248 // X * X eq/ne C
2249 if (Cmp.isEquality() &&
2250 (Mul->hasNoUnsignedWrap() || (Mul->hasNoSignedWrap() && C.isZero()))) {
2251
2252 // If constant is not a square, eq/ne is false/true respectively
2253 if (!IsSqr)
2254 return replaceInstUsesWith(
2255 Cmp,
2256 ConstantInt::getBool(Cmp.getType(), Pred == ICmpInst::ICMP_NE));
2257
2258 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2259 }
2260
2261 // If the multiply does not wrap
2262 // X * X pred C --> X pred R
2263 if (Mul->hasNoUnsignedWrap()) {
2264
2265 if (IsSqr)
2266 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2267
2268 // If C is not a square, we use floor/ceil of sqrt(C).
2269 //
2270 // If LT or LE, we need R to be an overestimate of sqrt(C),
2271 // then use the strict predicate (LT->LT, LE->LT).
2272 //
2273 // If GT or GE, we need R to be an underestimate of sqrt(C),
2274 // then use the strict predicate (GT->GT, GE->GT).
2275 //
2276 // R is already an underestimate of sqrt(C) due to sqrtFloor.
2277 if (ICmpInst::isLT(Pred) || ICmpInst::isLE(Pred))
2278 ++R;
2279
2280 return new ICmpInst(Cmp.getStrictPredicate(), X,
2281 ConstantInt::get(MulTy, R));
2282 }
2283 }
2284
2285 const APInt *MulC;
2286 if (!match(Mul->getOperand(1), m_APInt(MulC)))
2287 return nullptr;
2288
2289 // If this is a test of the sign bit and the multiply is sign-preserving with
2290 // a constant operand, use the multiply LHS operand instead:
2291 // (X * +MulC) < 0 --> X < 0
2292 // (X * -MulC) < 0 --> X > 0
2293 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2294 if (MulC->isNegative())
2295 Pred = ICmpInst::getSwappedPredicate(Pred);
2296 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2297 }
2298
2299 if (MulC->isZero())
2300 return nullptr;
2301
2302 // If the multiply does not wrap or the constant is odd, try to divide the
2303 // compare constant by the multiplication factor.
2304 if (Cmp.isEquality()) {
2305 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2306 if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
2307 Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
2308 return new ICmpInst(Pred, X, NewC);
2309 }
2310
2311 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2312 // correct to transform if MulC * N == C including overflow. I.e with i8
2313 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2314 // miss that case.
2315 if (C.urem(*MulC).isZero()) {
2316 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2317 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2318 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2319 Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
2320 return new ICmpInst(Pred, X, NewC);
2321 }
2322 }
2323 }
2324
2325 // With a matching no-overflow guarantee, fold the constants:
2326 // (X * MulC) < C --> X < (C / MulC)
2327 // (X * MulC) > C --> X > (C / MulC)
2328 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2329 Constant *NewC = nullptr;
2330 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2331 // MININT / -1 --> overflow.
2332 if (C.isMinSignedValue() && MulC->isAllOnes())
2333 return nullptr;
2334 if (MulC->isNegative())
2335 Pred = ICmpInst::getSwappedPredicate(Pred);
2336
2337 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2338 NewC = ConstantInt::get(
2340 } else {
2341 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2342 "Unexpected predicate");
2343 NewC = ConstantInt::get(
2345 }
2346 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2347 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2348 NewC = ConstantInt::get(
2350 } else {
2351 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2352 "Unexpected predicate");
2353 NewC = ConstantInt::get(
2355 }
2356 }
2357
2358 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2359}
2360
2361/// Fold icmp (shl nuw C2, Y), C.
2363 const APInt &C) {
2364 Value *Y;
2365 const APInt *C2;
2366 if (!match(Shl, m_NUWShl(m_APInt(C2), m_Value(Y))))
2367 return nullptr;
2368
2369 Type *ShiftType = Shl->getType();
2370 unsigned TypeBits = C.getBitWidth();
2371 ICmpInst::Predicate Pred = Cmp.getPredicate();
2372 if (Cmp.isUnsigned()) {
2373 if (C2->isZero() || C2->ugt(C))
2374 return nullptr;
2375 APInt Div, Rem;
2376 APInt::udivrem(C, *C2, Div, Rem);
2377 bool CIsPowerOf2 = Rem.isZero() && Div.isPowerOf2();
2378
2379 // (1 << Y) pred C -> Y pred Log2(C)
2380 if (!CIsPowerOf2) {
2381 // (1 << Y) < 30 -> Y <= 4
2382 // (1 << Y) <= 30 -> Y <= 4
2383 // (1 << Y) >= 30 -> Y > 4
2384 // (1 << Y) > 30 -> Y > 4
2385 if (Pred == ICmpInst::ICMP_ULT)
2386 Pred = ICmpInst::ICMP_ULE;
2387 else if (Pred == ICmpInst::ICMP_UGE)
2388 Pred = ICmpInst::ICMP_UGT;
2389 }
2390
2391 unsigned CLog2 = Div.logBase2();
2392 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2393 } else if (Cmp.isSigned() && C2->isOne()) {
2394 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2395 // (1 << Y) > 0 -> Y != 31
2396 // (1 << Y) > C -> Y != 31 if C is negative.
2397 if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
2398 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2399
2400 // (1 << Y) < 0 -> Y == 31
2401 // (1 << Y) < 1 -> Y == 31
2402 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2403 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2404 if (Pred == ICmpInst::ICMP_SLT && (C - 1).sle(0))
2405 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2406 }
2407
2408 return nullptr;
2409}
2410
2411/// Fold icmp (shl X, Y), C.
2413 BinaryOperator *Shl,
2414 const APInt &C) {
2415 const APInt *ShiftVal;
2416 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2417 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2418
2419 ICmpInst::Predicate Pred = Cmp.getPredicate();
2420 // (icmp pred (shl nuw&nsw X, Y), Csle0)
2421 // -> (icmp pred X, Csle0)
2422 //
2423 // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2424 // so X's must be what is used.
2425 if (C.sle(0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2426 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2427
2428 // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2429 // -> (icmp eq/ne X, 0)
2430 if (ICmpInst::isEquality(Pred) && C.isZero() &&
2431 (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2432 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2433
2434 // (icmp slt (shl nsw X, Y), 0/1)
2435 // -> (icmp slt X, 0/1)
2436 // (icmp sgt (shl nsw X, Y), 0/-1)
2437 // -> (icmp sgt X, 0/-1)
2438 //
2439 // NB: sge/sle with a constant will canonicalize to sgt/slt.
2440 if (Shl->hasNoSignedWrap() &&
2441 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2442 if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2443 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2444
2445 const APInt *ShiftAmt;
2446 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2447 return foldICmpShlLHSC(Cmp, Shl, C);
2448
2449 // Check that the shift amount is in range. If not, don't perform undefined
2450 // shifts. When the shift is visited, it will be simplified.
2451 unsigned TypeBits = C.getBitWidth();
2452 if (ShiftAmt->uge(TypeBits))
2453 return nullptr;
2454
2455 Value *X = Shl->getOperand(0);
2456 Type *ShType = Shl->getType();
2457
2458 // NSW guarantees that we are only shifting out sign bits from the high bits,
2459 // so we can ASHR the compare constant without needing a mask and eliminate
2460 // the shift.
2461 if (Shl->hasNoSignedWrap()) {
2462 if (Pred == ICmpInst::ICMP_SGT) {
2463 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2464 APInt ShiftedC = C.ashr(*ShiftAmt);
2465 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2466 }
2467 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2468 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2469 APInt ShiftedC = C.ashr(*ShiftAmt);
2470 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2471 }
2472 if (Pred == ICmpInst::ICMP_SLT) {
2473 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2474 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2475 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2476 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2477 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2478 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2479 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2480 }
2481 }
2482
2483 // NUW guarantees that we are only shifting out zero bits from the high bits,
2484 // so we can LSHR the compare constant without needing a mask and eliminate
2485 // the shift.
2486 if (Shl->hasNoUnsignedWrap()) {
2487 if (Pred == ICmpInst::ICMP_UGT) {
2488 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2489 APInt ShiftedC = C.lshr(*ShiftAmt);
2490 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2491 }
2492 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2493 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2494 APInt ShiftedC = C.lshr(*ShiftAmt);
2495 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2496 }
2497 if (Pred == ICmpInst::ICMP_ULT) {
2498 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2499 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2500 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2501 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2502 assert(C.ugt(0) && "ult 0 should have been eliminated");
2503 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2504 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2505 }
2506 }
2507
2508 if (Cmp.isEquality() && Shl->hasOneUse()) {
2509 // Strength-reduce the shift into an 'and'.
2510 Constant *Mask = ConstantInt::get(
2511 ShType,
2512 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2513 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2514 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2515 return new ICmpInst(Pred, And, LShrC);
2516 }
2517
2518 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2519 bool TrueIfSigned = false;
2520 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2521 // (X << 31) <s 0 --> (X & 1) != 0
2522 Constant *Mask = ConstantInt::get(
2523 ShType,
2524 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2525 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2526 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2527 And, Constant::getNullValue(ShType));
2528 }
2529
2530 // Simplify 'shl' inequality test into 'and' equality test.
2531 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2532 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2533 if ((C + 1).isPowerOf2() &&
2534 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2535 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2536 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2538 And, Constant::getNullValue(ShType));
2539 }
2540 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2541 if (C.isPowerOf2() &&
2542 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2543 Value *And =
2544 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2545 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2547 And, Constant::getNullValue(ShType));
2548 }
2549 }
2550
2551 // Transform (icmp pred iM (shl iM %v, N), C)
2552 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2553 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2554 // This enables us to get rid of the shift in favor of a trunc that may be
2555 // free on the target. It has the additional benefit of comparing to a
2556 // smaller constant that may be more target-friendly.
2557 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2558 if (Shl->hasOneUse() && Amt != 0 &&
2559 shouldChangeType(ShType->getScalarSizeInBits(), TypeBits - Amt)) {
2560 ICmpInst::Predicate CmpPred = Pred;
2561 APInt RHSC = C;
2562
2563 if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(CmpPred)) {
2564 // Try the flipped strictness predicate.
2565 // e.g.:
2566 // icmp ult i64 (shl X, 32), 8589934593 ->
2567 // icmp ule i64 (shl X, 32), 8589934592 ->
2568 // icmp ule i32 (trunc X, i32), 2 ->
2569 // icmp ult i32 (trunc X, i32), 3
2570 if (auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(
2571 Pred, ConstantInt::get(ShType->getContext(), C))) {
2572 CmpPred = FlippedStrictness->first;
2573 RHSC = cast<ConstantInt>(FlippedStrictness->second)->getValue();
2574 }
2575 }
2576
2577 if (RHSC.countr_zero() >= Amt) {
2578 Type *TruncTy = ShType->getWithNewBitWidth(TypeBits - Amt);
2579 Constant *NewC =
2580 ConstantInt::get(TruncTy, RHSC.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2581 return new ICmpInst(CmpPred,
2582 Builder.CreateTrunc(X, TruncTy, "", /*IsNUW=*/false,
2583 Shl->hasNoSignedWrap()),
2584 NewC);
2585 }
2586 }
2587
2588 return nullptr;
2589}
2590
2591/// Fold icmp ({al}shr X, Y), C.
2593 BinaryOperator *Shr,
2594 const APInt &C) {
2595 // An exact shr only shifts out zero bits, so:
2596 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2597 Value *X = Shr->getOperand(0);
2598 CmpInst::Predicate Pred = Cmp.getPredicate();
2599 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2600 return new ICmpInst(Pred, X, Cmp.getOperand(1));
2601
2602 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2603 const APInt *ShiftValC;
2604 if (match(X, m_APInt(ShiftValC))) {
2605 if (Cmp.isEquality())
2606 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2607
2608 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2609 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2610 bool TrueIfSigned;
2611 if (!IsAShr && ShiftValC->isNegative() &&
2612 isSignBitCheck(Pred, C, TrueIfSigned))
2613 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2614 Shr->getOperand(1),
2615 ConstantInt::getNullValue(X->getType()));
2616
2617 // If the shifted constant is a power-of-2, test the shift amount directly:
2618 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2619 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2620 if (!IsAShr && ShiftValC->isPowerOf2() &&
2621 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2622 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2623 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2624 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2625
2626 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2627 unsigned ShiftLZ = ShiftValC->countl_zero();
2628 Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2629 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2630 return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2631 }
2632 }
2633
2634 const APInt *ShiftAmtC;
2635 if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2636 return nullptr;
2637
2638 // Check that the shift amount is in range. If not, don't perform undefined
2639 // shifts. When the shift is visited it will be simplified.
2640 unsigned TypeBits = C.getBitWidth();
2641 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2642 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2643 return nullptr;
2644
2645 bool IsExact = Shr->isExact();
2646 Type *ShrTy = Shr->getType();
2647 // TODO: If we could guarantee that InstSimplify would handle all of the
2648 // constant-value-based preconditions in the folds below, then we could assert
2649 // those conditions rather than checking them. This is difficult because of
2650 // undef/poison (PR34838).
2651 if (IsAShr && Shr->hasOneUse()) {
2652 if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&
2653 (C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {
2654 // When C - 1 is a power of two and the transform can be legally
2655 // performed, prefer this form so the produced constant is close to a
2656 // power of two.
2657 // icmp slt/ult (ashr exact X, ShAmtC), C
2658 // --> icmp slt/ult X, (C - 1) << ShAmtC) + 1
2659 APInt ShiftedC = (C - 1).shl(ShAmtVal) + 1;
2660 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2661 }
2662 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2663 // When ShAmtC can be shifted losslessly:
2664 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2665 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2666 APInt ShiftedC = C.shl(ShAmtVal);
2667 if (ShiftedC.ashr(ShAmtVal) == C)
2668 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2669 }
2670 if (Pred == CmpInst::ICMP_SGT) {
2671 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2672 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2673 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2674 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2675 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2676 }
2677 if (Pred == CmpInst::ICMP_UGT) {
2678 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2679 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2680 // clause accounts for that pattern.
2681 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2682 if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2683 (C + 1).shl(ShAmtVal).isMinSignedValue())
2684 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2685 }
2686
2687 // If the compare constant has significant bits above the lowest sign-bit,
2688 // then convert an unsigned cmp to a test of the sign-bit:
2689 // (ashr X, ShiftC) u> C --> X s< 0
2690 // (ashr X, ShiftC) u< C --> X s> -1
2691 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2692 if (Pred == CmpInst::ICMP_UGT) {
2693 return new ICmpInst(CmpInst::ICMP_SLT, X,
2695 }
2696 if (Pred == CmpInst::ICMP_ULT) {
2697 return new ICmpInst(CmpInst::ICMP_SGT, X,
2699 }
2700 }
2701 } else if (!IsAShr) {
2702 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2703 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2704 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2705 APInt ShiftedC = C.shl(ShAmtVal);
2706 if (ShiftedC.lshr(ShAmtVal) == C)
2707 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2708 }
2709 if (Pred == CmpInst::ICMP_UGT) {
2710 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2711 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2712 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2713 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2714 }
2715 }
2716
2717 if (!Cmp.isEquality())
2718 return nullptr;
2719
2720 // Handle equality comparisons of shift-by-constant.
2721
2722 // If the comparison constant changes with the shift, the comparison cannot
2723 // succeed (bits of the comparison constant cannot match the shifted value).
2724 // This should be known by InstSimplify and already be folded to true/false.
2725 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2726 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2727 "Expected icmp+shr simplify did not occur.");
2728
2729 // If the bits shifted out are known zero, compare the unshifted value:
2730 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2731 if (Shr->isExact())
2732 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2733
2734 if (Shr->hasOneUse()) {
2735 // Canonicalize the shift into an 'and':
2736 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2737 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2738 Constant *Mask = ConstantInt::get(ShrTy, Val);
2739 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2740 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2741 }
2742
2743 return nullptr;
2744}
2745
2747 BinaryOperator *SRem,
2748 const APInt &C) {
2749 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2750 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT) {
2751 // Canonicalize unsigned predicates to signed:
2752 // (X s% DivisorC) u> C -> (X s% DivisorC) s< 0
2753 // iff (C s< 0 ? ~C : C) u>= abs(DivisorC)-1
2754 // (X s% DivisorC) u< C+1 -> (X s% DivisorC) s> -1
2755 // iff (C+1 s< 0 ? ~C : C) u>= abs(DivisorC)-1
2756
2757 const APInt *DivisorC;
2758 if (!match(SRem->getOperand(1), m_APInt(DivisorC)))
2759 return nullptr;
2760 if (DivisorC->isZero())
2761 return nullptr;
2762
2763 APInt NormalizedC = C;
2764 if (Pred == ICmpInst::ICMP_ULT) {
2765 assert(!NormalizedC.isZero() &&
2766 "ult X, 0 should have been simplified already.");
2767 --NormalizedC;
2768 }
2769 if (C.isNegative())
2770 NormalizedC.flipAllBits();
2771 if (!NormalizedC.uge(DivisorC->abs() - 1))
2772 return nullptr;
2773
2774 Type *Ty = SRem->getType();
2775 if (Pred == ICmpInst::ICMP_UGT)
2776 return new ICmpInst(ICmpInst::ICMP_SLT, SRem,
2778 return new ICmpInst(ICmpInst::ICMP_SGT, SRem,
2780 }
2781 // Match an 'is positive' or 'is negative' comparison of remainder by a
2782 // constant power-of-2 value:
2783 // (X % pow2C) sgt/slt 0
2784 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2785 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2786 return nullptr;
2787
2788 // TODO: The one-use check is standard because we do not typically want to
2789 // create longer instruction sequences, but this might be a special-case
2790 // because srem is not good for analysis or codegen.
2791 if (!SRem->hasOneUse())
2792 return nullptr;
2793
2794 const APInt *DivisorC;
2795 if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2796 return nullptr;
2797
2798 // For cmp_sgt/cmp_slt only zero valued C is handled.
2799 // For cmp_eq/cmp_ne only positive valued C is handled.
2800 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2801 !C.isZero()) ||
2802 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2803 !C.isStrictlyPositive()))
2804 return nullptr;
2805
2806 // Mask off the sign bit and the modulo bits (low-bits).
2807 Type *Ty = SRem->getType();
2808 APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
2809 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2810 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2811
2812 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2813 return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2814
2815 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2816 // bit is set. Example:
2817 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2818 if (Pred == ICmpInst::ICMP_SGT)
2820
2821 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2822 // bit is set. Example:
2823 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2824 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2825}
2826
2827/// Fold icmp (udiv X, Y), C.
2829 BinaryOperator *UDiv,
2830 const APInt &C) {
2831 ICmpInst::Predicate Pred = Cmp.getPredicate();
2832 Value *X = UDiv->getOperand(0);
2833 Value *Y = UDiv->getOperand(1);
2834 Type *Ty = UDiv->getType();
2835
2836 const APInt *C2;
2837 if (!match(X, m_APInt(C2)))
2838 return nullptr;
2839
2840 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2841
2842 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2843 if (Pred == ICmpInst::ICMP_UGT) {
2844 assert(!C.isMaxValue() &&
2845 "icmp ugt X, UINT_MAX should have been simplified already.");
2846 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2847 ConstantInt::get(Ty, C2->udiv(C + 1)));
2848 }
2849
2850 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2851 if (Pred == ICmpInst::ICMP_ULT) {
2852 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2853 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2854 ConstantInt::get(Ty, C2->udiv(C)));
2855 }
2856
2857 return nullptr;
2858}
2859
2860/// Fold icmp ({su}div X, Y), C.
2862 BinaryOperator *Div,
2863 const APInt &C) {
2864 ICmpInst::Predicate Pred = Cmp.getPredicate();
2865 Value *X = Div->getOperand(0);
2866 Value *Y = Div->getOperand(1);
2867 Type *Ty = Div->getType();
2868 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2869
2870 // If unsigned division and the compare constant is bigger than
2871 // UMAX/2 (negative), there's only one pair of values that satisfies an
2872 // equality check, so eliminate the division:
2873 // (X u/ Y) == C --> (X == C) && (Y == 1)
2874 // (X u/ Y) != C --> (X != C) || (Y != 1)
2875 // Similarly, if signed division and the compare constant is exactly SMIN:
2876 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2877 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2878 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2879 (!DivIsSigned || C.isMinSignedValue())) {
2880 Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2881 Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2882 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2883 return BinaryOperator::Create(Logic, XBig, YOne);
2884 }
2885
2886 // Fold: icmp pred ([us]div X, C2), C -> range test
2887 // Fold this div into the comparison, producing a range check.
2888 // Determine, based on the divide type, what the range is being
2889 // checked. If there is an overflow on the low or high side, remember
2890 // it, otherwise compute the range [low, hi) bounding the new value.
2891 // See: InsertRangeTest above for the kinds of replacements possible.
2892 const APInt *C2;
2893 if (!match(Y, m_APInt(C2)))
2894 return nullptr;
2895
2896 // FIXME: If the operand types don't match the type of the divide
2897 // then don't attempt this transform. The code below doesn't have the
2898 // logic to deal with a signed divide and an unsigned compare (and
2899 // vice versa). This is because (x /s C2) <s C produces different
2900 // results than (x /s C2) <u C or (x /u C2) <s C or even
2901 // (x /u C2) <u C. Simply casting the operands and result won't
2902 // work. :( The if statement below tests that condition and bails
2903 // if it finds it.
2904 // However, when the divisor is a positive constant and the dividend is
2905 // known non-negative, sdiv is equivalent to udiv, so we can lower
2906 // DivIsSigned and proceed through the unsigned path.
2907 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) {
2908 if (!DivIsSigned || !C2->isStrictlyPositive() ||
2909 !isKnownNonNegative(X, SQ.getWithInstruction(&Cmp)))
2910 return nullptr;
2911 DivIsSigned = false;
2912 }
2913
2914 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2915 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2916 // division-by-constant cases should be present, we can not assert that they
2917 // have happened before we reach this icmp instruction.
2918 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2919 return nullptr;
2920
2921 // Compute Prod = C * C2. We are essentially solving an equation of
2922 // form X / C2 = C. We solve for X by multiplying C2 and C.
2923 // By solving for X, we can turn this into a range check instead of computing
2924 // a divide.
2925 APInt Prod = C * *C2;
2926
2927 // Determine if the product overflows by seeing if the product is not equal to
2928 // the divide. Make sure we do the same kind of divide as in the LHS
2929 // instruction that we're folding.
2930 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2931
2932 // If the division is known to be exact, then there is no remainder from the
2933 // divide, so the covered range size is unit, otherwise it is the divisor.
2934 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2935
2936 // Figure out the interval that is being checked. For example, a comparison
2937 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2938 // Compute this interval based on the constants involved and the signedness of
2939 // the compare/divide. This computes a half-open interval, keeping track of
2940 // whether either value in the interval overflows. After analysis each
2941 // overflow variable is set to 0 if it's corresponding bound variable is valid
2942 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2943 int LoOverflow = 0, HiOverflow = 0;
2944 APInt LoBound, HiBound;
2945
2946 if (!DivIsSigned) { // udiv
2947 // e.g. X/5 op 3 --> [15, 20)
2948 LoBound = Prod;
2949 HiOverflow = LoOverflow = ProdOV;
2950 if (!HiOverflow) {
2951 // If this is not an exact divide, then many values in the range collapse
2952 // to the same result value.
2953 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2954 }
2955 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2956 if (C.isZero()) { // (X / pos) op 0
2957 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2958 LoBound = -(RangeSize - 1);
2959 HiBound = RangeSize;
2960 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2961 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2962 HiOverflow = LoOverflow = ProdOV;
2963 if (!HiOverflow)
2964 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2965 } else { // (X / pos) op neg
2966 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2967 HiBound = Prod + 1;
2968 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2969 if (!LoOverflow) {
2970 APInt DivNeg = -RangeSize;
2971 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2972 }
2973 }
2974 } else if (C2->isNegative()) { // Divisor is < 0.
2975 if (Div->isExact())
2976 RangeSize.negate();
2977 if (C.isZero()) { // (X / neg) op 0
2978 // e.g. X/-5 op 0 --> [-4, 5)
2979 LoBound = RangeSize + 1;
2980 HiBound = -RangeSize;
2981 if (HiBound == *C2) { // -INTMIN = INTMIN
2982 HiOverflow = 1; // [INTMIN+1, overflow)
2983 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2984 }
2985 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2986 // e.g. X/-5 op 3 --> [-19, -14)
2987 HiBound = Prod + 1;
2988 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2989 if (!LoOverflow)
2990 LoOverflow =
2991 addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
2992 } else { // (X / neg) op neg
2993 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2994 LoOverflow = HiOverflow = ProdOV;
2995 if (!HiOverflow)
2996 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2997 }
2998
2999 // Dividing by a negative swaps the condition. LT <-> GT
3000 Pred = ICmpInst::getSwappedPredicate(Pred);
3001 }
3002
3003 switch (Pred) {
3004 default:
3005 llvm_unreachable("Unhandled icmp predicate!");
3006 case ICmpInst::ICMP_EQ:
3007 if (LoOverflow && HiOverflow)
3008 return replaceInstUsesWith(Cmp, Builder.getFalse());
3009 if (HiOverflow)
3010 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3011 X, ConstantInt::get(Ty, LoBound));
3012 if (LoOverflow)
3013 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3014 X, ConstantInt::get(Ty, HiBound));
3015 return replaceInstUsesWith(
3016 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
3017 case ICmpInst::ICMP_NE:
3018 if (LoOverflow && HiOverflow)
3019 return replaceInstUsesWith(Cmp, Builder.getTrue());
3020 if (HiOverflow)
3021 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3022 X, ConstantInt::get(Ty, LoBound));
3023 if (LoOverflow)
3024 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3025 X, ConstantInt::get(Ty, HiBound));
3026 return replaceInstUsesWith(
3027 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
3028 case ICmpInst::ICMP_ULT:
3029 case ICmpInst::ICMP_SLT:
3030 if (LoOverflow == +1) // Low bound is greater than input range.
3031 return replaceInstUsesWith(Cmp, Builder.getTrue());
3032 if (LoOverflow == -1) // Low bound is less than input range.
3033 return replaceInstUsesWith(Cmp, Builder.getFalse());
3034 return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
3035 case ICmpInst::ICMP_UGT:
3036 case ICmpInst::ICMP_SGT:
3037 if (HiOverflow == +1) // High bound greater than input range.
3038 return replaceInstUsesWith(Cmp, Builder.getFalse());
3039 if (HiOverflow == -1) // High bound less than input range.
3040 return replaceInstUsesWith(Cmp, Builder.getTrue());
3041 if (Pred == ICmpInst::ICMP_UGT)
3042 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
3043 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
3044 }
3045
3046 return nullptr;
3047}
3048
3049/// Fold icmp (sub X, Y), C.
3052 const APInt &C) {
3053 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
3054 ICmpInst::Predicate Pred = Cmp.getPredicate();
3055 Type *Ty = Sub->getType();
3056
3057 // (X - (X urem D)) is D*(X/D), a multiple of D, so it is u> C exactly when
3058 // X u>= D (for C u< D), and u< C exactly when X u< D (for 0 u< C u<= D):
3059 // icmp ugt (sub X, (urem X, D)), C --> icmp ugt X, D-1
3060 // icmp ult (sub X, (urem X, D)), C --> icmp ult X, D
3061 const APInt *D;
3062 if (match(Y, m_URem(m_Specific(X), m_APInt(D))) && !D->isZero()) {
3063 if (Pred == ICmpInst::ICMP_UGT && C.ult(*D))
3064 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, *D - 1));
3065 if (Pred == ICmpInst::ICMP_ULT && !C.isZero() && C.ule(*D))
3066 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, *D));
3067 }
3068
3069 // (SubC - Y) == C) --> Y == (SubC - C)
3070 // (SubC - Y) != C) --> Y != (SubC - C)
3071 Constant *SubC;
3072 if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
3073 return new ICmpInst(Pred, Y,
3074 ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C)));
3075 }
3076
3077 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
3078 const APInt *C2;
3079 APInt SubResult;
3080 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
3081 bool HasNSW = Sub->hasNoSignedWrap();
3082 bool HasNUW = Sub->hasNoUnsignedWrap();
3083 if (match(X, m_APInt(C2)) &&
3084 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
3085 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
3086 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
3087
3088 // X - Y == 0 --> X == Y.
3089 // X - Y != 0 --> X != Y.
3090 // TODO: We allow this with multiple uses as long as the other uses are not
3091 // in phis. The phi use check is guarding against a codegen regression
3092 // for a loop test. If the backend could undo this (and possibly
3093 // subsequent transforms), we would not need this hack.
3094 if (Cmp.isEquality() && C.isZero() &&
3095 none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
3096 return new ICmpInst(Pred, X, Y);
3097
3098 // The following transforms are only worth it if the only user of the subtract
3099 // is the icmp.
3100 // TODO: This is an artificial restriction for all of the transforms below
3101 // that only need a single replacement icmp. Can these use the phi test
3102 // like the transform above here?
3103 if (!Sub->hasOneUse())
3104 return nullptr;
3105
3106 if (Sub->hasNoSignedWrap()) {
3107 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
3108 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3109 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3110
3111 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
3112 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
3113 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3114
3115 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
3116 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
3117 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3118
3119 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
3120 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3121 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3122 }
3123
3124 if (!match(X, m_APInt(C2)))
3125 return nullptr;
3126
3127 // C2 - Y <u C -> (Y | (C - 1)) == C2
3128 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
3129 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
3130 (*C2 & (C - 1)) == (C - 1))
3131 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
3132
3133 // C2 - Y >u C -> (Y | C) != C2
3134 // iff C2 & C == C and C + 1 is a power of 2
3135 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
3136 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
3137
3138 // We have handled special cases that reduce.
3139 // Canonicalize any remaining sub to add as:
3140 // (C2 - Y) > C --> (Y + ~C2) < ~C
3141 Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
3142 HasNUW, HasNSW);
3143 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
3144}
3145
3146static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
3147 Value *Op1, IRBuilderBase &Builder,
3148 bool HasOneUse) {
3149 auto FoldConstant = [&](bool Val) {
3150 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3151 if (Op0->getType()->isVectorTy())
3153 cast<VectorType>(Op0->getType())->getElementCount(), Res);
3154 return Res;
3155 };
3156
3157 switch (Table.to_ulong()) {
3158 case 0: // 0 0 0 0
3159 return FoldConstant(false);
3160 case 1: // 0 0 0 1
3161 return HasOneUse ? Builder.CreateNot(Builder.CreateOr(Op0, Op1)) : nullptr;
3162 case 2: // 0 0 1 0
3163 return HasOneUse ? Builder.CreateAnd(Builder.CreateNot(Op0), Op1) : nullptr;
3164 case 3: // 0 0 1 1
3165 return Builder.CreateNot(Op0);
3166 case 4: // 0 1 0 0
3167 return HasOneUse ? Builder.CreateAnd(Op0, Builder.CreateNot(Op1)) : nullptr;
3168 case 5: // 0 1 0 1
3169 return Builder.CreateNot(Op1);
3170 case 6: // 0 1 1 0
3171 return Builder.CreateXor(Op0, Op1);
3172 case 7: // 0 1 1 1
3173 return HasOneUse ? Builder.CreateNot(Builder.CreateAnd(Op0, Op1)) : nullptr;
3174 case 8: // 1 0 0 0
3175 return Builder.CreateAnd(Op0, Op1);
3176 case 9: // 1 0 0 1
3177 return HasOneUse ? Builder.CreateNot(Builder.CreateXor(Op0, Op1)) : nullptr;
3178 case 10: // 1 0 1 0
3179 return Op1;
3180 case 11: // 1 0 1 1
3181 return HasOneUse ? Builder.CreateOr(Builder.CreateNot(Op0), Op1) : nullptr;
3182 case 12: // 1 1 0 0
3183 return Op0;
3184 case 13: // 1 1 0 1
3185 return HasOneUse ? Builder.CreateOr(Op0, Builder.CreateNot(Op1)) : nullptr;
3186 case 14: // 1 1 1 0
3187 return Builder.CreateOr(Op0, Op1);
3188 case 15: // 1 1 1 1
3189 return FoldConstant(true);
3190 default:
3191 llvm_unreachable("Invalid Operation");
3192 }
3193 return nullptr;
3194}
3195
3197 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3198 Value *A, *B;
3199 Constant *C1, *C2, *C3, *C4;
3200 if (!match(BO->getOperand(0),
3202 !match(BO->getOperand(1),
3204 Cmp.getType() != A->getType() || Cmp.getType() != B->getType())
3205 return nullptr;
3206
3207 std::bitset<4> Table;
3208 auto ComputeTable = [&](bool First, bool Second) -> std::optional<bool> {
3209 Constant *L = First ? C1 : C2;
3210 Constant *R = Second ? C3 : C4;
3211 if (auto *Res = ConstantFoldBinaryOpOperands(BO->getOpcode(), L, R, DL)) {
3212 auto *Val = Res->getType()->isVectorTy() ? Res->getSplatValue() : Res;
3213 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val))
3214 return ICmpInst::compare(CI->getValue(), C, Cmp.getPredicate());
3215 }
3216 return std::nullopt;
3217 };
3218
3219 for (unsigned I = 0; I < 4; ++I) {
3220 bool First = (I >> 1) & 1;
3221 bool Second = I & 1;
3222 if (auto Res = ComputeTable(First, Second))
3223 Table[I] = *Res;
3224 else
3225 return nullptr;
3226 }
3227
3228 // Synthesize optimal logic.
3229 if (auto *Cond = createLogicFromTable(Table, A, B, Builder, BO->hasOneUse()))
3230 return replaceInstUsesWith(Cmp, Cond);
3231 return nullptr;
3232}
3233
3234/// Fold icmp (add X, Y), C.
3237 const APInt &C) {
3238 Value *Y = Add->getOperand(1);
3239 Value *X = Add->getOperand(0);
3240 const CmpPredicate Pred = Cmp.getCmpPredicate();
3241
3242 // icmp ult (add nuw A, (lshr A, ShAmtC)), C --> icmp ult A, C
3243 // when C <= (1 << ShAmtC).
3244 const APInt *ShAmtC;
3245 Value *A;
3246 unsigned BitWidth = C.getBitWidth();
3247 if (Pred == ICmpInst::ICMP_ULT &&
3248 match(Add,
3249 m_c_NUWAdd(m_Value(A), m_LShr(m_Deferred(A), m_APInt(ShAmtC)))) &&
3250 ShAmtC->ult(BitWidth) &&
3251 C.ule(APInt::getOneBitSet(BitWidth, ShAmtC->getZExtValue())))
3252 return new ICmpInst(Pred, A, ConstantInt::get(A->getType(), C));
3253
3254 const APInt *C2;
3255 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
3256 return nullptr;
3257
3258 // Fold icmp pred (add X, C2), C.
3259 Type *Ty = Add->getType();
3260
3261 // If the add does not wrap, we can always adjust the compare by subtracting
3262 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3263 // have been canonicalized to SGT/SLT/UGT/ULT.
3264 if (Add->hasNoUnsignedWrap() &&
3265 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT)) {
3266 bool Overflow;
3267 APInt NewC = C.usub_ov(*C2, Overflow);
3268 // If there is overflow, the result must be true or false.
3269 if (!Overflow)
3270 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
3271 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
3272 }
3273
3274 CmpInst::Predicate ChosenPred = Pred.getPreferredSignedPredicate();
3275
3276 if (Add->hasNoSignedWrap() &&
3277 (ChosenPred == ICmpInst::ICMP_SGT || ChosenPred == ICmpInst::ICMP_SLT)) {
3278 bool Overflow;
3279 APInt NewC = C.ssub_ov(*C2, Overflow);
3280 if (!Overflow)
3281 // icmp samesign ugt/ult (add nsw X, C2), C
3282 // -> icmp sgt/slt X, (C - C2)
3283 return new ICmpInst(ChosenPred, X, ConstantInt::get(Ty, NewC));
3284 }
3285
3286 if (ICmpInst::isUnsigned(Pred) && Add->hasNoSignedWrap() &&
3287 C.isNonNegative() && (C - *C2).isNonNegative() &&
3288 computeConstantRange(X, /*ForSigned=*/true, SQ.getWithInstruction(&Cmp))
3289 .add(*C2)
3290 .isAllNonNegative())
3291 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), X,
3292 ConstantInt::get(Ty, C - *C2));
3293
3294 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
3295 const APInt &Upper = CR.getUpper();
3296 const APInt &Lower = CR.getLower();
3297 if (Cmp.isSigned()) {
3298 if (Lower.isSignMask())
3299 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
3300 if (Upper.isSignMask())
3301 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
3302 } else {
3303 if (Lower.isMinValue())
3304 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
3305 if (Upper.isMinValue())
3306 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
3307 }
3308
3309 // This set of folds is intentionally placed after folds that use no-wrapping
3310 // flags because those folds are likely better for later analysis/codegen.
3311 const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
3312 const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
3313
3314 // Fold compare with offset to opposite sign compare if it eliminates offset:
3315 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3316 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3317 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
3318
3319 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3320 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3321 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
3322
3323 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3324 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3325 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
3326
3327 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3328 if (Pred == CmpInst::ICMP_SLT && C == *C2)
3329 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
3330
3331 // (X + -1) <u C --> X <=u C (if X is never null)
3332 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3333 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3334 if (llvm::isKnownNonZero(X, Q))
3335 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
3336 }
3337
3338 if (!Add->hasOneUse())
3339 return nullptr;
3340
3341 // X+C <u C2 -> (X & -C2) == C
3342 // iff C & (C2-1) == 0
3343 // C2 is a power of 2
3344 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3345 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
3347
3348 // X+C2 <u C -> (X & C) == 2C
3349 // iff C == -(C2)
3350 // C2 is a power of 2
3351 if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)
3352 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, C),
3353 ConstantInt::get(Ty, C * 2));
3354
3355 // X+C >u C2 -> (X & ~C2) != C
3356 // iff C & C2 == 0
3357 // C2+1 is a power of 2
3358 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3359 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
3361
3362 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3363 // to the ult form.
3364 // X+C2 >u C -> X+(C2-C-1) <u ~C
3365 if (Pred == ICmpInst::ICMP_UGT)
3366 return new ICmpInst(ICmpInst::ICMP_ULT,
3367 Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
3368 ConstantInt::get(Ty, ~C));
3369
3370 // zext(V) + C2 pred C -> V + C3 pred' C4
3371 Value *V;
3372 if (match(X, m_ZExt(m_Value(V)))) {
3373 Type *NewCmpTy = V->getType();
3374 unsigned NewCmpBW = NewCmpTy->getScalarSizeInBits();
3375 if (shouldChangeType(Ty, NewCmpTy)) {
3376 ConstantRange SrcCR = CR.truncate(NewCmpBW, TruncInst::NoUnsignedWrap);
3377 CmpInst::Predicate EquivPred;
3378 APInt EquivInt;
3379 APInt EquivOffset;
3380
3381 SrcCR.getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
3382 return new ICmpInst(
3383 EquivPred,
3384 EquivOffset.isZero()
3385 ? V
3386 : Builder.CreateAdd(V, ConstantInt::get(NewCmpTy, EquivOffset)),
3387 ConstantInt::get(NewCmpTy, EquivInt));
3388 }
3389 }
3390
3391 return nullptr;
3392}
3393
3395 Value *&RHS, ConstantInt *&Less,
3396 ConstantInt *&Equal,
3397 ConstantInt *&Greater) {
3398 // TODO: Generalize this to work with other comparison idioms or ensure
3399 // they get canonicalized into this form.
3400
3401 // select i1 (a == b),
3402 // i32 Equal,
3403 // i32 (select i1 (a < b), i32 Less, i32 Greater)
3404 // where Equal, Less and Greater are placeholders for any three constants.
3405 CmpPredicate PredA;
3406 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
3407 !ICmpInst::isEquality(PredA))
3408 return false;
3409 Value *EqualVal = SI->getTrueValue();
3410 Value *UnequalVal = SI->getFalseValue();
3411 // We still can get non-canonical predicate here, so canonicalize.
3412 if (PredA == ICmpInst::ICMP_NE)
3413 std::swap(EqualVal, UnequalVal);
3414 if (!match(EqualVal, m_ConstantInt(Equal)))
3415 return false;
3416 CmpPredicate PredB;
3417 Value *LHS2, *RHS2;
3418 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
3419 m_ConstantInt(Less), m_ConstantInt(Greater))))
3420 return false;
3421 // We can get predicate mismatch here, so canonicalize if possible:
3422 // First, ensure that 'LHS' match.
3423 if (LHS2 != LHS) {
3424 // x sgt y <--> y slt x
3425 std::swap(LHS2, RHS2);
3426 PredB = ICmpInst::getSwappedPredicate(PredB);
3427 }
3428 if (LHS2 != LHS)
3429 return false;
3430 // We also need to canonicalize 'RHS'.
3431 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
3432 // x sgt C-1 <--> x sge C <--> not(x slt C)
3433 auto FlippedStrictness =
3435 if (!FlippedStrictness)
3436 return false;
3437 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3438 "basic correctness failure");
3439 RHS2 = FlippedStrictness->second;
3440 // And kind-of perform the result swap.
3441 std::swap(Less, Greater);
3442 PredB = ICmpInst::ICMP_SLT;
3443 }
3444 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3445}
3446
3449 ConstantInt *C) {
3450
3451 assert(C && "Cmp RHS should be a constant int!");
3452 // If we're testing a constant value against the result of a three way
3453 // comparison, the result can be expressed directly in terms of the
3454 // original values being compared. Note: We could possibly be more
3455 // aggressive here and remove the hasOneUse test. The original select is
3456 // really likely to simplify or sink when we remove a test of the result.
3457 Value *OrigLHS, *OrigRHS;
3458 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3459 if (Cmp.hasOneUse() &&
3460 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
3461 C3GreaterThan)) {
3462 assert(C1LessThan && C2Equal && C3GreaterThan);
3463
3464 bool TrueWhenLessThan = ICmpInst::compare(
3465 C1LessThan->getValue(), C->getValue(), Cmp.getPredicate());
3466 bool TrueWhenEqual = ICmpInst::compare(C2Equal->getValue(), C->getValue(),
3467 Cmp.getPredicate());
3468 bool TrueWhenGreaterThan = ICmpInst::compare(
3469 C3GreaterThan->getValue(), C->getValue(), Cmp.getPredicate());
3470
3471 // This generates the new instruction that will replace the original Cmp
3472 // Instruction. Instead of enumerating the various combinations when
3473 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3474 // false, we rely on chaining of ORs and future passes of InstCombine to
3475 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3476
3477 // When none of the three constants satisfy the predicate for the RHS (C),
3478 // the entire original Cmp can be simplified to a false.
3479 Value *Cond = Builder.getFalse();
3480 if (TrueWhenLessThan)
3481 Cond = Builder.CreateOr(
3482 Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT, OrigLHS, OrigRHS));
3483 if (TrueWhenEqual)
3484 Cond = Builder.CreateOr(
3485 Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ, OrigLHS, OrigRHS));
3486 if (TrueWhenGreaterThan)
3487 Cond = Builder.CreateOr(
3488 Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT, OrigLHS, OrigRHS));
3489
3490 return replaceInstUsesWith(Cmp, Cond);
3491 }
3492 return nullptr;
3493}
3494
3496 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3497 if (!Bitcast)
3498 return nullptr;
3499
3500 ICmpInst::Predicate Pred = Cmp.getPredicate();
3501 Value *Op1 = Cmp.getOperand(1);
3502 Value *BCSrcOp = Bitcast->getOperand(0);
3503 Type *SrcType = Bitcast->getSrcTy();
3504 Type *DstType = Bitcast->getType();
3505
3506 // Make sure the bitcast doesn't change between scalar and vector and
3507 // doesn't change the number of vector elements.
3508 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3509 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3510 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3511 Value *X;
3512 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
3513 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3514 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3515 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3516 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3517 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3518 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3519 match(Op1, m_Zero()))
3520 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3521
3522 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3523 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
3524 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
3525
3526 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3527 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
3528 return new ICmpInst(Pred, X,
3529 ConstantInt::getAllOnesValue(X->getType()));
3530 }
3531
3532 // Zero-equality checks are preserved through unsigned floating-point casts:
3533 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3534 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3535 if (match(BCSrcOp, m_UIToFP(m_Value(X))))
3536 if (Cmp.isEquality() && match(Op1, m_Zero()))
3537 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3538
3539 const APInt *C;
3540 bool TrueIfSigned;
3541 if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse()) {
3542 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3543 // the FP extend/truncate because that cast does not change the sign-bit.
3544 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3545 // The sign-bit is always the most significant bit in those types.
3546 if (isSignBitCheck(Pred, *C, TrueIfSigned) &&
3547 (match(BCSrcOp, m_FPExt(m_Value(X))) ||
3548 match(BCSrcOp, m_FPTrunc(m_Value(X))))) {
3549 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3550 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3551 Type *XType = X->getType();
3552
3553 // We can't currently handle Power style floating point operations here.
3554 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3555 Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
3556 if (auto *XVTy = dyn_cast<VectorType>(XType))
3557 NewType = VectorType::get(NewType, XVTy->getElementCount());
3558 Value *NewBitcast = Builder.CreateBitCast(X, NewType);
3559 if (TrueIfSigned)
3560 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3561 ConstantInt::getNullValue(NewType));
3562 else
3563 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3565 }
3566 }
3567
3568 // icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)
3569 Type *FPType = SrcType->getScalarType();
3570 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3571 Attribute::NoImplicitFloat) &&
3572 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3573 FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();
3574 if (Mask & (fcInf | fcZero)) {
3575 if (Pred == ICmpInst::ICMP_NE)
3576 Mask = ~Mask;
3577 return replaceInstUsesWith(Cmp,
3578 Builder.createIsFPClass(BCSrcOp, Mask));
3579 }
3580 }
3581 }
3582 }
3583
3584 const APInt *C;
3585 if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3586 !SrcType->isIntOrIntVectorTy())
3587 return nullptr;
3588
3589 // If this is checking if all elements of a vector compare are set or not,
3590 // invert the casted vector equality compare and test if all compare
3591 // elements are clear or not. Compare against zero is generally easier for
3592 // analysis and codegen.
3593 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3594 // Example: are all elements equal? --> are zero elements not equal?
3595 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3596 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3597 if (Value *NotBCSrcOp =
3598 getFreelyInverted(BCSrcOp, BCSrcOp->hasOneUse(), &Builder)) {
3599 Value *Cast = Builder.CreateBitCast(NotBCSrcOp, DstType);
3600 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3601 }
3602 }
3603
3604 // If this is checking if all elements of an extended vector are clear or not,
3605 // compare in a narrow type to eliminate the extend:
3606 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3607 Value *X;
3608 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3609 match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3610 if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3611 Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3612 Value *NewCast = Builder.CreateBitCast(X, NewType);
3613 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3614 }
3615 }
3616
3617 // Folding: icmp <pred> iN X, C
3618 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3619 // and C is a splat of a K-bit pattern
3620 // and SC is a constant vector = <C', C', C', ..., C'>
3621 // Into:
3622 // %E = extractelement <M x iK> %vec, i32 C'
3623 // icmp <pred> iK %E, trunc(C)
3624 Value *Vec;
3625 ArrayRef<int> Mask;
3626 if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3627 // Check whether every element of Mask is the same constant
3628 if (all_equal(Mask)) {
3629 auto *VecTy = cast<VectorType>(SrcType);
3630 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3631 if (C->isSplat(EltTy->getBitWidth())) {
3632 // Fold the icmp based on the value of C
3633 // If C is M copies of an iK sized bit pattern,
3634 // then:
3635 // => %E = extractelement <N x iK> %vec, i64 Elem
3636 // icmp <pred> iK %SplatVal, <pattern>
3637 Value *Extract = Builder.CreateExtractElement(Vec, Mask[0]);
3638 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3639 return new ICmpInst(Pred, Extract, NewC);
3640 }
3641 }
3642 }
3643 return nullptr;
3644}
3645
3646/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3647/// where X is some kind of instruction.
3649 const APInt *C;
3650
3651 if (match(Cmp.getOperand(1), m_APInt(C))) {
3652 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3653 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3654 return I;
3655
3656 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3657 // For now, we only support constant integers while folding the
3658 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3659 // similar to the cases handled by binary ops above.
3660 if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3661 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3662 return I;
3663
3664 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3665 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3666 return I;
3667
3668 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3670 return I;
3671
3672 {
3673 // icmp slt/sgt (extractvalue (frexp X), 1), C -->
3674 // fcmp olt/oge (fabs X), 2^ExpVal
3675 // slt -> olt, ExpVal = C-1; sgt -> oge, ExpVal = C.
3676 Value *X;
3677 if (match(Cmp.getOperand(0),
3680 ICmpInst::Predicate Pred = Cmp.getPredicate();
3681 APInt Exp;
3682 FCmpInst::Predicate NewPred;
3683 bool ValidPred = true;
3684
3685 switch (Pred) {
3686 case ICmpInst::ICMP_SLT:
3687 NewPred = FCmpInst::FCMP_OLT;
3688 Exp = *C - 1;
3689 break;
3690 case ICmpInst::ICMP_SGT:
3691 NewPred = FCmpInst::FCMP_OGE;
3692 Exp = *C;
3693 break;
3694 default:
3695 ValidPred = false;
3696 break;
3697 }
3698
3699 if (ValidPred) {
3700 const fltSemantics &Sem =
3701 X->getType()->getScalarType()->getFltSemantics();
3702 int MaxExp = APFloat::semanticsMaxExponent(Sem);
3703
3704 if (!Exp.isNegative() && Exp.sle(MaxExp + 1) &&
3705 isKnownNeverInfOrNaN(X, SQ.getWithInstruction(&Cmp))) {
3706 int ExpVal = static_cast<int>(Exp.getSExtValue());
3707 APFloat CmpConst = scalbn(APFloat::getOne(Sem), ExpVal,
3709 Value *Fabs = Builder.CreateFAbs(X);
3710 return new FCmpInst(NewPred, Fabs,
3711 ConstantFP::get(X->getType(), CmpConst));
3712 }
3713 }
3714 }
3715 }
3716
3717 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3718 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3719 // TODO: This checks one-use, but that is not strictly necessary.
3720 Value *Cmp0 = Cmp.getOperand(0);
3721 Value *X, *Y;
3722 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3723 (match(Cmp0,
3725 m_Value(X), m_Value(Y)))) ||
3726 match(Cmp0,
3728 m_Value(X), m_Value(Y))))))
3729 return new ICmpInst(Cmp.getPredicate(), X, Y);
3730 }
3731
3732 if (match(Cmp.getOperand(1), m_APIntAllowPoison(C)))
3734
3735 return nullptr;
3736}
3737
3738/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3739/// icmp eq/ne BO, C.
3741 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3742 // TODO: Some of these folds could work with arbitrary constants, but this
3743 // function is limited to scalar and vector splat constants.
3744 if (!Cmp.isEquality())
3745 return nullptr;
3746
3747 ICmpInst::Predicate Pred = Cmp.getPredicate();
3748 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3749 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3750 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3751
3752 switch (BO->getOpcode()) {
3753 case Instruction::SRem:
3754 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3755 if (C.isZero() && BO->hasOneUse()) {
3756 const APInt *BOC;
3757 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3758 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3759 return new ICmpInst(Pred, NewRem,
3761 }
3762 }
3763 break;
3764 case Instruction::Add: {
3765 // (A + C2) == C --> A == (C - C2)
3766 // (A + C2) != C --> A != (C - C2)
3767 // TODO: Remove the one-use limitation? See discussion in D58633.
3768 if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
3769 if (BO->hasOneUse())
3770 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
3771 } else if (C.isZero()) {
3772 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3773 // efficiently invertible, or if the add has just this one use.
3774 if (Value *NegVal = dyn_castNegVal(BOp1))
3775 return new ICmpInst(Pred, BOp0, NegVal);
3776 if (Value *NegVal = dyn_castNegVal(BOp0))
3777 return new ICmpInst(Pred, NegVal, BOp1);
3778 if (BO->hasOneUse()) {
3779 // (add nuw A, B) != 0 -> (or A, B) != 0
3780 if (match(BO, m_NUWAdd(m_Value(), m_Value()))) {
3781 Value *Or = Builder.CreateOr(BOp0, BOp1);
3782 return new ICmpInst(Pred, Or, Constant::getNullValue(BO->getType()));
3783 }
3784 Value *Neg = Builder.CreateNeg(BOp1);
3785 Neg->takeName(BO);
3786 return new ICmpInst(Pred, BOp0, Neg);
3787 }
3788 }
3789 break;
3790 }
3791 case Instruction::Xor:
3792 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3793 // For the xor case, we can xor two constants together, eliminating
3794 // the explicit xor.
3795 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3796 } else if (C.isZero()) {
3797 // Replace ((xor A, B) != 0) with (A != B)
3798 return new ICmpInst(Pred, BOp0, BOp1);
3799 }
3800 break;
3801 case Instruction::Or: {
3802 const APInt *BOC;
3803 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3804 // Comparing if all bits outside of a constant mask are set?
3805 // Replace (X | C) == -1 with (X & ~C) == ~C.
3806 // This removes the -1 constant.
3808 Value *And = Builder.CreateAnd(BOp0, NotBOC);
3809 return new ICmpInst(Pred, And, NotBOC);
3810 }
3811 // (icmp eq (or (select cond, 0, NonZero), Other), 0)
3812 // -> (and cond, (icmp eq Other, 0))
3813 // (icmp ne (or (select cond, NonZero, 0), Other), 0)
3814 // -> (or cond, (icmp ne Other, 0))
3815 Value *Cond, *TV, *FV, *Other, *Sel;
3816 if (C.isZero() &&
3817 match(BO,
3820 m_Value(FV))),
3821 m_Value(Other)))) &&
3822 Cond->getType() == Cmp.getType()) {
3823 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3824 // Easy case is if eq/ne matches whether 0 is trueval/falseval.
3825 if (Pred == ICmpInst::ICMP_EQ
3826 ? (match(TV, m_Zero()) && isKnownNonZero(FV, Q))
3827 : (match(FV, m_Zero()) && isKnownNonZero(TV, Q))) {
3828 Value *Cmp = Builder.CreateICmp(
3829 Pred, Other, Constant::getNullValue(Other->getType()));
3831 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3832 Cond);
3833 }
3834 // Harder case is if eq/ne matches whether 0 is falseval/trueval. In this
3835 // case we need to invert the select condition so we need to be careful to
3836 // avoid creating extra instructions.
3837 // (icmp ne (or (select cond, 0, NonZero), Other), 0)
3838 // -> (or (not cond), (icmp ne Other, 0))
3839 // (icmp eq (or (select cond, NonZero, 0), Other), 0)
3840 // -> (and (not cond), (icmp eq Other, 0))
3841 //
3842 // Only do this if the inner select has one use, in which case we are
3843 // replacing `select` with `(not cond)`. Otherwise, we will create more
3844 // uses. NB: Trying to freely invert cond doesn't make sense here, as if
3845 // cond was freely invertable, the select arms would have been inverted.
3846 if (Sel->hasOneUse() &&
3847 (Pred == ICmpInst::ICMP_EQ
3848 ? (match(FV, m_Zero()) && isKnownNonZero(TV, Q))
3849 : (match(TV, m_Zero()) && isKnownNonZero(FV, Q)))) {
3850 Value *NotCond = Builder.CreateNot(Cond);
3851 Value *Cmp = Builder.CreateICmp(
3852 Pred, Other, Constant::getNullValue(Other->getType()));
3854 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3855 NotCond);
3856 }
3857 }
3858 break;
3859 }
3860 case Instruction::UDiv:
3861 case Instruction::SDiv:
3862 if (BO->isExact()) {
3863 // div exact X, Y eq/ne 0 -> X eq/ne 0
3864 // div exact X, Y eq/ne 1 -> X eq/ne Y
3865 // div exact X, Y eq/ne C ->
3866 // if Y * C never-overflow && OneUse:
3867 // -> Y * C eq/ne X
3868 if (C.isZero())
3869 return new ICmpInst(Pred, BOp0, Constant::getNullValue(BO->getType()));
3870 else if (C.isOne())
3871 return new ICmpInst(Pred, BOp0, BOp1);
3872 else if (BO->hasOneUse()) {
3874 Instruction::Mul, BO->getOpcode() == Instruction::SDiv, BOp1,
3875 Cmp.getOperand(1), BO);
3877 Value *YC =
3878 Builder.CreateMul(BOp1, ConstantInt::get(BO->getType(), C));
3879 return new ICmpInst(Pred, YC, BOp0);
3880 }
3881 }
3882 }
3883 if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3884 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3885 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3886 return new ICmpInst(NewPred, BOp1, BOp0);
3887 }
3888 break;
3889 default:
3890 break;
3891 }
3892 return nullptr;
3893}
3894
3896 const APInt &CRhs,
3897 InstCombiner::BuilderTy &Builder,
3898 const SimplifyQuery &Q) {
3899 assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3900 "Non-ctpop intrin in ctpop fold");
3901 if (!CtpopLhs->hasOneUse())
3902 return nullptr;
3903
3904 // Power of 2 test:
3905 // isPow2OrZero : ctpop(X) u< 2
3906 // isPow2 : ctpop(X) == 1
3907 // NotPow2OrZero: ctpop(X) u> 1
3908 // NotPow2 : ctpop(X) != 1
3909 // If we know any bit of X can be folded to:
3910 // IsPow2 : X & (~Bit) == 0
3911 // NotPow2 : X & (~Bit) != 0
3912 const ICmpInst::Predicate Pred = I.getPredicate();
3913 if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3914 (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3915 Value *Op = CtpopLhs->getArgOperand(0);
3916 KnownBits OpKnown = computeKnownBits(Op, Q.DL, Q.AC, Q.CxtI, Q.DT);
3917 // No need to check for count > 1, that should be already constant folded.
3918 if (OpKnown.countMinPopulation() == 1) {
3919 Value *And = Builder.CreateAnd(
3920 Op, Constant::getIntegerValue(Op->getType(), ~(OpKnown.One)));
3921 return new ICmpInst(
3922 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3925 And, Constant::getNullValue(Op->getType()));
3926 }
3927 }
3928
3929 return nullptr;
3930}
3931
3932/// Fold an equality icmp with LLVM intrinsic and constant operand.
3934 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3935 Type *Ty = II->getType();
3936 unsigned BitWidth = C.getBitWidth();
3937 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3938
3939 switch (II->getIntrinsicID()) {
3940 case Intrinsic::abs:
3941 // abs(A) == 0 -> A == 0
3942 // abs(A) == INT_MIN -> A == INT_MIN
3943 if (C.isZero() || C.isMinSignedValue())
3944 return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3945 break;
3946
3947 case Intrinsic::bswap:
3948 // bswap(A) == C -> A == bswap(C)
3949 return new ICmpInst(Pred, II->getArgOperand(0),
3950 ConstantInt::get(Ty, C.byteSwap()));
3951
3952 case Intrinsic::bitreverse:
3953 // bitreverse(A) == C -> A == bitreverse(C)
3954 return new ICmpInst(Pred, II->getArgOperand(0),
3955 ConstantInt::get(Ty, C.reverseBits()));
3956
3957 case Intrinsic::ctlz:
3958 case Intrinsic::cttz: {
3959 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3960 if (C == BitWidth)
3961 return new ICmpInst(Pred, II->getArgOperand(0),
3963
3964 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3965 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3966 // Limit to one use to ensure we don't increase instruction count.
3967 unsigned Num = C.getLimitedValue(BitWidth);
3968 if (Num != BitWidth && II->hasOneUse()) {
3969 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3970 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3971 : APInt::getHighBitsSet(BitWidth, Num + 1);
3972 APInt Mask2 = IsTrailing
3975 return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
3976 ConstantInt::get(Ty, Mask2));
3977 }
3978 break;
3979 }
3980
3981 case Intrinsic::ctpop: {
3982 // popcount(A) == 0 -> A == 0 and likewise for !=
3983 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3984 bool IsZero = C.isZero();
3985 if (IsZero || C == BitWidth)
3986 return new ICmpInst(Pred, II->getArgOperand(0),
3987 IsZero ? Constant::getNullValue(Ty)
3989
3990 break;
3991 }
3992
3993 case Intrinsic::fshl:
3994 case Intrinsic::fshr:
3995 if (II->getArgOperand(0) == II->getArgOperand(1)) {
3996 const APInt *RotAmtC;
3997 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3998 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3999 if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
4000 return new ICmpInst(Pred, II->getArgOperand(0),
4001 II->getIntrinsicID() == Intrinsic::fshl
4002 ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
4003 : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
4004 }
4005 break;
4006
4007 case Intrinsic::umax:
4008 case Intrinsic::uadd_sat: {
4009 // uadd.sat(a, b) == 0 -> (a | b) == 0
4010 // umax(a, b) == 0 -> (a | b) == 0
4011 if (C.isZero() && II->hasOneUse()) {
4012 Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));
4013 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
4014 }
4015 break;
4016 }
4017
4018 case Intrinsic::ssub_sat:
4019 // ssub.sat(a, b) == 0 -> a == b
4020 //
4021 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4022 // (because 1 saturates to 0). Just skip the optimization for i1.
4023 if (C.isZero() && II->getType()->getScalarSizeInBits() > 1)
4024 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4025 break;
4026 case Intrinsic::usub_sat: {
4027 // usub.sat(a, b) == 0 -> a <= b
4028 if (C.isZero()) {
4029 ICmpInst::Predicate NewPred =
4031 return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
4032 }
4033 break;
4034 }
4035 default:
4036 break;
4037 }
4038
4039 return nullptr;
4040}
4041
4042/// Fold an icmp with LLVM intrinsics
4043static Instruction *
4045 InstCombiner::BuilderTy &Builder) {
4046 assert(Cmp.isEquality());
4047
4048 ICmpInst::Predicate Pred = Cmp.getPredicate();
4049 Value *Op0 = Cmp.getOperand(0);
4050 Value *Op1 = Cmp.getOperand(1);
4051 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
4052 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
4053 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
4054 return nullptr;
4055
4056 switch (IIOp0->getIntrinsicID()) {
4057 case Intrinsic::bswap:
4058 case Intrinsic::bitreverse:
4059 // If both operands are byte-swapped or bit-reversed, just compare the
4060 // original values.
4061 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4062 case Intrinsic::fshl:
4063 case Intrinsic::fshr: {
4064 // If both operands are rotated by same amount, just compare the
4065 // original values.
4066 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
4067 break;
4068 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
4069 break;
4070 if (IIOp0->getOperand(2) == IIOp1->getOperand(2))
4071 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4072
4073 // rotate(X, AmtX) == rotate(Y, AmtY)
4074 // -> rotate(X, AmtX - AmtY) == Y
4075 // Do this if either both rotates have one use or if only one has one use
4076 // and AmtX/AmtY are constants.
4077 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
4078 if (OneUses == 2 ||
4079 (OneUses == 1 && match(IIOp0->getOperand(2), m_ImmConstant()) &&
4080 match(IIOp1->getOperand(2), m_ImmConstant()))) {
4081 Value *SubAmt =
4082 Builder.CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));
4083 Value *CombinedRotate = Builder.CreateIntrinsic(
4084 Op0->getType(), IIOp0->getIntrinsicID(),
4085 {IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});
4086 return new ICmpInst(Pred, IIOp1->getOperand(0), CombinedRotate);
4087 }
4088 } break;
4089 default:
4090 break;
4091 }
4092
4093 return nullptr;
4094}
4095
4096/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
4097/// where X is some kind of instruction and C is AllowPoison.
4098/// TODO: Move more folds which allow poison to this function.
4101 const APInt &C) {
4102 const ICmpInst::Predicate Pred = Cmp.getPredicate();
4103 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
4104 switch (II->getIntrinsicID()) {
4105 default:
4106 break;
4107 case Intrinsic::fshl:
4108 case Intrinsic::fshr:
4109 if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
4110 // (rot X, ?) == 0/-1 --> X == 0/-1
4111 if (C.isZero() || C.isAllOnes())
4112 return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
4113 }
4114 break;
4115 }
4116 }
4117
4118 return nullptr;
4119}
4120
4121/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
4123 BinaryOperator *BO,
4124 const APInt &C) {
4125 switch (BO->getOpcode()) {
4126 case Instruction::Xor:
4127 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
4128 return I;
4129 break;
4130 case Instruction::And:
4131 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
4132 return I;
4133 break;
4134 case Instruction::Or:
4135 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
4136 return I;
4137 break;
4138 case Instruction::Mul:
4139 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
4140 return I;
4141 break;
4142 case Instruction::Shl:
4143 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
4144 return I;
4145 break;
4146 case Instruction::LShr:
4147 case Instruction::AShr:
4148 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
4149 return I;
4150 break;
4151 case Instruction::SRem:
4152 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
4153 return I;
4154 break;
4155 case Instruction::UDiv:
4156 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
4157 return I;
4158 [[fallthrough]];
4159 case Instruction::SDiv:
4160 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
4161 return I;
4162 break;
4163 case Instruction::Sub:
4164 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
4165 return I;
4166 break;
4167 case Instruction::Add:
4168 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
4169 return I;
4170 break;
4171 default:
4172 break;
4173 }
4174
4175 // TODO: These folds could be refactored to be part of the above calls.
4177 return I;
4178
4179 // Fall back to handling `icmp pred (select A ? C1 : C2) binop (select B ? C3
4180 // : C4), C5` pattern, by computing a truth table of the four constant
4181 // variants.
4183}
4184
4185static Instruction *
4187 const APInt &C,
4188 InstCombiner::BuilderTy &Builder) {
4189 // This transform may end up producing more than one instruction for the
4190 // intrinsic, so limit it to one user of the intrinsic.
4191 if (!II->hasOneUse())
4192 return nullptr;
4193
4194 // Let Y = [add/sub]_sat(X, C) pred C2
4195 // SatVal = The saturating value for the operation
4196 // WillWrap = Whether or not the operation will underflow / overflow
4197 // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
4198 // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
4199 //
4200 // When (SatVal pred C2) is true, then
4201 // Y = WillWrap ? true : ((X binop C) pred C2)
4202 // => Y = WillWrap || ((X binop C) pred C2)
4203 // else
4204 // Y = WillWrap ? false : ((X binop C) pred C2)
4205 // => Y = !WillWrap ? ((X binop C) pred C2) : false
4206 // => Y = !WillWrap && ((X binop C) pred C2)
4207 Value *Op0 = II->getOperand(0);
4208 Value *Op1 = II->getOperand(1);
4209
4210 const APInt *COp1;
4211 // This transform only works when the intrinsic has an integral constant or
4212 // splat vector as the second operand.
4213 if (!match(Op1, m_APInt(COp1)))
4214 return nullptr;
4215
4216 APInt SatVal;
4217 switch (II->getIntrinsicID()) {
4218 default:
4220 "This function only works with usub_sat and uadd_sat for now!");
4221 case Intrinsic::uadd_sat:
4222 SatVal = APInt::getAllOnes(C.getBitWidth());
4223 break;
4224 case Intrinsic::usub_sat:
4225 SatVal = APInt::getZero(C.getBitWidth());
4226 break;
4227 }
4228
4229 // Check (SatVal pred C2)
4230 bool SatValCheck = ICmpInst::compare(SatVal, C, Pred);
4231
4232 // !WillWrap.
4234 II->getBinaryOp(), *COp1, II->getNoWrapKind());
4235
4236 // WillWrap.
4237 if (SatValCheck)
4238 C1 = C1.inverse();
4239
4241 if (II->getBinaryOp() == Instruction::Add)
4242 C2 = C2.sub(*COp1);
4243 else
4244 C2 = C2.add(*COp1);
4245
4246 Instruction::BinaryOps CombiningOp =
4247 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4248
4249 std::optional<ConstantRange> Combination;
4250 if (CombiningOp == Instruction::BinaryOps::Or)
4251 Combination = C1.exactUnionWith(C2);
4252 else /* CombiningOp == Instruction::BinaryOps::And */
4253 Combination = C1.exactIntersectWith(C2);
4254
4255 if (!Combination)
4256 return nullptr;
4257
4258 CmpInst::Predicate EquivPred;
4259 APInt EquivInt;
4260 APInt EquivOffset;
4261
4262 Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
4263
4264 return new ICmpInst(
4265 EquivPred,
4266 Builder.CreateAdd(Op0, ConstantInt::get(Op1->getType(), EquivOffset)),
4267 ConstantInt::get(Op1->getType(), EquivInt));
4268}
4269
4270static Instruction *
4272 const APInt &C,
4273 InstCombiner::BuilderTy &Builder) {
4274 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4275 switch (Pred) {
4276 case ICmpInst::ICMP_EQ:
4277 case ICmpInst::ICMP_NE:
4278 if (C.isZero())
4279 NewPredicate = Pred;
4280 else if (C.isOne())
4281 NewPredicate =
4283 else if (C.isAllOnes())
4284 NewPredicate =
4286 break;
4287
4288 case ICmpInst::ICMP_SGT:
4289 if (C.isAllOnes())
4290 NewPredicate = ICmpInst::ICMP_UGE;
4291 else if (C.isZero())
4292 NewPredicate = ICmpInst::ICMP_UGT;
4293 break;
4294
4295 case ICmpInst::ICMP_SLT:
4296 if (C.isZero())
4297 NewPredicate = ICmpInst::ICMP_ULT;
4298 else if (C.isOne())
4299 NewPredicate = ICmpInst::ICMP_ULE;
4300 break;
4301
4302 case ICmpInst::ICMP_ULT:
4303 if (C.ugt(1))
4304 NewPredicate = ICmpInst::ICMP_UGE;
4305 break;
4306
4307 case ICmpInst::ICMP_UGT:
4308 if (!C.isZero() && !C.isAllOnes())
4309 NewPredicate = ICmpInst::ICMP_ULT;
4310 break;
4311
4312 default:
4313 break;
4314 }
4315
4316 if (!NewPredicate)
4317 return nullptr;
4318
4319 if (I->getIntrinsicID() == Intrinsic::scmp)
4320 NewPredicate = ICmpInst::getSignedPredicate(*NewPredicate);
4321 Value *LHS = I->getOperand(0);
4322 Value *RHS = I->getOperand(1);
4323 return new ICmpInst(*NewPredicate, LHS, RHS);
4324}
4325
4326/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
4329 const APInt &C) {
4330 ICmpInst::Predicate Pred = Cmp.getPredicate();
4331
4332 // Handle folds that apply for any kind of icmp.
4333 switch (II->getIntrinsicID()) {
4334 default:
4335 break;
4336 case Intrinsic::uadd_sat:
4337 case Intrinsic::usub_sat:
4338 if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(
4339 Pred, cast<SaturatingInst>(II), C, Builder))
4340 return Folded;
4341 break;
4342 case Intrinsic::ctpop: {
4343 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
4344 if (Instruction *R = foldCtpopPow2Test(Cmp, II, C, Builder, Q))
4345 return R;
4346 } break;
4347 case Intrinsic::scmp:
4348 case Intrinsic::ucmp:
4349 if (auto *Folded = foldICmpOfCmpIntrinsicWithConstant(Pred, II, C, Builder))
4350 return Folded;
4351 break;
4352 }
4353
4354 if (Cmp.isEquality())
4355 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
4356
4357 Type *Ty = II->getType();
4358 unsigned BitWidth = C.getBitWidth();
4359 switch (II->getIntrinsicID()) {
4360 case Intrinsic::ctpop: {
4361 // (ctpop X > BitWidth - 1) --> X == -1
4362 Value *X = II->getArgOperand(0);
4363 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
4364 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
4366 // (ctpop X < BitWidth) --> X != -1
4367 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
4368 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
4370 break;
4371 }
4372 case Intrinsic::ctlz: {
4373 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
4374 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4375 unsigned Num = C.getLimitedValue();
4376 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
4377 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
4378 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4379 }
4380
4381 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
4382 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4383 unsigned Num = C.getLimitedValue();
4385 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
4386 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4387 }
4388 break;
4389 }
4390 case Intrinsic::cttz: {
4391 // Limit to one use to ensure we don't increase instruction count.
4392 if (!II->hasOneUse())
4393 return nullptr;
4394
4395 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
4396 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4397 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
4398 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
4399 Builder.CreateAnd(II->getArgOperand(0), Mask),
4401 }
4402
4403 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
4404 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4405 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
4406 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
4407 Builder.CreateAnd(II->getArgOperand(0), Mask),
4409 }
4410 break;
4411 }
4412 case Intrinsic::ssub_sat:
4413 // ssub.sat(a, b) spred 0 -> a spred b
4414 //
4415 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4416 // (because 1 saturates to 0). Just skip the optimization for i1.
4417 if (ICmpInst::isSigned(Pred) && C.getBitWidth() > 1) {
4418 if (C.isZero())
4419 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4420 // X s<= 0 is cannonicalized to X s< 1
4421 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
4422 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(0),
4423 II->getArgOperand(1));
4424 // X s>= 0 is cannonicalized to X s> -1
4425 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
4426 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(0),
4427 II->getArgOperand(1));
4428 }
4429 break;
4430 case Intrinsic::abs: {
4431 if (!II->hasOneUse())
4432 return nullptr;
4433
4434 Value *X = II->getArgOperand(0);
4435 bool IsIntMinPoison =
4436 cast<ConstantInt>(II->getArgOperand(1))->getValue().isOne();
4437
4438 // If C >= 0:
4439 // abs(X) u> C --> X + C u> 2 * C
4440 if (Pred == CmpInst::ICMP_UGT && C.isNonNegative()) {
4441 return new ICmpInst(ICmpInst::ICMP_UGT,
4442 Builder.CreateAdd(X, ConstantInt::get(Ty, C)),
4443 ConstantInt::get(Ty, 2 * C));
4444 }
4445
4446 // If abs(INT_MIN) is poison and C >= 1:
4447 // abs(X) u< C --> X + (C - 1) u<= 2 * (C - 1)
4448 if (IsIntMinPoison && Pred == CmpInst::ICMP_ULT && C.sge(1)) {
4449 return new ICmpInst(ICmpInst::ICMP_ULE,
4450 Builder.CreateAdd(X, ConstantInt::get(Ty, C - 1)),
4451 ConstantInt::get(Ty, 2 * (C - 1)));
4452 }
4453
4454 break;
4455 }
4456 default:
4457 break;
4458 }
4459
4460 return nullptr;
4461}
4462
4463/// Handle icmp with constant (but not simple integer constant) RHS.
4465 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4466 Constant *RHSC = dyn_cast<Constant>(Op1);
4468 if (!RHSC || !LHSI)
4469 return nullptr;
4470
4471 switch (LHSI->getOpcode()) {
4472 case Instruction::IntToPtr:
4473 // icmp pred inttoptr(X), null -> icmp pred X, null pointer value
4474 if (isa<ConstantPointerNull>(RHSC)) {
4475 Type *IntPtrTy = DL.getIntPtrType(RHSC->getType());
4476 if (IntPtrTy == LHSI->getOperand(0)->getType()) {
4477 APInt NullPtrValue =
4478 DL.getNullPtrValue(RHSC->getType()->getPointerAddressSpace());
4479 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
4480 Constant::getIntegerValue(IntPtrTy, NullPtrValue));
4481 }
4482 }
4483 break;
4484
4485 case Instruction::Load:
4486 // Try to optimize things like "A[i] > 4" to index computations.
4487 if (GetElementPtrInst *GEP =
4489 if (Instruction *Res =
4491 return Res;
4492 break;
4493 }
4494
4495 return nullptr;
4496}
4497
4499 Value *RHS, const ICmpInst &I) {
4500 // Try to fold the comparison into the select arms, which will cause the
4501 // select to be converted into a logical and/or.
4502 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
4503 if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
4504 return Res;
4505 if (std::optional<bool> Impl = isImpliedCondition(
4506 SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
4507 return ConstantInt::get(I.getType(), *Impl);
4508 return nullptr;
4509 };
4510
4511 ConstantInt *CI = nullptr;
4512 Value *Op1 = SimplifyOp(SI->getOperand(1), true);
4513 if (Op1)
4514 CI = dyn_cast<ConstantInt>(Op1);
4515
4516 Value *Op2 = SimplifyOp(SI->getOperand(2), false);
4517 if (Op2)
4518 CI = dyn_cast<ConstantInt>(Op2);
4519
4520 auto Simplifies = [&](Value *Op, unsigned Idx) {
4521 // A comparison of ucmp/scmp with a constant will fold into an icmp.
4522 const APInt *Dummy;
4523 return Op ||
4524 (isa<CmpIntrinsic>(SI->getOperand(Idx)) &&
4525 SI->getOperand(Idx)->hasOneUse() && match(RHS, m_APInt(Dummy)));
4526 };
4527
4528 // We only want to perform this transformation if it will not lead to
4529 // additional code. This is true if either both sides of the select
4530 // fold to a constant (in which case the icmp is replaced with a select
4531 // which will usually simplify) or this is the only user of the
4532 // select (in which case we are trading a select+icmp for a simpler
4533 // select+icmp) or all uses of the select can be replaced based on
4534 // dominance information ("Global cases").
4535 bool Transform = false;
4536 if (Op1 && Op2)
4537 Transform = true;
4538 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4539 // Local case
4540 if (SI->hasOneUse())
4541 Transform = true;
4542 // Global cases
4543 else if (CI && !CI->isZero())
4544 // When Op1 is constant try replacing select with second operand.
4545 // Otherwise Op2 is constant and try replacing select with first
4546 // operand.
4547 Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
4548 }
4549 if (Transform) {
4550 if (!Op1)
4551 Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
4552 if (!Op2)
4553 Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
4554 return SelectInst::Create(SI->getOperand(0), Op1, Op2, "", nullptr,
4555 ProfcheckDisableMetadataFixes ? nullptr : SI);
4556 }
4557
4558 return nullptr;
4559}
4560
4561// Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)
4562static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,
4563 unsigned Depth = 0) {
4564 if (Not ? match(V, m_NegatedPower2OrZero()) : match(V, m_LowBitMaskOrZero()))
4565 return true;
4566 if (V->getType()->getScalarSizeInBits() == 1)
4567 return true;
4569 return false;
4570 Value *X;
4572 if (!I)
4573 return false;
4574 switch (I->getOpcode()) {
4575 case Instruction::ZExt:
4576 // ZExt(Mask) is a Mask.
4577 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4578 case Instruction::SExt:
4579 // SExt(Mask) is a Mask.
4580 // SExt(~Mask) is a ~Mask.
4581 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4582 case Instruction::And:
4583 case Instruction::Or:
4584 // Mask0 | Mask1 is a Mask.
4585 // Mask0 & Mask1 is a Mask.
4586 // ~Mask0 | ~Mask1 is a ~Mask.
4587 // ~Mask0 & ~Mask1 is a ~Mask.
4588 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4589 isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4590 case Instruction::Xor:
4591 if (match(V, m_Not(m_Value(X))))
4592 return isMaskOrZero(X, !Not, Q, Depth);
4593
4594 // (X ^ -X) is a ~Mask
4595 if (Not)
4596 return match(V, m_c_Xor(m_Value(X), m_Neg(m_Deferred(X))));
4597 // (X ^ (X - 1)) is a Mask
4598 else
4599 return match(V, m_c_Xor(m_Value(X), m_Add(m_Deferred(X), m_AllOnes())));
4600 case Instruction::Select:
4601 // c ? Mask0 : Mask1 is a Mask.
4602 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4603 isMaskOrZero(I->getOperand(2), Not, Q, Depth);
4604 case Instruction::Shl:
4605 // (~Mask) << X is a ~Mask.
4606 return Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4607 case Instruction::LShr:
4608 // Mask >> X is a Mask.
4609 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4610 case Instruction::AShr:
4611 // Mask s>> X is a Mask.
4612 // ~Mask s>> X is a ~Mask.
4613 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4614 case Instruction::Add:
4615 // Pow2 - 1 is a Mask.
4616 if (!Not && match(I->getOperand(1), m_AllOnes()))
4617 return isKnownToBeAPowerOfTwo(I->getOperand(0), Q.DL, /*OrZero*/ true,
4618 Q.AC, Q.CxtI, Q.DT, Depth);
4619 break;
4620 case Instruction::Sub:
4621 // -Pow2 is a ~Mask.
4622 if (Not && match(I->getOperand(0), m_Zero()))
4623 return isKnownToBeAPowerOfTwo(I->getOperand(1), Q.DL, /*OrZero*/ true,
4624 Q.AC, Q.CxtI, Q.DT, Depth);
4625 break;
4626 case Instruction::Call: {
4627 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
4628 switch (II->getIntrinsicID()) {
4629 // min/max(Mask0, Mask1) is a Mask.
4630 // min/max(~Mask0, ~Mask1) is a ~Mask.
4631 case Intrinsic::umax:
4632 case Intrinsic::smax:
4633 case Intrinsic::umin:
4634 case Intrinsic::smin:
4635 return isMaskOrZero(II->getArgOperand(1), Not, Q, Depth) &&
4636 isMaskOrZero(II->getArgOperand(0), Not, Q, Depth);
4637
4638 // In the context of masks, bitreverse(Mask) == ~Mask
4639 case Intrinsic::bitreverse:
4640 return isMaskOrZero(II->getArgOperand(0), !Not, Q, Depth);
4641 default:
4642 break;
4643 }
4644 }
4645 break;
4646 }
4647 default:
4648 break;
4649 }
4650 return false;
4651}
4652
4653/// Some comparisons can be simplified.
4654/// In this case, we are looking for comparisons that look like
4655/// a check for a lossy truncation.
4656/// Folds:
4657/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
4658/// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask
4659/// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask
4660/// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask
4661/// Where Mask is some pattern that produces all-ones in low bits:
4662/// (-1 >> y)
4663/// ((-1 << y) >> y) <- non-canonical, has extra uses
4664/// ~(-1 << y)
4665/// ((1 << y) + (-1)) <- non-canonical, has extra uses
4666/// The Mask can be a constant, too.
4667/// For some predicates, the operands are commutative.
4668/// For others, x can only be on a specific side.
4670 Value *Op1, const SimplifyQuery &Q,
4671 InstCombiner &IC) {
4672
4673 ICmpInst::Predicate DstPred;
4674 switch (Pred) {
4676 // x & Mask == x
4677 // x & ~Mask == 0
4678 // ~x | Mask == -1
4679 // -> x u<= Mask
4680 // x & ~Mask == ~Mask
4681 // -> ~Mask u<= x
4683 break;
4685 // x & Mask != x
4686 // x & ~Mask != 0
4687 // ~x | Mask != -1
4688 // -> x u> Mask
4689 // x & ~Mask != ~Mask
4690 // -> ~Mask u> x
4692 break;
4694 // x & Mask u< x
4695 // -> x u> Mask
4696 // x & ~Mask u< ~Mask
4697 // -> ~Mask u> x
4699 break;
4701 // x & Mask u>= x
4702 // -> x u<= Mask
4703 // x & ~Mask u>= ~Mask
4704 // -> ~Mask u<= x
4706 break;
4708 // x & Mask s< x [iff Mask s>= 0]
4709 // -> x s> Mask
4710 // x & ~Mask s< ~Mask [iff ~Mask != 0]
4711 // -> ~Mask s> x
4713 break;
4715 // x & Mask s>= x [iff Mask s>= 0]
4716 // -> x s<= Mask
4717 // x & ~Mask s>= ~Mask [iff ~Mask != 0]
4718 // -> ~Mask s<= x
4720 break;
4721 default:
4722 // We don't support sgt,sle
4723 // ult/ugt are simplified to true/false respectively.
4724 return nullptr;
4725 }
4726
4727 Value *X, *M;
4728 // Put search code in lambda for early positive returns.
4729 auto IsLowBitMask = [&]() {
4730 if (match(Op0, m_c_And(m_Specific(Op1), m_Value(M)))) {
4731 X = Op1;
4732 // Look for: x & Mask pred x
4733 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4734 return !ICmpInst::isSigned(Pred) ||
4735 (match(M, m_NonNegative()) || isKnownNonNegative(M, Q));
4736 }
4737
4738 // Look for: x & ~Mask pred ~Mask
4739 if (isMaskOrZero(X, /*Not=*/true, Q)) {
4740 return !ICmpInst::isSigned(Pred) || isKnownNonZero(X, Q);
4741 }
4742 return false;
4743 }
4744 if (ICmpInst::isEquality(Pred) && match(Op1, m_AllOnes()) &&
4745 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(M))))) {
4746
4747 auto Check = [&]() {
4748 // Look for: ~x | Mask == -1
4749 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4750 if (Value *NotX =
4751 IC.getFreelyInverted(X, X->hasOneUse(), &IC.Builder)) {
4752 X = NotX;
4753 return true;
4754 }
4755 }
4756 return false;
4757 };
4758 if (Check())
4759 return true;
4760 std::swap(X, M);
4761 return Check();
4762 }
4763 if (ICmpInst::isEquality(Pred) && match(Op1, m_Zero()) &&
4764 match(Op0, m_OneUse(m_And(m_Value(X), m_Value(M))))) {
4765 auto Check = [&]() {
4766 // Look for: x & ~Mask == 0
4767 if (isMaskOrZero(M, /*Not=*/true, Q)) {
4768 if (Value *NotM =
4769 IC.getFreelyInverted(M, M->hasOneUse(), &IC.Builder)) {
4770 M = NotM;
4771 return true;
4772 }
4773 }
4774 return false;
4775 };
4776 if (Check())
4777 return true;
4778 std::swap(X, M);
4779 return Check();
4780 }
4781 return false;
4782 };
4783
4784 if (!IsLowBitMask())
4785 return nullptr;
4786
4787 return IC.Builder.CreateICmp(DstPred, X, M);
4788}
4789
4790/// Some comparisons can be simplified.
4791/// In this case, we are looking for comparisons that look like
4792/// a check for a lossy signed truncation.
4793/// Folds: (MaskedBits is a constant.)
4794/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4795/// Into:
4796/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4797/// Where KeptBits = bitwidth(%x) - MaskedBits
4798static Value *
4800 InstCombiner::BuilderTy &Builder) {
4801 CmpPredicate SrcPred;
4802 Value *X;
4803 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4804 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4805 if (!match(&I, m_c_ICmp(SrcPred,
4807 m_APInt(C1))),
4808 m_Deferred(X))))
4809 return nullptr;
4810
4811 // Potential handling of non-splats: for each element:
4812 // * if both are undef, replace with constant 0.
4813 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4814 // * if both are not undef, and are different, bailout.
4815 // * else, only one is undef, then pick the non-undef one.
4816
4817 // The shift amount must be equal.
4818 if (*C0 != *C1)
4819 return nullptr;
4820 const APInt &MaskedBits = *C0;
4821 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4822
4823 ICmpInst::Predicate DstPred;
4824 switch (SrcPred) {
4826 // ((%x << MaskedBits) a>> MaskedBits) == %x
4827 // =>
4828 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4830 break;
4832 // ((%x << MaskedBits) a>> MaskedBits) != %x
4833 // =>
4834 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4836 break;
4837 // FIXME: are more folds possible?
4838 default:
4839 return nullptr;
4840 }
4841
4842 auto *XType = X->getType();
4843 const unsigned XBitWidth = XType->getScalarSizeInBits();
4844 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4845 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4846
4847 // KeptBits = bitwidth(%x) - MaskedBits
4848 const APInt KeptBits = BitWidth - MaskedBits;
4849 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4850 // ICmpCst = (1 << KeptBits)
4851 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
4852 assert(ICmpCst.isPowerOf2());
4853 // AddCst = (1 << (KeptBits-1))
4854 const APInt AddCst = ICmpCst.lshr(1);
4855 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4856
4857 // T0 = add %x, AddCst
4858 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
4859 // T1 = T0 DstPred ICmpCst
4860 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
4861
4862 return T1;
4863}
4864
4865// Given pattern:
4866// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4867// we should move shifts to the same hand of 'and', i.e. rewrite as
4868// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4869// We are only interested in opposite logical shifts here.
4870// One of the shifts can be truncated.
4871// If we can, we want to end up creating 'lshr' shift.
4872static Value *
4874 InstCombiner::BuilderTy &Builder) {
4875 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
4876 !I.getOperand(0)->hasOneUse())
4877 return nullptr;
4878
4879 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
4880
4881 // Look for an 'and' of two logical shifts, one of which may be truncated.
4882 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4883 Instruction *XShift, *MaybeTruncation, *YShift;
4884 if (!match(
4885 I.getOperand(0),
4886 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
4888 m_AnyLogicalShift, m_Instruction(YShift))),
4889 m_Instruction(MaybeTruncation)))))
4890 return nullptr;
4891
4892 // We potentially looked past 'trunc', but only when matching YShift,
4893 // therefore YShift must have the widest type.
4894 Instruction *WidestShift = YShift;
4895 // Therefore XShift must have the shallowest type.
4896 // Or they both have identical types if there was no truncation.
4897 Instruction *NarrowestShift = XShift;
4898
4899 Type *WidestTy = WidestShift->getType();
4900 Type *NarrowestTy = NarrowestShift->getType();
4901 assert(NarrowestTy == I.getOperand(0)->getType() &&
4902 "We did not look past any shifts while matching XShift though.");
4903 bool HadTrunc = WidestTy != I.getOperand(0)->getType();
4904
4905 // If YShift is a 'lshr', swap the shifts around.
4906 if (match(YShift, m_LShr(m_Value(), m_Value())))
4907 std::swap(XShift, YShift);
4908
4909 // The shifts must be in opposite directions.
4910 auto XShiftOpcode = XShift->getOpcode();
4911 if (XShiftOpcode == YShift->getOpcode())
4912 return nullptr; // Do not care about same-direction shifts here.
4913
4914 Value *X, *XShAmt, *Y, *YShAmt;
4915 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
4916 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
4917
4918 // If one of the values being shifted is a constant, then we will end with
4919 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4920 // however, we will need to ensure that we won't increase instruction count.
4921 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
4922 // At least one of the hands of the 'and' should be one-use shift.
4923 if (!match(I.getOperand(0),
4924 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
4925 return nullptr;
4926 if (HadTrunc) {
4927 // Due to the 'trunc', we will need to widen X. For that either the old
4928 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4929 if (!MaybeTruncation->hasOneUse() &&
4930 !NarrowestShift->getOperand(1)->hasOneUse())
4931 return nullptr;
4932 }
4933 }
4934
4935 // We have two shift amounts from two different shifts. The types of those
4936 // shift amounts may not match. If that's the case let's bailout now.
4937 if (XShAmt->getType() != YShAmt->getType())
4938 return nullptr;
4939
4940 // As input, we have the following pattern:
4941 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4942 // We want to rewrite that as:
4943 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4944 // While we know that originally (Q+K) would not overflow
4945 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
4946 // shift amounts. so it may now overflow in smaller bitwidth.
4947 // To ensure that does not happen, we need to ensure that the total maximal
4948 // shift amount is still representable in that smaller bit width.
4949 unsigned MaximalPossibleTotalShiftAmount =
4950 (WidestTy->getScalarSizeInBits() - 1) +
4951 (NarrowestTy->getScalarSizeInBits() - 1);
4952 APInt MaximalRepresentableShiftAmount =
4954 if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
4955 return nullptr;
4956
4957 // Can we fold (XShAmt+YShAmt) ?
4958 auto *NewShAmt = dyn_cast_or_null<Constant>(
4959 simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
4960 /*isNUW=*/false, SQ.getWithInstruction(&I)));
4961 if (!NewShAmt)
4962 return nullptr;
4963 if (NewShAmt->getType() != WidestTy) {
4964 NewShAmt =
4965 ConstantFoldCastOperand(Instruction::ZExt, NewShAmt, WidestTy, SQ.DL);
4966 if (!NewShAmt)
4967 return nullptr;
4968 }
4969 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
4970
4971 // Is the new shift amount smaller than the bit width?
4972 // FIXME: could also rely on ConstantRange.
4973 if (!match(NewShAmt,
4975 APInt(WidestBitWidth, WidestBitWidth))))
4976 return nullptr;
4977
4978 // An extra legality check is needed if we had trunc-of-lshr.
4979 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
4980 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
4981 WidestShift]() {
4982 // It isn't obvious whether it's worth it to analyze non-constants here.
4983 // Also, let's basically give up on non-splat cases, pessimizing vectors.
4984 // If *any* of these preconditions matches we can perform the fold.
4985 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
4986 ? NewShAmt->getSplatValue()
4987 : NewShAmt;
4988 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
4989 if (NewShAmtSplat &&
4990 (NewShAmtSplat->isNullValue() ||
4991 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
4992 return true;
4993 // We consider *min* leading zeros so a single outlier
4994 // blocks the transform as opposed to allowing it.
4995 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
4997 unsigned MinLeadZero = Known.countMinLeadingZeros();
4998 // If the value being shifted has at most lowest bit set we can fold.
4999 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5000 if (MaxActiveBits <= 1)
5001 return true;
5002 // Precondition: NewShAmt u<= countLeadingZeros(C)
5003 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
5004 return true;
5005 }
5006 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
5008 unsigned MinLeadZero = Known.countMinLeadingZeros();
5009 // If the value being shifted has at most lowest bit set we can fold.
5010 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5011 if (MaxActiveBits <= 1)
5012 return true;
5013 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
5014 if (NewShAmtSplat) {
5015 APInt AdjNewShAmt =
5016 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
5017 if (AdjNewShAmt.ule(MinLeadZero))
5018 return true;
5019 }
5020 }
5021 return false; // Can't tell if it's ok.
5022 };
5023 if (!CanFold())
5024 return nullptr;
5025 }
5026
5027 // All good, we can do this fold.
5028 X = Builder.CreateZExt(X, WidestTy);
5029 Y = Builder.CreateZExt(Y, WidestTy);
5030 // The shift is the same that was for X.
5031 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
5032 ? Builder.CreateLShr(X, NewShAmt)
5033 : Builder.CreateShl(X, NewShAmt);
5034 Value *T1 = Builder.CreateAnd(T0, Y);
5035 return Builder.CreateICmp(I.getPredicate(), T1,
5036 Constant::getNullValue(WidestTy));
5037}
5038
5039/// Fold
5040/// (-1 u/ x) u< y
5041/// ((x * y) ?/ x) != y
5042/// to
5043/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
5044/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
5045/// will mean that we are looking for the opposite answer.
5047 CmpPredicate Pred;
5048 Value *X, *Y;
5050 Instruction *Div;
5051 bool NeedNegation;
5052 // Look for: (-1 u/ x) u</u>= y
5053 if (!I.isEquality() &&
5054 match(&I, m_c_ICmp(Pred,
5056 m_Instruction(Div)),
5057 m_Value(Y)))) {
5058 Mul = nullptr;
5059
5060 // Are we checking that overflow does not happen, or does happen?
5061 switch (Pred) {
5063 NeedNegation = false;
5064 break; // OK
5066 NeedNegation = true;
5067 break; // OK
5068 default:
5069 return nullptr; // Wrong predicate.
5070 }
5071 } else // Look for: ((x * y) / x) !=/== y
5072 if (I.isEquality() &&
5073 match(&I, m_c_ICmp(Pred, m_Value(Y),
5076 m_Value(X)),
5078 m_Deferred(X))),
5079 m_Instruction(Div))))) {
5080 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
5081 } else
5082 return nullptr;
5083
5085 // If the pattern included (x * y), we'll want to insert new instructions
5086 // right before that original multiplication so that we can replace it.
5087 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
5088 if (MulHadOtherUses)
5089 Builder.SetInsertPoint(Mul);
5090
5091 Value *Call = Builder.CreateIntrinsic(
5092 Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
5093 : Intrinsic::smul_with_overflow,
5094 X->getType(), {X, Y}, /*FMFSource=*/nullptr, "mul");
5095
5096 // If the multiplication was used elsewhere, to ensure that we don't leave
5097 // "duplicate" instructions, replace uses of that original multiplication
5098 // with the multiplication result from the with.overflow intrinsic.
5099 if (MulHadOtherUses)
5100 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
5101
5102 Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
5103 if (NeedNegation) // This technically increases instruction count.
5104 Res = Builder.CreateNot(Res, "mul.not.ov");
5105
5106 // If we replaced the mul, erase it. Do this after all uses of Builder,
5107 // as the mul is used as insertion point.
5108 if (MulHadOtherUses)
5110
5111 return Res;
5112}
5113
5115 InstCombiner::BuilderTy &Builder) {
5116 CmpPredicate Pred;
5117 Value *X;
5118 if (match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) {
5119
5120 if (ICmpInst::isSigned(Pred))
5121 Pred = ICmpInst::getSwappedPredicate(Pred);
5122 else if (ICmpInst::isUnsigned(Pred))
5123 Pred = ICmpInst::getSignedPredicate(Pred);
5124 // else for equality-comparisons just keep the predicate.
5125
5126 return ICmpInst::Create(Instruction::ICmp, Pred, X,
5127 Constant::getNullValue(X->getType()), I.getName());
5128 }
5129
5130 // A value is not equal to its negation unless that value is 0 or
5131 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
5132 if (match(&I, m_c_ICmp(Pred, m_OneUse(m_Neg(m_Value(X))), m_Deferred(X))) &&
5133 ICmpInst::isEquality(Pred)) {
5134 Type *Ty = X->getType();
5135 uint32_t BitWidth = Ty->getScalarSizeInBits();
5136 Constant *MaxSignedVal =
5137 ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
5138 Value *And = Builder.CreateAnd(X, MaxSignedVal);
5139 Constant *Zero = Constant::getNullValue(Ty);
5140 return CmpInst::Create(Instruction::ICmp, Pred, And, Zero);
5141 }
5142
5143 return nullptr;
5144}
5145
5147 InstCombinerImpl &IC) {
5148 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5149 // Normalize and operand as operand 0.
5150 CmpInst::Predicate Pred = I.getPredicate();
5151 if (match(Op1, m_c_And(m_Specific(Op0), m_Value()))) {
5152 std::swap(Op0, Op1);
5153 Pred = ICmpInst::getSwappedPredicate(Pred);
5154 }
5155
5156 if (!match(Op0, m_c_And(m_Specific(Op1), m_Value(A))))
5157 return nullptr;
5158
5159 // (icmp (X & Y) u< X --> (X & Y) != X
5160 if (Pred == ICmpInst::ICMP_ULT)
5161 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5162
5163 // (icmp (X & Y) u>= X --> (X & Y) == X
5164 if (Pred == ICmpInst::ICMP_UGE)
5165 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5166
5167 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5168 // icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and
5169 // Y is non-constant. If Y is constant the `X & C == C` form is preferable
5170 // so don't do this fold.
5171 if (!match(Op1, m_ImmConstant()))
5172 if (auto *NotOp1 =
5173 IC.getFreelyInverted(Op1, !Op1->hasNUsesOrMore(3), &IC.Builder))
5174 return new ICmpInst(Pred, IC.Builder.CreateOr(A, NotOp1),
5175 Constant::getAllOnesValue(Op1->getType()));
5176 // icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.
5177 if (auto *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5178 return new ICmpInst(Pred, IC.Builder.CreateAnd(Op1, NotA),
5179 Constant::getNullValue(Op1->getType()));
5180 }
5181
5182 if (!ICmpInst::isSigned(Pred))
5183 return nullptr;
5184
5185 KnownBits KnownY = IC.computeKnownBits(A, &I);
5186 // (X & NegY) spred X --> (X & NegY) upred X
5187 if (KnownY.isNegative())
5188 return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);
5189
5190 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGT)
5191 return nullptr;
5192
5193 if (KnownY.isNonNegative())
5194 // (X & PosY) s<= X --> X s>= 0
5195 // (X & PosY) s> X --> X s< 0
5196 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
5197 Constant::getNullValue(Op1->getType()));
5198
5200 // (NegX & Y) s<= NegX --> Y s< 0
5201 // (NegX & Y) s> NegX --> Y s>= 0
5203 Constant::getNullValue(A->getType()));
5204
5205 return nullptr;
5206}
5207
5209 InstCombinerImpl &IC) {
5210 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5211
5212 // Normalize or operand as operand 0.
5213 CmpInst::Predicate Pred = I.getPredicate();
5214 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value(A)))) {
5215 std::swap(Op0, Op1);
5216 Pred = ICmpInst::getSwappedPredicate(Pred);
5217 } else if (!match(Op0, m_c_Or(m_Specific(Op1), m_Value(A)))) {
5218 return nullptr;
5219 }
5220
5221 // icmp (X | Y) u<= X --> (X | Y) == X
5222 if (Pred == ICmpInst::ICMP_ULE)
5223 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5224
5225 // icmp (X | Y) u> X --> (X | Y) != X
5226 if (Pred == ICmpInst::ICMP_UGT)
5227 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5228
5229 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5230 // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
5231 if (Value *NotOp1 = IC.getFreelyInverted(
5232 Op1, !isa<Constant>(Op1) && !Op1->hasNUsesOrMore(3), &IC.Builder))
5233 return new ICmpInst(Pred, IC.Builder.CreateAnd(A, NotOp1),
5234 Constant::getNullValue(Op1->getType()));
5235 // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.
5236 if (Value *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5237 return new ICmpInst(Pred, IC.Builder.CreateOr(Op1, NotA),
5238 Constant::getAllOnesValue(Op1->getType()));
5239 }
5240 return nullptr;
5241}
5242
5244 InstCombinerImpl &IC) {
5245 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5246 // Normalize xor operand as operand 0.
5247 CmpInst::Predicate Pred = I.getPredicate();
5248 if (match(Op1, m_c_Xor(m_Specific(Op0), m_Value()))) {
5249 std::swap(Op0, Op1);
5250 Pred = ICmpInst::getSwappedPredicate(Pred);
5251 }
5252 if (!match(Op0, m_c_Xor(m_Specific(Op1), m_Value(A))))
5253 return nullptr;
5254
5255 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
5256 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
5257 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
5258 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
5260 if (PredOut != Pred && isKnownNonZero(A, Q))
5261 return new ICmpInst(PredOut, Op0, Op1);
5262
5263 // These transform work when A is negative.
5264 // X s< X^A, X s<= X^A, X u> X^A, X u>= X^A --> X s< 0
5265 // X s> X^A, X s>= X^A, X u< X^A, X u<= X^A --> X s>= 0
5266 if (match(A, m_Negative())) {
5267 CmpInst::Predicate NewPred;
5268 switch (ICmpInst::getStrictPredicate(Pred)) {
5269 default:
5270 return nullptr;
5271 case ICmpInst::ICMP_SLT:
5272 case ICmpInst::ICMP_UGT:
5273 NewPred = ICmpInst::ICMP_SLT;
5274 break;
5275 case ICmpInst::ICMP_SGT:
5276 case ICmpInst::ICMP_ULT:
5277 NewPred = ICmpInst::ICMP_SGE;
5278 break;
5279 }
5280 Constant *Const = Constant::getNullValue(Op0->getType());
5281 return new ICmpInst(NewPred, Op0, Const);
5282 }
5283
5284 return nullptr;
5285}
5286
5287/// Return true if X is a multiple of C.
5288/// TODO: Handle non-power-of-2 factors.
5289static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q) {
5290 if (C.isOne())
5291 return true;
5292
5293 if (!C.isPowerOf2())
5294 return false;
5295
5296 return MaskedValueIsZero(X, C - 1, Q);
5297}
5298
5299/// Try to fold icmp (binop), X or icmp X, (binop).
5300/// TODO: A large part of this logic is duplicated in InstSimplify's
5301/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
5302/// duplication.
5304 const SimplifyQuery &SQ) {
5305 const SimplifyQuery Q = SQ.getWithInstruction(&I);
5306 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5307
5308 // Special logic for binary operators.
5311 if (!BO0 && !BO1)
5312 return nullptr;
5313
5314 if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
5315 return NewICmp;
5316
5317 const CmpInst::Predicate Pred = I.getPredicate();
5318 Value *X;
5319
5320 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
5321 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
5322 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
5323 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5324 return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
5325 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
5326 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
5327 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5328 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
5329
5330 {
5331 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
5332 Constant *C;
5333 if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
5334 m_ImmConstant(C)))) &&
5335 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
5337 return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
5338 }
5339 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
5340 if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
5341 m_ImmConstant(C)))) &&
5342 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
5344 return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
5345 }
5346 }
5347
5348 // (icmp eq/ne (X, -P2), INT_MIN)
5349 // -> (icmp slt/sge X, INT_MIN + P2)
5350 if (ICmpInst::isEquality(Pred) && BO0 &&
5351 match(I.getOperand(1), m_SignMask()) &&
5353 // Will Constant fold.
5354 Value *NewC = Builder.CreateSub(I.getOperand(1), BO0->getOperand(1));
5355 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SLT
5357 BO0->getOperand(0), NewC);
5358 }
5359
5360 {
5361 // Similar to above: an unsigned overflow comparison may use offset + mask:
5362 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
5363 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
5364 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
5365 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
5366 BinaryOperator *BO;
5367 const APInt *C;
5368 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
5369 match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5371 CmpInst::Predicate NewPred =
5373 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5374 return new ICmpInst(NewPred, Op1, Zero);
5375 }
5376
5377 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5378 match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5380 CmpInst::Predicate NewPred =
5382 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5383 return new ICmpInst(NewPred, Op0, Zero);
5384 }
5385 }
5386
5387 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
5388 bool Op0HasNUW = false, Op1HasNUW = false;
5389 bool Op0HasNSW = false, Op1HasNSW = false;
5390 // Analyze the case when either Op0 or Op1 is an add instruction.
5391 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
5392 auto hasNoWrapProblem = [](const BinaryOperator &BO, CmpInst::Predicate Pred,
5393 bool &HasNSW, bool &HasNUW) -> bool {
5395 HasNUW = BO.hasNoUnsignedWrap();
5396 HasNSW = BO.hasNoSignedWrap();
5397 return ICmpInst::isEquality(Pred) ||
5398 (CmpInst::isUnsigned(Pred) && HasNUW) ||
5399 (CmpInst::isSigned(Pred) && HasNSW);
5400 } else if (BO.getOpcode() == Instruction::Or) {
5401 HasNUW = true;
5402 HasNSW = true;
5403 return true;
5404 } else {
5405 return false;
5406 }
5407 };
5408 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5409
5410 if (BO0) {
5411 match(BO0, m_AddLike(m_Value(A), m_Value(B)));
5412 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5413 }
5414 if (BO1) {
5415 match(BO1, m_AddLike(m_Value(C), m_Value(D)));
5416 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5417 }
5418
5419 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5420 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5421 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5422 return new ICmpInst(Pred, A == Op1 ? B : A,
5423 Constant::getNullValue(Op1->getType()));
5424
5425 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5426 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5427 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5428 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
5429 C == Op0 ? D : C);
5430
5431 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
5432 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
5433 NoOp1WrapProblem) {
5434 // Determine Y and Z in the form icmp (X+Y), (X+Z).
5435 Value *Y, *Z;
5436 if (A == C) {
5437 // C + B == C + D -> B == D
5438 Y = B;
5439 Z = D;
5440 } else if (A == D) {
5441 // D + B == C + D -> B == C
5442 Y = B;
5443 Z = C;
5444 } else if (B == C) {
5445 // A + C == C + D -> A == D
5446 Y = A;
5447 Z = D;
5448 } else {
5449 assert(B == D);
5450 // A + D == C + D -> A == C
5451 Y = A;
5452 Z = C;
5453 }
5454 return new ICmpInst(Pred, Y, Z);
5455 }
5456
5457 if (ICmpInst::isRelational(Pred)) {
5458 // Return if both X and Y is divisible by Z/-Z.
5459 // TODO: Generalize to check if (X - Y) is divisible by Z/-Z.
5460 auto ShareCommonDivisor = [&Q](Value *X, Value *Y, Value *Z,
5461 bool IsNegative) -> bool {
5462 const APInt *OffsetC;
5463 if (!match(Z, m_APInt(OffsetC)))
5464 return false;
5465
5466 // Fast path for Z == 1/-1.
5467 if (IsNegative ? OffsetC->isAllOnes() : OffsetC->isOne())
5468 return true;
5469
5470 APInt C = *OffsetC;
5471 if (IsNegative)
5472 C.negate();
5473 // Note: -INT_MIN is also negative.
5474 if (!C.isStrictlyPositive())
5475 return false;
5476
5477 return isMultipleOf(X, C, Q) && isMultipleOf(Y, C, Q);
5478 };
5479
5480 // TODO: The subtraction-related identities shown below also hold, but
5481 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
5482 // wouldn't happen even if they were implemented.
5483 //
5484 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5485 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5486 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5487 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5488
5489 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5490 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5491 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5492 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5493 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5494 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5495 if (A && NoOp0WrapProblem &&
5496 ShareCommonDivisor(A, Op1, B,
5497 ICmpInst::isLT(Pred) || ICmpInst::isGE(Pred)))
5499 Op1);
5500
5501 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5502 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5503 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5504 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5505 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5506 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5507 if (C && NoOp1WrapProblem &&
5508 ShareCommonDivisor(Op0, C, D,
5509 ICmpInst::isGT(Pred) || ICmpInst::isLE(Pred)))
5511 C);
5512 }
5513
5514 // if C1 has greater magnitude than C2:
5515 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5516 // s.t. C3 = C1 - C2
5517 //
5518 // if C2 has greater magnitude than C1:
5519 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5520 // s.t. C3 = C2 - C1
5521 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5522 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5523 const APInt *AP1, *AP2;
5524 // TODO: Support non-uniform vectors.
5525 // TODO: Allow poison passthrough if B or D's element is poison.
5526 if (match(B, m_APIntAllowPoison(AP1)) &&
5527 match(D, m_APIntAllowPoison(AP2)) &&
5528 AP1->isNegative() == AP2->isNegative()) {
5529 APInt AP1Abs = AP1->abs();
5530 APInt AP2Abs = AP2->abs();
5531 if (AP1Abs.uge(AP2Abs)) {
5532 APInt Diff = *AP1 - *AP2;
5533 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5534 Value *NewAdd = Builder.CreateAdd(
5535 A, C3, "", Op0HasNUW && Diff.ule(*AP1), Op0HasNSW);
5536 return new ICmpInst(Pred, NewAdd, C);
5537 } else {
5538 APInt Diff = *AP2 - *AP1;
5539 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5540 Value *NewAdd = Builder.CreateAdd(
5541 C, C3, "", Op1HasNUW && Diff.ule(*AP2), Op1HasNSW);
5542 return new ICmpInst(Pred, A, NewAdd);
5543 }
5544 }
5545 Constant *Cst1, *Cst2;
5546 if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
5547 ICmpInst::isEquality(Pred)) {
5548 Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
5549 Value *NewAdd = Builder.CreateAdd(C, Diff);
5550 return new ICmpInst(Pred, A, NewAdd);
5551 }
5552 }
5553
5554 // Analyze the case when either Op0 or Op1 is a sub instruction.
5555 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5556 A = nullptr;
5557 B = nullptr;
5558 C = nullptr;
5559 D = nullptr;
5560 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5561 A = BO0->getOperand(0);
5562 B = BO0->getOperand(1);
5563 }
5564 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5565 C = BO1->getOperand(0);
5566 D = BO1->getOperand(1);
5567 }
5568
5569 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5570 if (A == Op1 && NoOp0WrapProblem)
5571 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
5572 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5573 if (C == Op0 && NoOp1WrapProblem)
5574 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
5575
5576 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5577 // (A - B) u>/u<= A --> B u>/u<= A
5578 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5579 return new ICmpInst(Pred, B, A);
5580 // C u</u>= (C - D) --> C u</u>= D
5581 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5582 return new ICmpInst(Pred, C, D);
5583 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5584 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5585 isKnownNonZero(B, Q))
5587 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5588 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5589 isKnownNonZero(D, Q))
5591
5592 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
5593 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
5594 return new ICmpInst(Pred, A, C);
5595
5596 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
5597 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
5598 return new ICmpInst(Pred, D, B);
5599
5600 // icmp (0-X) < cst --> x > -cst
5601 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
5602 Value *X;
5603 if (match(BO0, m_Neg(m_Value(X))))
5604 if (Constant *RHSC = dyn_cast<Constant>(Op1))
5605 if (RHSC->isNotMinSignedValue())
5606 return new ICmpInst(I.getSwappedPredicate(), X,
5607 ConstantExpr::getNeg(RHSC));
5608 }
5609
5610 if (Instruction *R = foldICmpXorXX(I, Q, *this))
5611 return R;
5612 if (Instruction *R = foldICmpOrXX(I, Q, *this))
5613 return R;
5614
5615 {
5616 // Try to remove shared multiplier from comparison:
5617 // X * Z pred Y * Z
5618 Value *X, *Y, *Z;
5619 if ((match(Op0, m_Mul(m_Value(X), m_Value(Z))) &&
5620 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))) ||
5621 (match(Op0, m_Mul(m_Value(Z), m_Value(X))) &&
5622 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y))))) {
5623 if (ICmpInst::isSigned(Pred)) {
5624 if (Op0HasNSW && Op1HasNSW) {
5625 KnownBits ZKnown = computeKnownBits(Z, &I);
5626 if (ZKnown.isStrictlyPositive())
5627 return new ICmpInst(Pred, X, Y);
5628 if (ZKnown.isNegative())
5629 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), X, Y);
5631 SQ.getWithInstruction(&I));
5632 if (LessThan && match(LessThan, m_One()))
5633 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Z,
5634 Constant::getNullValue(Z->getType()));
5635 Value *GreaterThan = simplifyICmpInst(ICmpInst::ICMP_SGT, X, Y,
5636 SQ.getWithInstruction(&I));
5637 if (GreaterThan && match(GreaterThan, m_One()))
5638 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5639 }
5640 } else {
5641 bool NonZero;
5642 if (ICmpInst::isEquality(Pred)) {
5643 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5644 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5645 isKnownNonEqual(X, Y, SQ))
5646 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5647
5648 KnownBits ZKnown = computeKnownBits(Z, &I);
5649 // if Z % 2 != 0
5650 // X * Z eq/ne Y * Z -> X eq/ne Y
5651 if (ZKnown.countMaxTrailingZeros() == 0)
5652 return new ICmpInst(Pred, X, Y);
5653 NonZero = !ZKnown.One.isZero() || isKnownNonZero(Z, Q);
5654 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5655 // X * Z eq/ne Y * Z -> X eq/ne Y
5656 if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)
5657 return new ICmpInst(Pred, X, Y);
5658 } else
5659 NonZero = isKnownNonZero(Z, Q);
5660
5661 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5662 // X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
5663 if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)
5664 return new ICmpInst(Pred, X, Y);
5665 }
5666 }
5667 }
5668
5669 BinaryOperator *SRem = nullptr;
5670 // icmp (srem X, Y), Y
5671 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
5672 SRem = BO0;
5673 // icmp Y, (srem X, Y)
5674 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5675 Op0 == BO1->getOperand(1))
5676 SRem = BO1;
5677 if (SRem) {
5678 // We don't check hasOneUse to avoid increasing register pressure because
5679 // the value we use is the same value this instruction was already using.
5680 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
5681 default:
5682 break;
5683 case ICmpInst::ICMP_EQ:
5684 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5685 case ICmpInst::ICMP_NE:
5686 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5687 case ICmpInst::ICMP_SGT:
5688 case ICmpInst::ICMP_SGE:
5689 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
5691 case ICmpInst::ICMP_SLT:
5692 case ICmpInst::ICMP_SLE:
5693 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
5695 }
5696 }
5697
5698 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5699 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5700 BO0->getOperand(1) == BO1->getOperand(1)) {
5701 switch (BO0->getOpcode()) {
5702 default:
5703 break;
5704 case Instruction::Add:
5705 case Instruction::Sub:
5706 case Instruction::Xor: {
5707 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5708 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5709
5710 const APInt *C;
5711 if (match(BO0->getOperand(1), m_APInt(C))) {
5712 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5713 if (C->isSignMask()) {
5714 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5715 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5716 }
5717
5718 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5719 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5720 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5721 NewPred = I.getSwappedPredicate(NewPred);
5722 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5723 }
5724 }
5725 break;
5726 }
5727 case Instruction::Mul: {
5728 if (!I.isEquality())
5729 break;
5730
5731 const APInt *C;
5732 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
5733 !C->isOne()) {
5734 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5735 // Mask = -1 >> count-trailing-zeros(C).
5736 if (unsigned TZs = C->countr_zero()) {
5737 Constant *Mask = ConstantInt::get(
5738 BO0->getType(),
5739 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
5740 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
5741 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
5742 return new ICmpInst(Pred, And1, And2);
5743 }
5744 }
5745 break;
5746 }
5747 case Instruction::UDiv:
5748 case Instruction::LShr:
5749 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
5750 break;
5751 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5752
5753 case Instruction::SDiv:
5754 if (!(I.isEquality() || match(BO0->getOperand(1), m_NonNegative())) ||
5755 !BO0->isExact() || !BO1->isExact())
5756 break;
5757 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5758
5759 case Instruction::AShr:
5760 if (!BO0->isExact() || !BO1->isExact())
5761 break;
5762 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5763
5764 case Instruction::Shl: {
5765 bool NUW = Op0HasNUW && Op1HasNUW;
5766 bool NSW = Op0HasNSW && Op1HasNSW;
5767 if (!NUW && !NSW)
5768 break;
5769 if (!NSW && I.isSigned())
5770 break;
5771 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5772 }
5773 }
5774 }
5775
5776 if (BO0) {
5777 // Transform A & (L - 1) `ult` L --> L != 0
5778 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
5779 auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
5780
5781 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5782 auto *Zero = Constant::getNullValue(BO0->getType());
5783 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5784 }
5785 }
5786
5787 // For unsigned predicates / eq / ne:
5788 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5789 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5790 if (!ICmpInst::isSigned(Pred)) {
5791 if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
5792 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5793 Constant::getNullValue(Op1->getType()));
5794 else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
5795 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5796 Constant::getNullValue(Op0->getType()), Op0);
5797 }
5798
5800 return replaceInstUsesWith(I, V);
5801
5802 if (Instruction *R = foldICmpAndXX(I, Q, *this))
5803 return R;
5804
5806 return replaceInstUsesWith(I, V);
5807
5809 return replaceInstUsesWith(I, V);
5810
5811 return nullptr;
5812}
5813
5814/// Fold icmp Pred min|max(X, Y), Z.
5817 Value *Z, CmpPredicate Pred) {
5818 Value *X = MinMax->getLHS();
5819 Value *Y = MinMax->getRHS();
5820 if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5821 return nullptr;
5822 if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {
5823 // Revert the transform signed pred -> unsigned pred
5824 // TODO: We can flip the signedness of predicate if both operands of icmp
5825 // are negative.
5826 if (isKnownNonNegative(Z, SQ.getWithInstruction(&I)) &&
5827 isKnownNonNegative(MinMax, SQ.getWithInstruction(&I))) {
5829 } else
5830 return nullptr;
5831 }
5832 SimplifyQuery Q = SQ.getWithInstruction(&I);
5833 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5834 if (!Val)
5835 return std::nullopt;
5836 if (match(Val, m_One()))
5837 return true;
5838 if (match(Val, m_Zero()))
5839 return false;
5840 return std::nullopt;
5841 };
5842 // Remove samesign here since it is illegal to keep it when we speculatively
5843 // execute comparisons. For example, `icmp samesign ult umax(X, -46), -32`
5844 // cannot be decomposed into `(icmp samesign ult X, -46) or (icmp samesign ult
5845 // -46, -32)`. `X` is allowed to be non-negative here.
5846 Pred = Pred.dropSameSign();
5847 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, X, Z, Q));
5848 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, Y, Z, Q));
5849 if (!CmpXZ.has_value() && !CmpYZ.has_value())
5850 return nullptr;
5851 if (!CmpXZ.has_value()) {
5852 std::swap(X, Y);
5853 std::swap(CmpXZ, CmpYZ);
5854 }
5855
5856 auto FoldIntoCmpYZ = [&]() -> Instruction * {
5857 if (CmpYZ.has_value())
5858 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *CmpYZ));
5859 return ICmpInst::Create(Instruction::ICmp, Pred, Y, Z);
5860 };
5861
5862 switch (Pred) {
5863 case ICmpInst::ICMP_EQ:
5864 case ICmpInst::ICMP_NE: {
5865 // If X == Z:
5866 // Expr Result
5867 // min(X, Y) == Z X <= Y
5868 // max(X, Y) == Z X >= Y
5869 // min(X, Y) != Z X > Y
5870 // max(X, Y) != Z X < Y
5871 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5872 ICmpInst::Predicate NewPred =
5873 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
5874 if (Pred == ICmpInst::ICMP_NE)
5875 NewPred = ICmpInst::getInversePredicate(NewPred);
5876 return ICmpInst::Create(Instruction::ICmp, NewPred, X, Y);
5877 }
5878 // Otherwise (X != Z):
5879 ICmpInst::Predicate NewPred = MinMax->getPredicate();
5880 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5881 if (!MinMaxCmpXZ.has_value()) {
5882 std::swap(X, Y);
5883 std::swap(CmpXZ, CmpYZ);
5884 // Re-check pre-condition X != Z
5885 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5886 break;
5887 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5888 }
5889 if (!MinMaxCmpXZ.has_value())
5890 break;
5891 if (*MinMaxCmpXZ) {
5892 // Expr Fact Result
5893 // min(X, Y) == Z X < Z false
5894 // max(X, Y) == Z X > Z false
5895 // min(X, Y) != Z X < Z true
5896 // max(X, Y) != Z X > Z true
5897 return replaceInstUsesWith(
5898 I, ConstantInt::getBool(I.getType(), Pred == ICmpInst::ICMP_NE));
5899 } else {
5900 // Expr Fact Result
5901 // min(X, Y) == Z X > Z Y == Z
5902 // max(X, Y) == Z X < Z Y == Z
5903 // min(X, Y) != Z X > Z Y != Z
5904 // max(X, Y) != Z X < Z Y != Z
5905 return FoldIntoCmpYZ();
5906 }
5907 break;
5908 }
5909 case ICmpInst::ICMP_SLT:
5910 case ICmpInst::ICMP_ULT:
5911 case ICmpInst::ICMP_SLE:
5912 case ICmpInst::ICMP_ULE:
5913 case ICmpInst::ICMP_SGT:
5914 case ICmpInst::ICMP_UGT:
5915 case ICmpInst::ICMP_SGE:
5916 case ICmpInst::ICMP_UGE: {
5917 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(Pred);
5918 if (*CmpXZ) {
5919 if (IsSame) {
5920 // Expr Fact Result
5921 // min(X, Y) < Z X < Z true
5922 // min(X, Y) <= Z X <= Z true
5923 // max(X, Y) > Z X > Z true
5924 // max(X, Y) >= Z X >= Z true
5925 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5926 } else {
5927 // Expr Fact Result
5928 // max(X, Y) < Z X < Z Y < Z
5929 // max(X, Y) <= Z X <= Z Y <= Z
5930 // min(X, Y) > Z X > Z Y > Z
5931 // min(X, Y) >= Z X >= Z Y >= Z
5932 return FoldIntoCmpYZ();
5933 }
5934 } else {
5935 if (IsSame) {
5936 // Expr Fact Result
5937 // min(X, Y) < Z X >= Z Y < Z
5938 // min(X, Y) <= Z X > Z Y <= Z
5939 // max(X, Y) > Z X <= Z Y > Z
5940 // max(X, Y) >= Z X < Z Y >= Z
5941 return FoldIntoCmpYZ();
5942 } else {
5943 // Expr Fact Result
5944 // max(X, Y) < Z X >= Z false
5945 // max(X, Y) <= Z X > Z false
5946 // min(X, Y) > Z X <= Z false
5947 // min(X, Y) >= Z X < Z false
5948 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5949 }
5950 }
5951 break;
5952 }
5953 default:
5954 break;
5955 }
5956
5957 return nullptr;
5958}
5959
5960/// Match and fold patterns like:
5961/// icmp eq/ne X, min(max(X, Lo), Hi)
5962/// which represents a range check and can be represented as a ConstantRange.
5963///
5964/// For icmp eq, build ConstantRange [Lo, Hi + 1) and convert to:
5965/// (X - Lo) u< (Hi + 1 - Lo)
5966/// For icmp ne, build ConstantRange [Hi + 1, Lo) and convert to:
5967/// (X - (Hi + 1)) u< (Lo - (Hi + 1))
5969 MinMaxIntrinsic *Min) {
5970 if (!I.isEquality() || !Min->hasOneUse() || !Min->isMin())
5971 return nullptr;
5972
5973 const APInt *Lo = nullptr, *Hi = nullptr;
5974 if (Min->isSigned()) {
5975 if (!match(Min->getLHS(), m_OneUse(m_SMax(m_Specific(X), m_APInt(Lo)))) ||
5976 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->slt(*Hi))
5977 return nullptr;
5978 } else {
5979 if (!match(Min->getLHS(), m_OneUse(m_UMax(m_Specific(X), m_APInt(Lo)))) ||
5980 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->ult(*Hi))
5981 return nullptr;
5982 }
5983
5986 APInt C, Offset;
5987 if (I.getPredicate() == ICmpInst::ICMP_EQ)
5988 CR.getEquivalentICmp(Pred, C, Offset);
5989 else
5990 CR.inverse().getEquivalentICmp(Pred, C, Offset);
5991
5992 if (!Offset.isZero())
5993 X = Builder.CreateAdd(X, ConstantInt::get(X->getType(), Offset));
5994
5995 return replaceInstUsesWith(
5996 I, Builder.CreateICmp(Pred, X, ConstantInt::get(X->getType(), C)));
5997}
5998
5999// Canonicalize checking for a power-of-2-or-zero value:
6001 InstCombiner::BuilderTy &Builder) {
6002 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6003 const CmpInst::Predicate Pred = I.getPredicate();
6004 Value *A = nullptr;
6005 bool CheckIs;
6006 if (I.isEquality()) {
6007 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
6008 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
6009 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
6010 m_Deferred(A)))) ||
6011 !match(Op1, m_ZeroInt()))
6012 A = nullptr;
6013
6014 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
6015 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
6016 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
6017 A = Op1;
6018 else if (match(Op1,
6020 A = Op0;
6021
6022 CheckIs = Pred == ICmpInst::ICMP_EQ;
6023 } else if (ICmpInst::isUnsigned(Pred)) {
6024 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
6025 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
6026
6027 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
6029 m_Specific(Op1))))) {
6030 A = Op1;
6031 CheckIs = Pred == ICmpInst::ICMP_UGE;
6032 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
6034 m_Specific(Op0))))) {
6035 A = Op0;
6036 CheckIs = Pred == ICmpInst::ICMP_ULE;
6037 }
6038 }
6039
6040 if (A) {
6041 Type *Ty = A->getType();
6042 Value *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
6043 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
6044 ConstantInt::get(Ty, 2))
6045 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
6046 ConstantInt::get(Ty, 1));
6047 }
6048
6049 return nullptr;
6050}
6051
6052/// Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
6053using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
6055 bool AllowRecursion) {
6057 if (!Inst || !Inst->hasOneUse())
6058 return;
6059
6060 switch (Inst->getOpcode()) {
6061 case Instruction::Add:
6062 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(1));
6063 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(0));
6064 break;
6065 case Instruction::Sub:
6066 Offsets.emplace_back(Instruction::Add, Inst->getOperand(1));
6067 break;
6068 case Instruction::Xor:
6069 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(1));
6070 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(0));
6071 break;
6072 case Instruction::Shl:
6073 if (Inst->hasNoSignedWrap())
6074 Offsets.emplace_back(Instruction::AShr, Inst->getOperand(1));
6075 if (Inst->hasNoUnsignedWrap())
6076 Offsets.emplace_back(Instruction::LShr, Inst->getOperand(1));
6077 break;
6078 case Instruction::Select:
6079 if (AllowRecursion) {
6080 collectOffsetOp(Inst->getOperand(1), Offsets, /*AllowRecursion=*/false);
6081 collectOffsetOp(Inst->getOperand(2), Offsets, /*AllowRecursion=*/false);
6082 }
6083 break;
6084 default:
6085 break;
6086 }
6087}
6088
6090
6095
6097 return {OffsetKind::Invalid, nullptr, nullptr, nullptr, nullptr};
6098 }
6100 return {OffsetKind::Value, V, nullptr, nullptr, nullptr};
6101 }
6102 static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV,
6104 return {OffsetKind::Select, Cond, TrueV, FalseV, MDFrom};
6105 }
6106 bool isValid() const { return Kind != OffsetKind::Invalid; }
6108 switch (Kind) {
6110 llvm_unreachable("Invalid offset result");
6111 case OffsetKind::Value:
6112 return V0;
6113 case OffsetKind::Select:
6114 return Builder.CreateSelect(
6115 V0, V1, V2, "", ProfcheckDisableMetadataFixes ? nullptr : MDFrom);
6116 }
6117 llvm_unreachable("Unknown OffsetKind enum");
6118 }
6119};
6120
6121/// Offset both sides of an equality icmp to see if we can save some
6122/// instructions: icmp eq/ne X, Y -> icmp eq/ne X op Z, Y op Z.
6123/// Note: This operation should not introduce poison.
6125 InstCombiner::BuilderTy &Builder,
6126 const SimplifyQuery &SQ) {
6127 assert(I.isEquality() && "Expected an equality icmp");
6128 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6129 if (!Op0->getType()->isIntOrIntVectorTy())
6130 return nullptr;
6131
6132 SmallVector<OffsetOp, 4> OffsetOps;
6133 collectOffsetOp(Op0, OffsetOps, /*AllowRecursion=*/true);
6134 collectOffsetOp(Op1, OffsetOps, /*AllowRecursion=*/true);
6135
6136 auto ApplyOffsetImpl = [&](Value *V, unsigned BinOpc, Value *RHS) -> Value * {
6137 switch (BinOpc) {
6138 // V = shl nsw X, RHS => X = ashr V, RHS
6139 case Instruction::AShr: {
6140 const APInt *CV, *CRHS;
6141 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6142 CV->ashr(*CRHS).shl(*CRHS) == *CV) &&
6144 return nullptr;
6145 break;
6146 }
6147 // V = shl nuw X, RHS => X = lshr V, RHS
6148 case Instruction::LShr: {
6149 const APInt *CV, *CRHS;
6150 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6151 CV->lshr(*CRHS).shl(*CRHS) == *CV) &&
6153 return nullptr;
6154 break;
6155 }
6156 default:
6157 break;
6158 }
6159
6160 Value *Simplified = simplifyBinOp(BinOpc, V, RHS, SQ);
6161 if (!Simplified)
6162 return nullptr;
6163 // Reject constant expressions as they don't simplify things.
6164 if (isa<Constant>(Simplified) && !match(Simplified, m_ImmConstant()))
6165 return nullptr;
6166 // Check if the transformation introduces poison.
6167 return impliesPoison(RHS, V) ? Simplified : nullptr;
6168 };
6169
6170 auto ApplyOffset = [&](Value *V, unsigned BinOpc,
6171 Value *RHS) -> OffsetResult {
6172 if (auto *Sel = dyn_cast<SelectInst>(V)) {
6173 if (!Sel->hasOneUse())
6174 return OffsetResult::invalid();
6175 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc, RHS);
6176 if (!TrueVal)
6177 return OffsetResult::invalid();
6178 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc, RHS);
6179 if (!FalseVal)
6180 return OffsetResult::invalid();
6181 return OffsetResult::select(Sel->getCondition(), TrueVal, FalseVal, Sel);
6182 }
6183 if (Value *Simplified = ApplyOffsetImpl(V, BinOpc, RHS))
6184 return OffsetResult::value(Simplified);
6185 return OffsetResult::invalid();
6186 };
6187
6188 for (auto [BinOp, RHS] : OffsetOps) {
6189 auto BinOpc = static_cast<unsigned>(BinOp);
6190
6191 auto Op0Result = ApplyOffset(Op0, BinOpc, RHS);
6192 if (!Op0Result.isValid())
6193 continue;
6194 auto Op1Result = ApplyOffset(Op1, BinOpc, RHS);
6195 if (!Op1Result.isValid())
6196 continue;
6197
6198 Value *NewLHS = Op0Result.materialize(Builder);
6199 Value *NewRHS = Op1Result.materialize(Builder);
6200 return new ICmpInst(I.getPredicate(), NewLHS, NewRHS);
6201 }
6202
6203 return nullptr;
6204}
6205
6207 if (!I.isEquality())
6208 return nullptr;
6209
6210 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6211 const CmpInst::Predicate Pred = I.getPredicate();
6212 Value *A, *B, *C, *D;
6213 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6214 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6215 Value *OtherVal = A == Op1 ? B : A;
6216 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6217 }
6218
6219 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6220 // A^c1 == C^c2 --> A == C^(c1^c2)
6221 ConstantInt *C1, *C2;
6222 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
6223 Op1->hasOneUse()) {
6224 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
6225 Value *Xor = Builder.CreateXor(C, NC);
6226 return new ICmpInst(Pred, A, Xor);
6227 }
6228
6229 // A^B == A^D -> B == D
6230 if (A == C)
6231 return new ICmpInst(Pred, B, D);
6232 if (A == D)
6233 return new ICmpInst(Pred, B, C);
6234 if (B == C)
6235 return new ICmpInst(Pred, A, D);
6236 if (B == D)
6237 return new ICmpInst(Pred, A, C);
6238 }
6239 }
6240
6241 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
6242 // A == (A^B) -> B == 0
6243 Value *OtherVal = A == Op0 ? B : A;
6244 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6245 }
6246
6247 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6248 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
6249 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6250 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
6251
6252 if (A == C) {
6253 X = B;
6254 Y = D;
6255 Z = A;
6256 } else if (A == D) {
6257 X = B;
6258 Y = C;
6259 Z = A;
6260 } else if (B == C) {
6261 X = A;
6262 Y = D;
6263 Z = B;
6264 } else if (B == D) {
6265 X = A;
6266 Y = C;
6267 Z = B;
6268 }
6269
6270 if (X) {
6271 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
6272 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
6273 // instructions.
6274 const APInt *C0, *C1;
6275 bool XorIsNegP2 = match(X, m_APInt(C0)) && match(Y, m_APInt(C1)) &&
6276 (*C0 ^ *C1).isNegatedPowerOf2();
6277
6278 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
6279 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
6280 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
6281 int UseCnt =
6282 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
6283 (int(match(X, m_ImmConstant()) && match(Y, m_ImmConstant())));
6284 if (XorIsNegP2 || UseCnt >= 2) {
6285 // Build (X^Y) & Z
6286 Op1 = Builder.CreateXor(X, Y);
6287 Op1 = Builder.CreateAnd(Op1, Z);
6288 return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
6289 }
6290 }
6291 }
6292
6293 {
6294 // Similar to above, but specialized for constant because invert is needed:
6295 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
6296 Value *X, *Y;
6297 Constant *C;
6298 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
6299 match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
6300 Value *Xor = Builder.CreateXor(X, Y);
6301 Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
6302 return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
6303 }
6304 }
6305
6306 if (match(Op1, m_ZExt(m_Value(A))) &&
6307 (Op0->hasOneUse() || Op1->hasOneUse())) {
6308 // (B & (Pow2C-1)) == zext A --> A == trunc B
6309 // (B & (Pow2C-1)) != zext A --> A != trunc B
6310 const APInt *MaskC;
6311 if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
6312 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
6313 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
6314 }
6315
6316 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
6317 // For lshr and ashr pairs.
6318 const APInt *AP1, *AP2;
6319 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6320 match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowPoison(AP2))))) ||
6321 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6322 match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowPoison(AP2)))))) {
6323 if (*AP1 != *AP2)
6324 return nullptr;
6325 unsigned TypeBits = AP1->getBitWidth();
6326 unsigned ShAmt = AP1->getLimitedValue(TypeBits);
6327 if (ShAmt < TypeBits && ShAmt != 0) {
6328 ICmpInst::Predicate NewPred =
6330 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6331 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
6332 return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
6333 }
6334 }
6335
6336 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
6337 ConstantInt *Cst1;
6338 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
6339 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
6340 unsigned TypeBits = Cst1->getBitWidth();
6341 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
6342 if (ShAmt < TypeBits && ShAmt != 0) {
6343 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6344 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
6345 Value *And =
6346 Builder.CreateAnd(Xor, Builder.getInt(AndVal), I.getName() + ".mask");
6347 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
6348 }
6349 }
6350
6351 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
6352 // "icmp (and X, mask), cst"
6353 uint64_t ShAmt = 0;
6354 if (Op0->hasOneUse() &&
6355 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
6356 match(Op1, m_ConstantInt(Cst1)) &&
6357 // Only do this when A has multiple uses. This is most important to do
6358 // when it exposes other optimizations.
6359 !A->hasOneUse()) {
6360 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
6361
6362 if (ShAmt < ASize) {
6363 APInt MaskV =
6365 MaskV <<= ShAmt;
6366
6367 APInt CmpV = Cst1->getValue().zext(ASize);
6368 CmpV <<= ShAmt;
6369
6370 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
6371 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
6372 }
6373 }
6374
6376 return ICmp;
6377
6378 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
6379 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
6380 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
6381 // few steps of instcombine.
6382 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6383 if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
6385 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
6386 (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
6388 Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
6389 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
6391 Add, ConstantInt::get(A->getType(), C.shl(1)));
6392 }
6393
6394 // Canonicalize:
6395 // Assume B_Pow2 != 0
6396 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
6397 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
6398 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
6399 isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, &I))
6400 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
6402
6403 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
6404 isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, &I))
6405 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
6406 ConstantInt::getNullValue(Op1->getType()));
6407
6408 // Canonicalize:
6409 // icmp eq/ne X, OneUse(rotate-right(X))
6410 // -> icmp eq/ne X, rotate-left(X)
6411 // We generally try to convert rotate-right -> rotate-left, this just
6412 // canonicalizes another case.
6413 if (match(&I, m_c_ICmp(m_Value(A),
6415 m_Deferred(A), m_Deferred(A), m_Value(B))))))
6416 return new ICmpInst(
6417 Pred, A,
6418 Builder.CreateIntrinsic(Op0->getType(), Intrinsic::fshl, {A, A, B}));
6419
6420 // Canonicalize:
6421 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
6422 Constant *Cst;
6425 return new ICmpInst(Pred, Builder.CreateXor(A, B), Cst);
6426
6427 {
6428 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6429 auto m_Matcher =
6432 m_Sub(m_Value(B), m_Deferred(A)));
6433 std::optional<bool> IsZero = std::nullopt;
6434 if (match(&I, m_c_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)),
6435 m_Deferred(A))))
6436 IsZero = false;
6437 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6438 else if (match(&I,
6439 m_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)), m_Zero())))
6440 IsZero = true;
6441
6442 if (IsZero && isKnownToBeAPowerOfTwo(A, /* OrZero */ true, &I))
6443 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6444 // -> (icmp eq/ne (and X, P2), 0)
6445 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6446 // -> (icmp eq/ne (and X, P2), P2)
6447 return new ICmpInst(Pred, Builder.CreateAnd(B, A),
6448 *IsZero ? A
6449 : ConstantInt::getNullValue(A->getType()));
6450 }
6451
6452 if (auto *Res = foldICmpEqualityWithOffset(
6453 I, Builder, getSimplifyQuery().getWithInstruction(&I)))
6454 return Res;
6455
6456 return nullptr;
6457}
6458
6460 ICmpInst::Predicate Pred = ICmp.getPredicate();
6461 Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
6462
6463 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6464 // The trunc masks high bits while the compare may effectively mask low bits.
6465 Value *X;
6466 const APInt *C;
6467 if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
6468 return nullptr;
6469
6470 // This matches patterns corresponding to tests of the signbit as well as:
6471 // (trunc X) pred C2 --> (X & Mask) == C
6472 if (auto Res = decomposeBitTestICmp(Op0, Op1, Pred, /*LookThroughTrunc=*/true,
6473 /*AllowNonZeroC=*/true)) {
6474 Value *And = Builder.CreateAnd(Res->X, Res->Mask);
6475 Constant *C = ConstantInt::get(Res->X->getType(), Res->C);
6476 return new ICmpInst(Res->Pred, And, C);
6477 }
6478
6479 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6480 if (auto *II = dyn_cast<IntrinsicInst>(X)) {
6481 if (II->getIntrinsicID() == Intrinsic::cttz ||
6482 II->getIntrinsicID() == Intrinsic::ctlz) {
6483 unsigned MaxRet = SrcBits;
6484 // If the "is_zero_poison" argument is set, then we know at least
6485 // one bit is set in the input, so the result is always at least one
6486 // less than the full bitwidth of that input.
6487 if (match(II->getArgOperand(1), m_One()))
6488 MaxRet--;
6489
6490 // Make sure the destination is wide enough to hold the largest output of
6491 // the intrinsic.
6492 if (llvm::Log2_32(MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6493 if (Instruction *I =
6494 foldICmpIntrinsicWithConstant(ICmp, II, C->zext(SrcBits)))
6495 return I;
6496 }
6497 }
6498
6499 return nullptr;
6500}
6501
6503 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6504 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
6505 Value *X;
6506 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
6507 return nullptr;
6508
6509 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6510 bool IsSignedCmp = ICmp.isSigned();
6511
6512 // icmp Pred (ext X), (ext Y)
6513 Value *Y;
6514 if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
6515 bool IsZext0 = isa<ZExtInst>(ICmp.getOperand(0));
6516 bool IsZext1 = isa<ZExtInst>(ICmp.getOperand(1));
6517
6518 if (IsZext0 != IsZext1) {
6519 // If X and Y and both i1
6520 // (icmp eq/ne (zext X) (sext Y))
6521 // eq -> (icmp eq (or X, Y), 0)
6522 // ne -> (icmp ne (or X, Y), 0)
6523 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(1) &&
6524 Y->getType()->isIntOrIntVectorTy(1))
6525 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
6526 Constant::getNullValue(X->getType()));
6527
6528 // If we have mismatched casts and zext has the nneg flag, we can
6529 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6530
6531 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(0));
6532 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(1));
6533
6534 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6535 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6536
6537 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6538 IsSignedExt = true;
6539 else
6540 return nullptr;
6541 }
6542
6543 // Not an extension from the same type?
6544 Type *XTy = X->getType(), *YTy = Y->getType();
6545 if (XTy != YTy) {
6546 // One of the casts must have one use because we are creating a new cast.
6547 if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
6548 return nullptr;
6549 // Extend the narrower operand to the type of the wider operand.
6550 CastInst::CastOps CastOpcode =
6551 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6552 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6553 X = Builder.CreateCast(CastOpcode, X, YTy);
6554 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6555 Y = Builder.CreateCast(CastOpcode, Y, XTy);
6556 else
6557 return nullptr;
6558 }
6559
6560 // (zext X) == (zext Y) --> X == Y
6561 // (sext X) == (sext Y) --> X == Y
6562 if (ICmp.isEquality())
6563 return new ICmpInst(ICmp.getPredicate(), X, Y);
6564
6565 // A signed comparison of sign extended values simplifies into a
6566 // signed comparison.
6567 if (IsSignedCmp && IsSignedExt)
6568 return new ICmpInst(ICmp.getPredicate(), X, Y);
6569
6570 // The other three cases all fold into an unsigned comparison.
6571 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6572 }
6573
6574 // Below here, we are only folding a compare with constant.
6575 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
6576 if (!C)
6577 return nullptr;
6578
6579 // If a lossless truncate is possible...
6580 Type *SrcTy = CastOp0->getSrcTy();
6581 Constant *Res = getLosslessInvCast(C, SrcTy, CastOp0->getOpcode(), DL);
6582 if (Res) {
6583 if (ICmp.isEquality())
6584 return new ICmpInst(ICmp.getPredicate(), X, Res);
6585
6586 // A signed comparison of sign extended values simplifies into a
6587 // signed comparison.
6588 if (IsSignedExt && IsSignedCmp)
6589 return new ICmpInst(ICmp.getPredicate(), X, Res);
6590
6591 // The other three cases all fold into an unsigned comparison.
6592 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6593 }
6594
6595 // The re-extended constant changed, partly changed (in the case of a vector),
6596 // or could not be determined to be equal (in the case of a constant
6597 // expression), so the constant cannot be represented in the shorter type.
6598 // All the cases that fold to true or false will have already been handled
6599 // by simplifyICmpInst, so only deal with the tricky case.
6600 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
6601 return nullptr;
6602
6603 // Is source op positive?
6604 // icmp ult (sext X), C --> icmp sgt X, -1
6605 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6607
6608 // Is source op negative?
6609 // icmp ugt (sext X), C --> icmp slt X, 0
6610 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6612}
6613
6614/// Handle icmp (cast x), (cast or constant).
6616 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6617 // icmp compares only pointer's value.
6618 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6619 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
6620 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
6621 if (SimplifiedOp0 || SimplifiedOp1)
6622 return new ICmpInst(ICmp.getPredicate(),
6623 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
6624 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
6625
6626 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
6627 Value *Op1 = ICmp.getOperand(1);
6628 if (!CastOp0)
6629 return nullptr;
6630 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
6631 return nullptr;
6632
6633 Value *Op0Src = CastOp0->getOperand(0);
6634 Type *SrcTy = CastOp0->getSrcTy();
6635 Type *DestTy = CastOp0->getDestTy();
6636
6637 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6638 // integer type is the same size as the pointer type.
6639 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6640 unsigned IntWidth = IntTy->getScalarType()->getIntegerBitWidth();
6641 unsigned IndexWidth = DL.getAddressSizeInBits(PtrTy);
6642 unsigned PtrWidth = DL.getPointerTypeSizeInBits(PtrTy);
6643 // For ptrtoint/inttoptr, we must check that IntWidth == IndexWidth and also
6644 // IndexWidth == PtrWidth to (not) handle non-integral pointers.
6645 return IntWidth == IndexWidth && IndexWidth == PtrWidth;
6646 };
6647 if (isa<PtrToIntInst, PtrToAddrInst>(CastOp0)) {
6648 bool HasPtrToInt = isa<PtrToIntInst>(CastOp0);
6649 Value *NewOp1 = nullptr;
6650 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(Op1)) {
6651 NewOp1 = PtrToIntOp1->getOperand(0);
6652 HasPtrToInt = true;
6653 } else if (auto *PtrToAddrOp1 = dyn_cast<PtrToAddrOperator>(Op1)) {
6654 NewOp1 = PtrToAddrOp1->getOperand(0);
6655 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6656 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6657 }
6658
6659 // For ptrtoaddr, IntWidth == IndexWidth is implied and we don't need to
6660 // check PtrWidth.
6661 if ((!HasPtrToInt || CompatibleSizes(SrcTy, DestTy)) &&
6662 (NewOp1 && NewOp1->getType() == Op0Src->getType()))
6663 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6664 }
6665
6666 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6667 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6668 CompatibleSizes(DestTy, SrcTy)) {
6669 Value *NewOp1 = nullptr;
6670 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(Op1)) {
6671 Value *IntSrc = IntToPtrOp1->getOperand(0);
6672 if (IntSrc->getType() == Op0Src->getType())
6673 NewOp1 = IntToPtrOp1->getOperand(0);
6674 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6675 NewOp1 = ConstantFoldConstant(ConstantExpr::getPtrToInt(RHSC, SrcTy), DL);
6676 }
6677
6678 if (NewOp1)
6679 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6680 }
6681
6682 if (Instruction *R = foldICmpWithTrunc(ICmp))
6683 return R;
6684
6685 return foldICmpWithZextOrSext(ICmp);
6686}
6687
6689 bool IsSigned) {
6690 switch (BinaryOp) {
6691 default:
6692 llvm_unreachable("Unsupported binary op");
6693 case Instruction::Add:
6694 case Instruction::Sub:
6695 return match(RHS, m_Zero());
6696 case Instruction::Mul:
6697 return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
6698 match(RHS, m_One());
6699 }
6700}
6701
6704 bool IsSigned, Value *LHS, Value *RHS,
6705 Instruction *CxtI) const {
6706 switch (BinaryOp) {
6707 default:
6708 llvm_unreachable("Unsupported binary op");
6709 case Instruction::Add:
6710 if (IsSigned)
6711 return computeOverflowForSignedAdd(LHS, RHS, CxtI);
6712 else
6713 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
6714 case Instruction::Sub:
6715 if (IsSigned)
6716 return computeOverflowForSignedSub(LHS, RHS, CxtI);
6717 else
6718 return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
6719 case Instruction::Mul:
6720 if (IsSigned)
6721 return computeOverflowForSignedMul(LHS, RHS, CxtI);
6722 else
6723 return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
6724 }
6725}
6726
6727bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6728 bool IsSigned, Value *LHS,
6729 Value *RHS, Instruction &OrigI,
6730 Value *&Result,
6731 Constant *&Overflow) {
6732 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
6733 std::swap(LHS, RHS);
6734
6735 // If the overflow check was an add followed by a compare, the insertion point
6736 // may be pointing to the compare. We want to insert the new instructions
6737 // before the add in case there are uses of the add between the add and the
6738 // compare.
6739 Builder.SetInsertPoint(&OrigI);
6740
6741 Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
6742 if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
6743 OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
6744
6745 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6746 Result = LHS;
6747 Overflow = ConstantInt::getFalse(OverflowTy);
6748 return true;
6749 }
6750
6751 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
6753 return false;
6756 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6757 Result->takeName(&OrigI);
6758 Overflow = ConstantInt::getTrue(OverflowTy);
6759 return true;
6761 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6762 Result->takeName(&OrigI);
6763 Overflow = ConstantInt::getFalse(OverflowTy);
6764 if (auto *Inst = dyn_cast<Instruction>(Result)) {
6765 if (IsSigned)
6766 Inst->setHasNoSignedWrap();
6767 else
6768 Inst->setHasNoUnsignedWrap();
6769 }
6770 return true;
6771 }
6772
6773 llvm_unreachable("Unexpected overflow result");
6774}
6775
6776/// Recognize and process idiom involving test for multiplication
6777/// overflow.
6778///
6779/// The caller has matched a pattern of the form:
6780/// I = cmp u (mul(zext A, zext B), V
6781/// The function checks if this is a test for overflow and if so replaces
6782/// multiplication with call to 'mul.with.overflow' intrinsic.
6783///
6784/// \param I Compare instruction.
6785/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
6786/// the compare instruction. Must be of integer type.
6787/// \param OtherVal The other argument of compare instruction.
6788/// \returns Instruction which must replace the compare instruction, NULL if no
6789/// replacement required.
6791 const APInt *OtherVal,
6792 InstCombinerImpl &IC) {
6793 // Don't bother doing this transformation for pointers, don't do it for
6794 // vectors.
6795 if (!isa<IntegerType>(MulVal->getType()))
6796 return nullptr;
6797
6798 auto *MulInstr = dyn_cast<Instruction>(MulVal);
6799 if (!MulInstr)
6800 return nullptr;
6801 assert(MulInstr->getOpcode() == Instruction::Mul);
6802
6803 auto *LHS = cast<ZExtInst>(MulInstr->getOperand(0)),
6804 *RHS = cast<ZExtInst>(MulInstr->getOperand(1));
6805 assert(LHS->getOpcode() == Instruction::ZExt);
6806 assert(RHS->getOpcode() == Instruction::ZExt);
6807 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
6808
6809 // Calculate type and width of the result produced by mul.with.overflow.
6810 Type *TyA = A->getType(), *TyB = B->getType();
6811 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6812 WidthB = TyB->getPrimitiveSizeInBits();
6813 unsigned MulWidth;
6814 Type *MulType;
6815 if (WidthB > WidthA) {
6816 MulWidth = WidthB;
6817 MulType = TyB;
6818 } else {
6819 MulWidth = WidthA;
6820 MulType = TyA;
6821 }
6822
6823 // In order to replace the original mul with a narrower mul.with.overflow,
6824 // all uses must ignore upper bits of the product. The number of used low
6825 // bits must be not greater than the width of mul.with.overflow.
6826 if (MulVal->hasNUsesOrMore(2))
6827 for (User *U : MulVal->users()) {
6828 if (U == &I)
6829 continue;
6830 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6831 // Check if truncation ignores bits above MulWidth.
6832 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
6833 if (TruncWidth > MulWidth)
6834 return nullptr;
6835 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6836 // Check if AND ignores bits above MulWidth.
6837 if (BO->getOpcode() != Instruction::And)
6838 return nullptr;
6839 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6840 const APInt &CVal = CI->getValue();
6841 if (CVal.getBitWidth() - CVal.countl_zero() > MulWidth)
6842 return nullptr;
6843 } else {
6844 // In this case we could have the operand of the binary operation
6845 // being defined in another block, and performing the replacement
6846 // could break the dominance relation.
6847 return nullptr;
6848 }
6849 } else {
6850 // Other uses prohibit this transformation.
6851 return nullptr;
6852 }
6853 }
6854
6855 // Recognize patterns
6856 switch (I.getPredicate()) {
6857 case ICmpInst::ICMP_UGT: {
6858 // Recognize pattern:
6859 // mulval = mul(zext A, zext B)
6860 // cmp ugt mulval, max
6861 APInt MaxVal = APInt::getMaxValue(MulWidth);
6862 MaxVal = MaxVal.zext(OtherVal->getBitWidth());
6863 if (MaxVal.eq(*OtherVal))
6864 break; // Recognized
6865 return nullptr;
6866 }
6867
6868 case ICmpInst::ICMP_ULT: {
6869 // Recognize pattern:
6870 // mulval = mul(zext A, zext B)
6871 // cmp ule mulval, max + 1
6872 APInt MaxVal = APInt::getOneBitSet(OtherVal->getBitWidth(), MulWidth);
6873 if (MaxVal.eq(*OtherVal))
6874 break; // Recognized
6875 return nullptr;
6876 }
6877
6878 default:
6879 return nullptr;
6880 }
6881
6882 InstCombiner::BuilderTy &Builder = IC.Builder;
6883 Builder.SetInsertPoint(MulInstr);
6884
6885 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
6886 Value *MulA = A, *MulB = B;
6887 if (WidthA < MulWidth)
6888 MulA = Builder.CreateZExt(A, MulType);
6889 if (WidthB < MulWidth)
6890 MulB = Builder.CreateZExt(B, MulType);
6891 Value *Call =
6892 Builder.CreateIntrinsic(Intrinsic::umul_with_overflow, MulType,
6893 {MulA, MulB}, /*FMFSource=*/nullptr, "umul");
6894 IC.addToWorklist(MulInstr);
6895
6896 // If there are uses of mul result other than the comparison, we know that
6897 // they are truncation or binary AND. Change them to use result of
6898 // mul.with.overflow and adjust properly mask/size.
6899 if (MulVal->hasNUsesOrMore(2)) {
6900 Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value");
6901 for (User *U : make_early_inc_range(MulVal->users())) {
6902 if (U == &I)
6903 continue;
6904 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6905 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
6906 IC.replaceInstUsesWith(*TI, Mul);
6907 else
6908 TI->setOperand(0, Mul);
6909 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6910 assert(BO->getOpcode() == Instruction::And);
6911 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
6912 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
6913 APInt ShortMask = CI->getValue().trunc(MulWidth);
6914 Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask);
6915 Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
6916 IC.replaceInstUsesWith(*BO, Zext);
6917 } else {
6918 llvm_unreachable("Unexpected Binary operation");
6919 }
6921 }
6922 }
6923
6924 // The original icmp gets replaced with the overflow value, maybe inverted
6925 // depending on predicate.
6926 if (I.getPredicate() == ICmpInst::ICMP_ULT) {
6927 Value *Res = Builder.CreateExtractValue(Call, 1);
6928 return BinaryOperator::CreateNot(Res);
6929 }
6930
6931 return ExtractValueInst::Create(Call, 1);
6932}
6933
6934/// When performing a comparison against a constant, it is possible that not all
6935/// the bits in the LHS are demanded. This helper method computes the mask that
6936/// IS demanded.
6938 const APInt *RHS;
6939 if (!match(I.getOperand(1), m_APInt(RHS)))
6941
6942 // If this is a normal comparison, it demands all bits. If it is a sign bit
6943 // comparison, it only demands the sign bit.
6944 bool UnusedBit;
6945 if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
6947
6948 switch (I.getPredicate()) {
6949 // For a UGT comparison, we don't care about any bits that
6950 // correspond to the trailing ones of the comparand. The value of these
6951 // bits doesn't impact the outcome of the comparison, because any value
6952 // greater than the RHS must differ in a bit higher than these due to carry.
6953 case ICmpInst::ICMP_UGT:
6954 return APInt::getBitsSetFrom(BitWidth, RHS->countr_one());
6955
6956 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
6957 // Any value less than the RHS must differ in a higher bit because of carries.
6958 case ICmpInst::ICMP_ULT:
6959 return APInt::getBitsSetFrom(BitWidth, RHS->countr_zero());
6960
6961 default:
6963 }
6964}
6965
6966/// Check that one use is in the same block as the definition and all
6967/// other uses are in blocks dominated by a given block.
6968///
6969/// \param DI Definition
6970/// \param UI Use
6971/// \param DB Block that must dominate all uses of \p DI outside
6972/// the parent block
6973/// \return true when \p UI is the only use of \p DI in the parent block
6974/// and all other uses of \p DI are in blocks dominated by \p DB.
6975///
6977 const Instruction *UI,
6978 const BasicBlock *DB) const {
6979 assert(DI && UI && "Instruction not defined\n");
6980 // Ignore incomplete definitions.
6981 if (!DI->getParent())
6982 return false;
6983 // DI and UI must be in the same block.
6984 if (DI->getParent() != UI->getParent())
6985 return false;
6986 // Protect from self-referencing blocks.
6987 if (DI->getParent() == DB)
6988 return false;
6989 for (const User *U : DI->users()) {
6990 auto *Usr = cast<Instruction>(U);
6991 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
6992 return false;
6993 }
6994 return true;
6995}
6996
6997/// Return true when the instruction sequence within a block is select-cmp-br.
6999 const BasicBlock *BB = SI->getParent();
7000 if (!BB)
7001 return false;
7003 if (!BI)
7004 return false;
7005 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
7006 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
7007 return false;
7008 return true;
7009}
7010
7011/// True when a select result is replaced by one of its operands
7012/// in select-icmp sequence. This will eventually result in the elimination
7013/// of the select.
7014///
7015/// \param SI Select instruction
7016/// \param Icmp Compare instruction
7017/// \param SIOpd Operand that replaces the select
7018///
7019/// Notes:
7020/// - The replacement is global and requires dominator information
7021/// - The caller is responsible for the actual replacement
7022///
7023/// Example:
7024///
7025/// entry:
7026/// %4 = select i1 %3, %C* %0, %C* null
7027/// %5 = icmp eq %C* %4, null
7028/// br i1 %5, label %9, label %7
7029/// ...
7030/// ; <label>:7 ; preds = %entry
7031/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
7032/// ...
7033///
7034/// can be transformed to
7035///
7036/// %5 = icmp eq %C* %0, null
7037/// %6 = select i1 %3, i1 %5, i1 true
7038/// br i1 %6, label %9, label %7
7039/// ...
7040/// ; <label>:7 ; preds = %entry
7041/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
7042///
7043/// Similar when the first operand of the select is a constant or/and
7044/// the compare is for not equal rather than equal.
7045///
7046/// NOTE: The function is only called when the select and compare constants
7047/// are equal, the optimization can work only for EQ predicates. This is not a
7048/// major restriction since a NE compare should be 'normalized' to an equal
7049/// compare, which usually happens in the combiner and test case
7050/// select-cmp-br.ll checks for it.
7052 const ICmpInst *Icmp,
7053 const unsigned SIOpd) {
7054 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
7056 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
7057 // The check for the single predecessor is not the best that can be
7058 // done. But it protects efficiently against cases like when SI's
7059 // home block has two successors, Succ and Succ1, and Succ1 predecessor
7060 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
7061 // replaced can be reached on either path. So the uniqueness check
7062 // guarantees that the path all uses of SI (outside SI's parent) are on
7063 // is disjoint from all other paths out of SI. But that information
7064 // is more expensive to compute, and the trade-off here is in favor
7065 // of compile-time. It should also be noticed that we check for a single
7066 // predecessor and not only uniqueness. This to handle the situation when
7067 // Succ and Succ1 points to the same basic block.
7068 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
7069 NumSel++;
7070 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
7071 return true;
7072 }
7073 }
7074 return false;
7075}
7076
7077/// Try to fold the comparison based on range information we can get by checking
7078/// whether bits are known to be zero or one in the inputs.
7080 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7081 Type *Ty = Op0->getType();
7082 ICmpInst::Predicate Pred = I.getPredicate();
7083
7084 // Get scalar or pointer size.
7085 unsigned BitWidth = Ty->isIntOrIntVectorTy()
7086 ? Ty->getScalarSizeInBits()
7087 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
7088
7089 if (!BitWidth)
7090 return nullptr;
7091
7092 KnownBits Op0Known(BitWidth);
7093 KnownBits Op1Known(BitWidth);
7094
7095 {
7096 // Don't use dominating conditions when folding icmp using known bits. This
7097 // may convert signed into unsigned predicates in ways that other passes
7098 // (especially IndVarSimplify) may not be able to reliably undo.
7099 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(&I);
7101 Op0Known, Q))
7102 return &I;
7103
7104 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, Q))
7105 return &I;
7106 }
7107
7108 // If an unsigned samesign comparison is not poison, both operands have the
7109 // same sign bit. Propagate a known sign bit between the temporary KnownBits
7110 // values so the existing range folds can use that constraint.
7111 if (I.hasSameSign() && I.isUnsigned()) {
7112 auto PropagateSignBit = [](const KnownBits &From, KnownBits &To) {
7113 if (To.isNegative() || To.isNonNegative())
7114 return;
7115 if (From.isNegative())
7116 To.makeNegative();
7117 else if (From.isNonNegative())
7118 To.makeNonNegative();
7119 };
7120 PropagateSignBit(Op0Known, Op1Known);
7121 PropagateSignBit(Op1Known, Op0Known);
7122 }
7123
7124 if (!isa<Constant>(Op0) && Op0Known.isConstant())
7125 return new ICmpInst(
7126 Pred, ConstantExpr::getIntegerValue(Ty, Op0Known.getConstant()), Op1);
7127 if (!isa<Constant>(Op1) && Op1Known.isConstant())
7128 return new ICmpInst(
7129 Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Known.getConstant()));
7130
7131 if (std::optional<bool> Res = ICmpInst::compare(Op0Known, Op1Known, Pred))
7132 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *Res));
7133
7134 // Given the known and unknown bits, compute a range that the LHS could be
7135 // in. Compute the Min, Max and RHS values based on the known bits. For the
7136 // EQ and NE we use unsigned values.
7137 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
7138 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
7139 if (I.isSigned()) {
7140 Op0Min = Op0Known.getSignedMinValue();
7141 Op0Max = Op0Known.getSignedMaxValue();
7142 Op1Min = Op1Known.getSignedMinValue();
7143 Op1Max = Op1Known.getSignedMaxValue();
7144 } else {
7145 Op0Min = Op0Known.getMinValue();
7146 Op0Max = Op0Known.getMaxValue();
7147 Op1Min = Op1Known.getMinValue();
7148 Op1Max = Op1Known.getMaxValue();
7149 }
7150
7151 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
7152 // min/max canonical compare with some other compare. That could lead to
7153 // conflict with select canonicalization and infinite looping.
7154 // FIXME: This constraint may go away if min/max intrinsics are canonical.
7155 auto isMinMaxCmp = [&](Instruction &Cmp) {
7156 if (!Cmp.hasOneUse())
7157 return false;
7158 Value *A, *B;
7159 SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
7161 return false;
7162 return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
7163 match(Op1, m_MaxOrMin(m_Value(), m_Value()));
7164 };
7165 if (!isMinMaxCmp(I)) {
7166 switch (Pred) {
7167 default:
7168 break;
7169 case ICmpInst::ICMP_ULT: {
7170 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
7171 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7172 const APInt *CmpC;
7173 if (match(Op1, m_APInt(CmpC))) {
7174 // A <u C -> A == C-1 if min(A)+1 == C
7175 if (*CmpC == Op0Min + 1)
7176 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7177 ConstantInt::get(Op1->getType(), *CmpC - 1));
7178 // X <u C --> X == 0, if the number of zero bits in the bottom of X
7179 // exceeds the log2 of C.
7180 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
7181 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7182 Constant::getNullValue(Op1->getType()));
7183 }
7184 break;
7185 }
7186 case ICmpInst::ICMP_UGT: {
7187 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
7188 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7189 const APInt *CmpC;
7190 if (match(Op1, m_APInt(CmpC))) {
7191 // A >u C -> A == C+1 if max(a)-1 == C
7192 if (*CmpC == Op0Max - 1)
7193 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7194 ConstantInt::get(Op1->getType(), *CmpC + 1));
7195 // X >u C --> X != 0, if the number of zero bits in the bottom of X
7196 // exceeds the log2 of C.
7197 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
7198 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
7199 Constant::getNullValue(Op1->getType()));
7200 }
7201 break;
7202 }
7203 case ICmpInst::ICMP_SLT: {
7204 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
7205 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7206 const APInt *CmpC;
7207 if (match(Op1, m_APInt(CmpC))) {
7208 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
7209 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7210 ConstantInt::get(Op1->getType(), *CmpC - 1));
7211 }
7212 break;
7213 }
7214 case ICmpInst::ICMP_SGT: {
7215 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
7216 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7217 const APInt *CmpC;
7218 if (match(Op1, m_APInt(CmpC))) {
7219 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
7220 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7221 ConstantInt::get(Op1->getType(), *CmpC + 1));
7222 }
7223 break;
7224 }
7225 }
7226 }
7227
7228 // Based on the range information we know about the LHS, see if we can
7229 // simplify this comparison. For example, (x&4) < 8 is always true.
7230 switch (Pred) {
7231 default:
7232 break;
7233 case ICmpInst::ICMP_EQ:
7234 case ICmpInst::ICMP_NE: {
7235 // If all bits are known zero except for one, then we know at most one bit
7236 // is set. If the comparison is against zero, then this is a check to see if
7237 // *that* bit is set.
7238 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
7239 if (Op1Known.isZero()) {
7240 // If the LHS is an AND with the same constant, look through it.
7241 Value *LHS = nullptr;
7242 const APInt *LHSC;
7243 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
7244 *LHSC != Op0KnownZeroInverted)
7245 LHS = Op0;
7246
7247 Value *X;
7248 const APInt *C1;
7249 if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
7250 Type *XTy = X->getType();
7251 unsigned Log2C1 = C1->countr_zero();
7252 APInt C2 = Op0KnownZeroInverted;
7253 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
7254 if (C2Pow2.isPowerOf2()) {
7255 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
7256 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
7257 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
7258 unsigned Log2C2 = C2Pow2.countr_zero();
7259 auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
7260 auto NewPred =
7262 return new ICmpInst(NewPred, X, CmpC);
7263 }
7264 }
7265 }
7266
7267 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
7268 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
7269 (Op0Known & Op1Known) == Op0Known)
7270 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
7271 ConstantInt::getNullValue(Op1->getType()));
7272 break;
7273 }
7274 case ICmpInst::ICMP_SGE:
7275 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
7276 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7277 break;
7278 case ICmpInst::ICMP_SLE:
7279 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
7280 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7281 break;
7282 case ICmpInst::ICMP_UGE:
7283 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
7284 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7285 break;
7286 case ICmpInst::ICMP_ULE:
7287 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
7288 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7289 break;
7290 }
7291
7292 // Turn a signed comparison into an unsigned one if both operands are known to
7293 // have the same sign. Set samesign if possible (except for equality
7294 // predicates).
7295 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
7296 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
7297 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
7298 I.setPredicate(I.getUnsignedPredicate());
7299 I.setSameSign();
7300 return &I;
7301 }
7302
7303 return nullptr;
7304}
7305
7306/// If one operand of an icmp is effectively a bool (value range of {0,1}),
7307/// then try to reduce patterns based on that limit.
7309 Value *X, *Y;
7310 CmpPredicate Pred;
7311
7312 // X must be 0 and bool must be true for "ULT":
7313 // X <u (zext i1 Y) --> (X == 0) & Y
7314 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
7315 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
7316 return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
7317
7318 // X must be 0 or bool must be true for "ULE":
7319 // X <=u (sext i1 Y) --> (X == 0) | Y
7320 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
7321 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
7322 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
7323
7324 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
7325 CmpPredicate Pred1, Pred2;
7326 const APInt *C;
7327 Instruction *ExtI;
7328 if (match(&I, m_c_ICmp(Pred1, m_Value(X),
7331 m_APInt(C)))))) &&
7332 ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
7333 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
7334 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(0)->hasOneUse();
7335 auto CreateRangeCheck = [&] {
7336 Value *CmpV1 =
7337 Builder.CreateICmp(Pred1, X, Constant::getNullValue(X->getType()));
7338 Value *CmpV2 = Builder.CreateICmp(
7339 Pred1, X, ConstantInt::getSigned(X->getType(), IsSExt ? -1 : 1));
7341 Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
7342 CmpV1, CmpV2);
7343 };
7344 if (C->isZero()) {
7345 if (Pred2 == ICmpInst::ICMP_EQ) {
7346 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
7347 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
7348 return replaceInstUsesWith(
7349 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7350 } else if (!IsSExt || HasOneUse) {
7351 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
7352 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
7353 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
7354 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X != -1
7355 return CreateRangeCheck();
7356 }
7357 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
7358 if (Pred2 == ICmpInst::ICMP_NE) {
7359 // icmp eq X, (zext (icmp ne X, 1)) --> false
7360 // icmp ne X, (zext (icmp ne X, 1)) --> true
7361 // icmp eq X, (sext (icmp ne X, -1)) --> false
7362 // icmp ne X, (sext (icmp ne X, -1)) --> true
7363 return replaceInstUsesWith(
7364 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7365 } else if (!IsSExt || HasOneUse) {
7366 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
7367 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
7368 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
7369 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
7370 return CreateRangeCheck();
7371 }
7372 } else {
7373 // when C != 0 && C != 1:
7374 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
7375 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
7376 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
7377 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
7378 // when C != 0 && C != -1:
7379 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
7380 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
7381 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
7382 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
7383 return ICmpInst::Create(
7384 Instruction::ICmp, Pred1, X,
7385 ConstantInt::getSigned(X->getType(), Pred2 == ICmpInst::ICMP_NE
7386 ? (IsSExt ? -1 : 1)
7387 : 0));
7388 }
7389 }
7390
7391 return nullptr;
7392}
7393
7394/// If we have an icmp le or icmp ge instruction with a constant operand, turn
7395/// it into the appropriate icmp lt or icmp gt instruction. This transform
7396/// allows them to be folded in visitICmpInst.
7398 CmpPredicate Pred = I.getCmpPredicate();
7399 if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
7401 return nullptr;
7402
7403 Value *Op0 = I.getOperand(0);
7404 Value *Op1 = I.getOperand(1);
7405 auto *Op1C = dyn_cast<Constant>(Op1);
7406 if (!Op1C)
7407 return nullptr;
7408
7409 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
7410 if (!FlippedStrictness)
7411 return nullptr;
7412
7413 auto *NewCmp =
7414 new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7415 NewCmp->setSameSign(FlippedStrictness->first.hasSameSign());
7416 return NewCmp;
7417}
7418
7419/// If we have a comparison with a non-canonical predicate, if we can update
7420/// all the users, invert the predicate and adjust all the users.
7422 // Is the predicate already canonical?
7423 CmpInst::Predicate Pred = I.getPredicate();
7425 return nullptr;
7426
7427 // Can all users be adjusted to predicate inversion?
7428 if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
7429 return nullptr;
7430
7431 // Ok, we can canonicalize comparison!
7432 // Let's first invert the comparison's predicate.
7433 I.setPredicate(CmpInst::getInversePredicate(Pred));
7434 I.setName(I.getName() + ".not");
7435
7436 // And, adapt users.
7438
7439 return &I;
7440}
7441
7442/// Integer compare with boolean values can always be turned into bitwise ops.
7444 InstCombiner::BuilderTy &Builder) {
7445 Value *A = I.getOperand(0), *B = I.getOperand(1);
7446 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
7447
7448 // A boolean compared to true/false can be simplified to Op0/true/false in
7449 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
7450 // Cases not handled by InstSimplify are always 'not' of Op0.
7451 if (match(B, m_Zero())) {
7452 switch (I.getPredicate()) {
7453 case CmpInst::ICMP_EQ: // A == 0 -> !A
7454 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
7455 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7457 default:
7458 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7459 }
7460 } else if (match(B, m_One())) {
7461 switch (I.getPredicate()) {
7462 case CmpInst::ICMP_NE: // A != 1 -> !A
7463 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7464 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7466 default:
7467 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7468 }
7469 }
7470
7471 switch (I.getPredicate()) {
7472 default:
7473 llvm_unreachable("Invalid icmp instruction!");
7474 case ICmpInst::ICMP_EQ:
7475 // icmp eq i1 A, B -> ~(A ^ B)
7476 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
7477
7478 case ICmpInst::ICMP_NE:
7479 // icmp ne i1 A, B -> A ^ B
7480 return BinaryOperator::CreateXor(A, B);
7481
7482 case ICmpInst::ICMP_UGT:
7483 // icmp ugt -> icmp ult
7484 std::swap(A, B);
7485 [[fallthrough]];
7486 case ICmpInst::ICMP_ULT:
7487 // icmp ult i1 A, B -> ~A & B
7488 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
7489
7490 case ICmpInst::ICMP_SGT:
7491 // icmp sgt -> icmp slt
7492 std::swap(A, B);
7493 [[fallthrough]];
7494 case ICmpInst::ICMP_SLT:
7495 // icmp slt i1 A, B -> A & ~B
7496 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
7497
7498 case ICmpInst::ICMP_UGE:
7499 // icmp uge -> icmp ule
7500 std::swap(A, B);
7501 [[fallthrough]];
7502 case ICmpInst::ICMP_ULE:
7503 // icmp ule i1 A, B -> ~A | B
7504 return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
7505
7506 case ICmpInst::ICMP_SGE:
7507 // icmp sge -> icmp sle
7508 std::swap(A, B);
7509 [[fallthrough]];
7510 case ICmpInst::ICMP_SLE:
7511 // icmp sle i1 A, B -> A | ~B
7512 return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
7513 }
7514}
7515
7516// Transform pattern like:
7517// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7518// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7519// Into:
7520// (X l>> Y) != 0
7521// (X l>> Y) == 0
7523 InstCombiner::BuilderTy &Builder) {
7524 CmpPredicate Pred, NewPred;
7525 Value *X, *Y;
7526 if (match(&Cmp,
7527 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
7528 switch (Pred) {
7529 case ICmpInst::ICMP_ULE:
7530 NewPred = ICmpInst::ICMP_NE;
7531 break;
7532 case ICmpInst::ICMP_UGT:
7533 NewPred = ICmpInst::ICMP_EQ;
7534 break;
7535 default:
7536 return nullptr;
7537 }
7538 } else if (match(&Cmp, m_c_ICmp(Pred,
7541 m_Add(m_Shl(m_One(), m_Value(Y)),
7542 m_AllOnes()))),
7543 m_Value(X)))) {
7544 // The variant with 'add' is not canonical, (the variant with 'not' is)
7545 // we only get it because it has extra uses, and can't be canonicalized,
7546
7547 switch (Pred) {
7548 case ICmpInst::ICMP_ULT:
7549 NewPred = ICmpInst::ICMP_NE;
7550 break;
7551 case ICmpInst::ICMP_UGE:
7552 NewPred = ICmpInst::ICMP_EQ;
7553 break;
7554 default:
7555 return nullptr;
7556 }
7557 } else
7558 return nullptr;
7559
7560 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
7561 Constant *Zero = Constant::getNullValue(NewX->getType());
7562 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
7563}
7564
7566 InstCombiner::BuilderTy &Builder) {
7567 const CmpInst::Predicate Pred = Cmp.getPredicate();
7568 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
7569 Value *V1, *V2;
7570
7571 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7572 Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
7573 if (auto *I = dyn_cast<Instruction>(V))
7574 I->copyIRFlags(&Cmp);
7575 Module *M = Cmp.getModule();
7577 M, Intrinsic::vector_reverse, V->getType());
7578 return CallInst::Create(F, V);
7579 };
7580
7581 if (match(LHS, m_VecReverse(m_Value(V1)))) {
7582 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7583 if (match(RHS, m_VecReverse(m_Value(V2))) &&
7584 (LHS->hasOneUse() || RHS->hasOneUse()))
7585 return createCmpReverse(Pred, V1, V2);
7586
7587 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7588 if (LHS->hasOneUse() && isSplatValue(RHS))
7589 return createCmpReverse(Pred, V1, RHS);
7590 }
7591 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7592 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
7593 return createCmpReverse(Pred, LHS, V2);
7594
7595 ArrayRef<int> M;
7596 if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
7597 return nullptr;
7598
7599 // If both arguments of the cmp are shuffles that use the same mask and
7600 // shuffle within a single vector, move the shuffle after the cmp:
7601 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7602 Type *V1Ty = V1->getType();
7603 if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
7604 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7605 Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
7606 return new ShuffleVectorInst(NewCmp, M);
7607 }
7608
7609 // Try to canonicalize compare with splatted operand and splat constant.
7610 // TODO: We could generalize this for more than splats. See/use the code in
7611 // InstCombiner::foldVectorBinop().
7612 Constant *C;
7613 if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
7614 return nullptr;
7615
7616 // Length-changing splats are ok, so adjust the constants as needed:
7617 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7618 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7619 int MaskSplatIndex;
7620 if (ScalarC && match(M, m_SplatOrPoisonMask(MaskSplatIndex))) {
7621 // We allow poison in matching, but this transform removes it for safety.
7622 // Demanded elements analysis should be able to recover some/all of that.
7623 C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
7624 ScalarC);
7625 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7626 Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
7627 return new ShuffleVectorInst(NewCmp, NewM);
7628 }
7629
7630 return nullptr;
7631}
7632
7633// extract(uadd.with.overflow(A, B), 0) ult A
7634// -> extract(uadd.with.overflow(A, B), 1)
7636 CmpInst::Predicate Pred = I.getPredicate();
7637 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7638
7639 Value *UAddOv;
7640 Value *A, *B;
7641 auto UAddOvResultPat = m_ExtractValue<0>(
7643 if (match(Op0, UAddOvResultPat) &&
7644 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7645 (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
7646 (match(A, m_One()) || match(B, m_One()))) ||
7647 (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
7648 (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
7649 // extract(uadd.with.overflow(A, B), 0) < A
7650 // extract(uadd.with.overflow(A, 1), 0) == 0
7651 // extract(uadd.with.overflow(A, -1), 0) != -1
7652 UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
7653 else if (match(Op1, UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7654 (Op0 == A || Op0 == B))
7655 // A > extract(uadd.with.overflow(A, B), 0)
7656 UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
7657 else
7658 return nullptr;
7659
7660 return ExtractValueInst::Create(UAddOv, 1);
7661}
7662
7664 if (!I.getOperand(0)->getType()->isPointerTy() ||
7666 I.getParent()->getParent(),
7667 I.getOperand(0)->getType()->getPointerAddressSpace())) {
7668 return nullptr;
7669 }
7670 Instruction *Op;
7671 if (match(I.getOperand(0), m_Instruction(Op)) &&
7672 match(I.getOperand(1), m_Zero()) &&
7673 Op->isLaunderOrStripInvariantGroup()) {
7674 return ICmpInst::Create(Instruction::ICmp, I.getPredicate(),
7675 Op->getOperand(0), I.getOperand(1));
7676 }
7677 return nullptr;
7678}
7679
7681 IRBuilderBase &Builder) {
7682 if (!ICmpInst::isEquality(I.getPredicate()))
7683 return nullptr;
7684
7685 // The caller puts constants after non-constants.
7686 Value *Op = I.getOperand(0);
7687 Value *Const = I.getOperand(1);
7688
7689 // For Cond an equality condition, fold
7690 //
7691 // icmp (eq|ne) (vreduce_(or|and) Op), (Zero|AllOnes) ->
7692 // icmp (eq|ne) Op, (Zero|AllOnes)
7693 //
7694 // with a bitcast.
7695 Value *Vec;
7696 if ((match(Const, m_ZeroInt()) &&
7698 m_Value(Vec))))) ||
7699 (match(Const, m_AllOnes()) &&
7701 m_Value(Vec)))))) {
7702 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
7703 if (!VecTy)
7704 return nullptr;
7705 Type *VecEltTy = VecTy->getElementType();
7706 unsigned ScalarBW =
7707 DL.getTypeSizeInBits(VecEltTy) * VecTy->getNumElements();
7708 if (!DL.fitsInLegalInteger(ScalarBW))
7709 return nullptr;
7710 Type *ScalarTy = IntegerType::get(I.getContext(), ScalarBW);
7711 Value *NewConst = match(Const, m_ZeroInt())
7712 ? ConstantInt::get(ScalarTy, 0)
7713 : ConstantInt::getAllOnesValue(ScalarTy);
7714 return CmpInst::Create(Instruction::ICmp, I.getPredicate(),
7715 Builder.CreateBitCast(Vec, ScalarTy), NewConst);
7716 }
7717 return nullptr;
7718}
7719
7720/// This function folds patterns produced by lowering of reduce idioms, such as
7721/// llvm.vector.reduce.and which are lowered into instruction chains. This code
7722/// attempts to generate fewer number of scalar comparisons instead of vector
7723/// comparisons when possible.
7725 InstCombiner::BuilderTy &Builder,
7726 const DataLayout &DL) {
7727 if (I.getType()->isVectorTy())
7728 return nullptr;
7729 CmpPredicate OuterPred, InnerPred;
7730 Value *LHS, *RHS;
7731
7732 // Match lowering of @llvm.vector.reduce.and. Turn
7733 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7734 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7735 /// %res = icmp <pred> i8 %scalar_ne, 0
7736 ///
7737 /// into
7738 ///
7739 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7740 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7741 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7742 ///
7743 /// for <pred> in {ne, eq}.
7744 if (!match(&I, m_ICmp(OuterPred,
7746 m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
7747 m_Zero())))
7748 return nullptr;
7749 auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
7750 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7751 return nullptr;
7752 unsigned NumBits =
7753 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7754 // TODO: Relax this to "not wider than max legal integer type"?
7755 if (!DL.isLegalInteger(NumBits))
7756 return nullptr;
7757
7758 if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7759 auto *ScalarTy = Builder.getIntNTy(NumBits);
7760 LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
7761 RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
7762 return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
7763 I.getName());
7764 }
7765
7766 return nullptr;
7767}
7768
7769// This helper will be called with icmp operands in both orders.
7771 Value *Op0, Value *Op1,
7772 ICmpInst &CxtI) {
7773 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7774 if (auto *GEP = dyn_cast<GEPOperator>(Op0))
7775 if (Instruction *NI = foldGEPICmp(GEP, Op1, Pred, CxtI))
7776 return NI;
7777
7778 if (auto *SI = dyn_cast<SelectInst>(Op0))
7779 if (Instruction *NI = foldSelectICmp(Pred, SI, Op1, CxtI))
7780 return NI;
7781
7782 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op0)) {
7783 if (Instruction *Res = foldICmpWithMinMax(CxtI, MinMax, Op1, Pred))
7784 return Res;
7785
7786 if (Instruction *Res = foldICmpWithClamp(CxtI, Op1, MinMax))
7787 return Res;
7788 }
7789
7790 {
7791 Value *X;
7792 const APInt *C;
7793 // icmp X+Cst, X
7794 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
7795 return foldICmpAddOpConst(X, *C, Pred);
7796 }
7797
7798 // abs(X) >= X --> true
7799 // abs(X) u<= X --> true
7800 // abs(X) < X --> false
7801 // abs(X) u> X --> false
7802 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7803 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7804 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7805 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7806 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7807 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7808 {
7809 Value *X;
7810 Constant *C;
7812 match(Op1, m_Specific(X))) {
7813 Value *NullValue = Constant::getNullValue(X->getType());
7814 Value *AllOnesValue = Constant::getAllOnesValue(X->getType());
7815 const APInt SMin =
7816 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits());
7817 bool IsIntMinPosion = C->isAllOnesValue();
7818 switch (Pred) {
7819 case CmpInst::ICMP_ULE:
7820 case CmpInst::ICMP_SGE:
7821 return replaceInstUsesWith(CxtI, ConstantInt::getTrue(CxtI.getType()));
7822 case CmpInst::ICMP_UGT:
7823 case CmpInst::ICMP_SLT:
7825 case CmpInst::ICMP_UGE:
7826 case CmpInst::ICMP_SLE:
7827 case CmpInst::ICMP_EQ: {
7828 return replaceInstUsesWith(
7829 CxtI, IsIntMinPosion
7830 ? Builder.CreateICmpSGT(X, AllOnesValue)
7831 : Builder.CreateICmpULT(
7832 X, ConstantInt::get(X->getType(), SMin + 1)));
7833 }
7834 case CmpInst::ICMP_ULT:
7835 case CmpInst::ICMP_SGT:
7836 case CmpInst::ICMP_NE: {
7837 return replaceInstUsesWith(
7838 CxtI, IsIntMinPosion
7839 ? Builder.CreateICmpSLT(X, NullValue)
7840 : Builder.CreateICmpUGT(
7841 X, ConstantInt::get(X->getType(), SMin)));
7842 }
7843 default:
7844 llvm_unreachable("Invalid predicate!");
7845 }
7846 }
7847 }
7848
7849 const SimplifyQuery Q = SQ.getWithInstruction(&CxtI);
7850 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, *this))
7851 return replaceInstUsesWith(CxtI, V);
7852
7853 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
7854 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(1); };
7855 {
7856 if (match(Op0, m_UDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7857 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7859 }
7860
7861 if (!ICmpInst::isUnsigned(Pred) &&
7862 match(Op0, m_SDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7863 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7865 }
7866 }
7867
7868 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
7869 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
7870 {
7871 if (match(Op0, m_LShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7872 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7874 }
7875
7876 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
7877 match(Op0, m_AShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7878 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7880 }
7881 }
7882
7883 // icmp (shl nsw/nuw X, L), (add nsw/nuw (shl nsw/nuw Y, L), K)
7884 // -> icmp X, (add nsw/nuw Y, K >> L)
7885 // We use AShr for nsw and LShr for nuw to safely peel off the shift.
7886 Value *X;
7887 uint64_t ShAmt;
7888 if (match(Op0, m_NUWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
7889 !CxtI.isSigned()) {
7890 if (ShAmt >= X->getType()->getScalarSizeInBits())
7891 return nullptr;
7892 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
7893 ShiftSemantics::Unsigned, &CxtI)) {
7894 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
7896 return new ICmpInst(Pred, X, NewOp1);
7897 }
7898 }
7899
7900 if (match(Op0, m_NSWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
7901 !CxtI.isUnsigned()) {
7902 if (ShAmt >= X->getType()->getScalarSizeInBits())
7903 return nullptr;
7904 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
7905 ShiftSemantics::Signed, &CxtI)) {
7906 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
7908 return new ICmpInst(Pred, X, NewOp1);
7909 }
7910 }
7911 return nullptr;
7912}
7913
7915 bool Changed = false;
7916 const SimplifyQuery Q = SQ.getWithInstruction(&I);
7917 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7918 unsigned Op0Cplxity = getComplexity(Op0);
7919 unsigned Op1Cplxity = getComplexity(Op1);
7920
7921 /// Orders the operands of the compare so that they are listed from most
7922 /// complex to least complex. This puts constants before unary operators,
7923 /// before binary operators.
7924 if (Op0Cplxity < Op1Cplxity) {
7925 I.swapOperands();
7926 std::swap(Op0, Op1);
7927 Changed = true;
7928 }
7929
7930 if (Value *V = simplifyICmpInst(I.getCmpPredicate(), Op0, Op1, Q))
7931 return replaceInstUsesWith(I, V);
7932
7933 // Comparing -val or val with non-zero is the same as just comparing val
7934 // ie, abs(val) != 0 -> val != 0
7935 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
7936 Value *Cond, *SelectTrue, *SelectFalse;
7937 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
7938 m_Value(SelectFalse)))) {
7939 if (Value *V = dyn_castNegVal(SelectTrue)) {
7940 if (V == SelectFalse)
7941 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
7942 } else if (Value *V = dyn_castNegVal(SelectFalse)) {
7943 if (V == SelectTrue)
7944 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
7945 }
7946 }
7947 }
7948
7950 return Res;
7951
7952 if (Op0->getType()->isIntOrIntVectorTy(1))
7954 return Res;
7955
7957 return Res;
7958
7960 return Res;
7961
7963 return Res;
7964
7966 return Res;
7967
7969 return Res;
7970
7972 return Res;
7973
7975 return Res;
7976
7977 // Test if the ICmpInst instruction is used exclusively by a select as
7978 // part of a minimum or maximum operation. If so, refrain from doing
7979 // any other folding. This helps out other analyses which understand
7980 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
7981 // and CodeGen. And in this case, at least one of the comparison
7982 // operands has at least one user besides the compare (the select),
7983 // which would often largely negate the benefit of folding anyway.
7984 //
7985 // Do the same for the other patterns recognized by matchSelectPattern.
7986 if (I.hasOneUse())
7987 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
7988 Value *A, *B;
7990 if (SPR.Flavor != SPF_UNKNOWN)
7991 return nullptr;
7992 }
7993
7994 // Do this after checking for min/max to prevent infinite looping.
7995 if (Instruction *Res = foldICmpWithZero(I))
7996 return Res;
7997
7998 Value *X;
7999 const APInt *C;
8000 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
8001 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
8002 match(Op1, m_Not(m_Specific(X)))) {
8003 if (C->isNonNegative())
8004 return new ICmpInst(ICmpInst::ICMP_SLT, X,
8005 Constant::getNullValue(X->getType()));
8006 return new ICmpInst(ICmpInst::ICMP_UGT, X,
8007 ConstantInt::get(X->getType(), ~*C));
8008 }
8009
8010 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
8011 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
8012 match(Op1, m_Not(m_Specific(X)))) {
8013 if (C->isNonNegative())
8014 return new ICmpInst(ICmpInst::ICMP_SGT, X,
8015 Constant::getAllOnesValue(X->getType()));
8016 return new ICmpInst(ICmpInst::ICMP_ULT, X,
8017 ConstantInt::get(X->getType(), ~*C));
8018 }
8019
8020 // FIXME: We only do this after checking for min/max to prevent infinite
8021 // looping caused by a reverse canonicalization of these patterns for min/max.
8022 // FIXME: The organization of folds is a mess. These would naturally go into
8023 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
8024 // down here after the min/max restriction.
8025 ICmpInst::Predicate Pred = I.getPredicate();
8026 if (match(Op1, m_APInt(C))) {
8027 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
8028 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
8029 Constant *Zero = Constant::getNullValue(Op0->getType());
8030 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
8031 }
8032
8033 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
8034 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
8036 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
8037 }
8038 }
8039
8040 // The folds in here may rely on wrapping flags and special constants, so
8041 // they can break up min/max idioms in some cases but not seemingly similar
8042 // patterns.
8043 // FIXME: It may be possible to enhance select folding to make this
8044 // unnecessary. It may also be moot if we canonicalize to min/max
8045 // intrinsics.
8046 if (Instruction *Res = foldICmpBinOp(I, Q))
8047 return Res;
8048
8050 return Res;
8051
8052 // Try to match comparison as a sign bit test. Intentionally do this after
8053 // foldICmpInstWithConstant() to potentially let other folds to happen first.
8054 if (Instruction *New = foldSignBitTest(I))
8055 return New;
8056
8057 if (auto *PN = dyn_cast<PHINode>(Op0))
8058 if (Instruction *NV = foldOpIntoPhi(I, PN))
8059 return NV;
8060 if (auto *PN = dyn_cast<PHINode>(Op1))
8061 if (Instruction *NV = foldOpIntoPhi(I, PN))
8062 return NV;
8063
8065 return Res;
8066
8067 if (Instruction *Res = foldICmpCommutative(I.getCmpPredicate(), Op0, Op1, I))
8068 return Res;
8069 if (Instruction *Res =
8070 foldICmpCommutative(I.getSwappedCmpPredicate(), Op1, Op0, I))
8071 return Res;
8072
8073 if (I.isCommutative()) {
8074 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
8075 replaceOperand(I, 0, Pair->first);
8076 replaceOperand(I, 1, Pair->second);
8077 return &I;
8078 }
8079 }
8080
8081 // Fold icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8082 // when all select arms are constants, via truth table.
8084 return R;
8085
8086 // In case of a comparison with two select instructions having the same
8087 // condition, check whether one of the resulting branches can be simplified.
8088 // If so, just compare the other branch and select the appropriate result.
8089 // For example:
8090 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
8091 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
8092 // %cmp2 = icmp slt i32 %tmp2, %tmp1
8093 // The icmp will result false for the false value of selects and the result
8094 // will depend upon the comparison of true values of selects if %cmp is
8095 // true. Thus, transform this into:
8096 // %cmp = icmp slt i32 %y, %z
8097 // %sel = select i1 %cond, i1 %cmp, i1 false
8098 // This handles similar cases to transform.
8099 {
8100 Value *Cond, *A, *B, *C, *D;
8101 if (match(Op0, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
8103 (Op0->hasOneUse() || Op1->hasOneUse())) {
8104 // Check whether comparison of TrueValues can be simplified
8105 if (Value *Res = simplifyICmpInst(Pred, A, C, SQ)) {
8106 Value *NewICMP = Builder.CreateICmp(Pred, B, D);
8107 return SelectInst::Create(
8108 Cond, Res, NewICMP, /*NameStr=*/"", /*InsertBefore=*/nullptr,
8110 }
8111 // Check whether comparison of FalseValues can be simplified
8112 if (Value *Res = simplifyICmpInst(Pred, B, D, SQ)) {
8113 Value *NewICMP = Builder.CreateICmp(Pred, A, C);
8114 return SelectInst::Create(
8115 Cond, NewICMP, Res, /*NameStr=*/"", /*InsertBefore=*/nullptr,
8117 }
8118 }
8119 }
8120
8121 // icmp slt (sub nsw x, y), (add nsw x, y) --> icmp sgt y, 0
8122 // icmp ult (sub nuw x, y), (add nuw x, y) --> icmp ugt y, 0
8123 // icmp eq (sub nsw/nuw x, y), (add nsw/nuw x, y) --> icmp eq y, 0
8124 {
8125 Value *A, *B;
8126 CmpPredicate CmpPred;
8127 if (match(&I, m_c_ICmp(CmpPred, m_Sub(m_Value(A), m_Value(B)),
8129 auto *I0 = cast<OverflowingBinaryOperator>(Op0);
8130 auto *I1 = cast<OverflowingBinaryOperator>(Op1);
8131 bool I0NUW = I0->hasNoUnsignedWrap();
8132 bool I1NUW = I1->hasNoUnsignedWrap();
8133 bool I0NSW = I0->hasNoSignedWrap();
8134 bool I1NSW = I1->hasNoSignedWrap();
8135 if ((ICmpInst::isUnsigned(Pred) && I0NUW && I1NUW) ||
8136 (ICmpInst::isSigned(Pred) && I0NSW && I1NSW) ||
8137 (ICmpInst::isEquality(Pred) &&
8138 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
8139 return new ICmpInst(CmpPredicate::getSwapped(CmpPred), B,
8140 ConstantInt::get(Op0->getType(), 0));
8141 }
8142 }
8143 }
8144
8145 // Try to optimize equality comparisons against alloca-based pointers.
8146 if (Op0->getType()->isPointerTy() && I.isEquality()) {
8147 assert(Op1->getType()->isPointerTy() &&
8148 "Comparing pointer with non-pointer?");
8149 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
8150 if (foldAllocaCmp(Alloca))
8151 return nullptr;
8152 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
8153 if (foldAllocaCmp(Alloca))
8154 return nullptr;
8155 }
8156
8157 if (Instruction *Res = foldICmpBitCast(I))
8158 return Res;
8159
8160 // TODO: Hoist this above the min/max bailout.
8162 return R;
8163
8164 {
8165 Value *X, *Y;
8166 // Transform (X & ~Y) == 0 --> (X & Y) != 0
8167 // and (X & ~Y) != 0 --> (X & Y) == 0
8168 // if A is a power of 2.
8169 if (match(Op0, m_And(m_Value(X), m_Not(m_Value(Y)))) &&
8170 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(X, false, &I) &&
8171 I.isEquality())
8172 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(X, Y),
8173 Op1);
8174
8175 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
8176 if (Op0->getType()->isIntOrIntVectorTy()) {
8177 bool ConsumesOp0, ConsumesOp1;
8178 if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
8179 isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
8180 (ConsumesOp0 || ConsumesOp1)) {
8181 Value *InvOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
8182 Value *InvOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
8183 assert(InvOp0 && InvOp1 &&
8184 "Mismatch between isFreeToInvert and getFreelyInverted");
8185 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
8186 }
8187 }
8188
8189 Instruction *AddI = nullptr;
8191 m_Instruction(AddI))) &&
8192 isa<IntegerType>(X->getType())) {
8193 Value *Result;
8194 Constant *Overflow;
8195 // m_UAddWithOverflow can match patterns that do not include an explicit
8196 // "add" instruction, so check the opcode of the matched op.
8197 if (AddI->getOpcode() == Instruction::Add &&
8198 OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, X, Y, *AddI,
8199 Result, Overflow)) {
8200 replaceInstUsesWith(*AddI, Result);
8201 eraseInstFromFunction(*AddI);
8202 return replaceInstUsesWith(I, Overflow);
8203 }
8204 }
8205
8206 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
8207 if (match(Op0, m_NUWMul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) &&
8208 match(Op1, m_APInt(C))) {
8209 if (Instruction *R = processUMulZExtIdiom(I, Op0, C, *this))
8210 return R;
8211 }
8212
8213 // Signbit test folds
8214 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
8215 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
8216 Instruction *ExtI;
8217 if ((I.isUnsigned() || I.isEquality()) &&
8218 match(Op1,
8220 Y->getType()->getScalarSizeInBits() == 1 &&
8221 (Op0->hasOneUse() || Op1->hasOneUse())) {
8222 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
8223 Instruction *ShiftI;
8224 if (match(Op0, m_CombineAnd(m_Instruction(ShiftI),
8226 OpWidth - 1))))) {
8227 unsigned ExtOpc = ExtI->getOpcode();
8228 unsigned ShiftOpc = ShiftI->getOpcode();
8229 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
8230 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
8231 Value *SLTZero =
8232 Builder.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
8233 Value *Cmp = Builder.CreateICmp(Pred, SLTZero, Y, I.getName());
8234 return replaceInstUsesWith(I, Cmp);
8235 }
8236 }
8237 }
8238 }
8239
8240 if (Instruction *Res = foldICmpEquality(I))
8241 return Res;
8242
8244 return Res;
8245
8246 if (Instruction *Res = foldICmpOfUAddOv(I))
8247 return Res;
8248
8250 return Res;
8251
8252 // The 'cmpxchg' instruction returns an aggregate containing the old value and
8253 // an i1 which indicates whether or not we successfully did the swap.
8254 //
8255 // Replace comparisons between the old value and the expected value with the
8256 // indicator that 'cmpxchg' returns.
8257 //
8258 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
8259 // spuriously fail. In those cases, the old value may equal the expected
8260 // value but it is possible for the swap to not occur.
8261 if (I.getPredicate() == ICmpInst::ICMP_EQ)
8262 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
8263 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
8264 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
8265 !ACXI->isWeak())
8266 return ExtractValueInst::Create(ACXI, 1);
8267
8269 return Res;
8270
8271 if (I.getType()->isVectorTy())
8272 if (Instruction *Res = foldVectorCmp(I, Builder))
8273 return Res;
8274
8276 return Res;
8277
8279 return Res;
8280
8281 {
8282 Value *A;
8283 const APInt *C1, *C2;
8284 ICmpInst::Predicate Pred = I.getPredicate();
8285 if (ICmpInst::isEquality(Pred)) {
8286 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
8287 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
8288 if (match(Op0, m_And(m_SExt(m_Value(A)), m_APInt(C1))) &&
8289 match(Op1, m_APInt(C2))) {
8290 Type *InputTy = A->getType();
8291 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
8292 // c2 must be non-negative at the bitwidth of a.
8293 if (C2->getActiveBits() < InputBitWidth) {
8294 APInt TruncC1 = C1->trunc(InputBitWidth);
8295 // Check if there are 1s in C1 high bits of size InputBitWidth.
8296 if (C1->uge(APInt::getOneBitSet(C1->getBitWidth(), InputBitWidth)))
8297 TruncC1.setBit(InputBitWidth - 1);
8298 Value *AndInst = Builder.CreateAnd(A, TruncC1);
8299 return new ICmpInst(
8300 Pred, AndInst,
8301 ConstantInt::get(InputTy, C2->trunc(InputBitWidth)));
8302 }
8303 }
8304 }
8305 }
8306
8307 return Changed ? &I : nullptr;
8308}
8309
8310/// Fold fcmp ([us]itofp x, cst) if possible.
8312 Instruction *LHSI,
8313 Constant *RHSC) {
8314 const APFloat *RHS;
8315 if (!match(RHSC, m_APFloat(RHS)))
8316 return nullptr;
8317
8318 // Get the width of the mantissa. We don't want to hack on conversions that
8319 // might lose information from the integer, e.g. "i64 -> float"
8320 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8321 if (MantissaWidth == -1)
8322 return nullptr; // Unknown.
8323
8324 Type *IntTy = LHSI->getOperand(0)->getType();
8325 unsigned IntWidth = IntTy->getScalarSizeInBits();
8326 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
8327
8328 if (I.isEquality()) {
8329 FCmpInst::Predicate P = I.getPredicate();
8330 bool IsExact = false;
8331 APSInt RHSCvt(IntWidth, LHSUnsigned);
8332 RHS->convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
8333
8334 // If the floating point constant isn't an integer value, we know if we will
8335 // ever compare equal / not equal to it.
8336 if (!IsExact) {
8337 // TODO: Can never be -0.0 and other non-representable values
8338 APFloat RHSRoundInt(*RHS);
8340 if (*RHS != RHSRoundInt) {
8342 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8343
8345 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8346 }
8347 }
8348
8349 // TODO: If the constant is exactly representable, is it always OK to do
8350 // equality compares as integer?
8351 }
8352
8353 // Check to see that the input is converted from an integer type that is small
8354 // enough that preserves all bits. TODO: check here for "known" sign bits.
8355 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
8356
8357 // Following test does NOT adjust IntWidth downwards for signed inputs,
8358 // because the most negative value still requires all the mantissa bits
8359 // to distinguish it from one less than that value.
8360 if ((int)IntWidth > MantissaWidth) {
8361 // Conversion would lose accuracy. Check if loss can impact comparison.
8362 int Exp = ilogb(*RHS);
8363 if (Exp == APFloat::IEK_Inf) {
8364 int MaxExponent = ilogb(APFloat::getLargest(RHS->getSemantics()));
8365 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
8366 // Conversion could create infinity.
8367 return nullptr;
8368 } else {
8369 // Note that if RHS is zero or NaN, then Exp is negative
8370 // and first condition is trivially false.
8371 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
8372 // Conversion could affect comparison.
8373 return nullptr;
8374 }
8375 }
8376
8377 // Otherwise, we can potentially simplify the comparison. We know that it
8378 // will always come through as an integer value and we know the constant is
8379 // not a NAN (it would have been previously simplified).
8380 assert(!RHS->isNaN() && "NaN comparison not already folded!");
8381
8383 switch (I.getPredicate()) {
8384 default:
8385 llvm_unreachable("Unexpected predicate!");
8386 case FCmpInst::FCMP_UEQ:
8387 case FCmpInst::FCMP_OEQ:
8388 Pred = ICmpInst::ICMP_EQ;
8389 break;
8390 case FCmpInst::FCMP_UGT:
8391 case FCmpInst::FCMP_OGT:
8392 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
8393 break;
8394 case FCmpInst::FCMP_UGE:
8395 case FCmpInst::FCMP_OGE:
8396 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
8397 break;
8398 case FCmpInst::FCMP_ULT:
8399 case FCmpInst::FCMP_OLT:
8400 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
8401 break;
8402 case FCmpInst::FCMP_ULE:
8403 case FCmpInst::FCMP_OLE:
8404 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
8405 break;
8406 case FCmpInst::FCMP_UNE:
8407 case FCmpInst::FCMP_ONE:
8408 Pred = ICmpInst::ICMP_NE;
8409 break;
8410 case FCmpInst::FCMP_ORD:
8411 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8412 case FCmpInst::FCMP_UNO:
8413 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8414 }
8415
8416 // Now we know that the APFloat is a normal number, zero or inf.
8417
8418 // See if the FP constant is too large for the integer. For example,
8419 // comparing an i8 to 300.0.
8420 if (!LHSUnsigned) {
8421 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
8422 // and large values.
8423 APFloat SMax(RHS->getSemantics());
8424 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
8426 if (SMax < *RHS) { // smax < 13123.0
8427 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
8428 Pred == ICmpInst::ICMP_SLE)
8429 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8430 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8431 }
8432 } else {
8433 // If the RHS value is > UnsignedMax, fold the comparison. This handles
8434 // +INF and large values.
8435 APFloat UMax(RHS->getSemantics());
8436 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
8438 if (UMax < *RHS) { // umax < 13123.0
8439 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
8440 Pred == ICmpInst::ICMP_ULE)
8441 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8442 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8443 }
8444 }
8445
8446 if (!LHSUnsigned) {
8447 // See if the RHS value is < SignedMin.
8448 APFloat SMin(RHS->getSemantics());
8449 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
8451 if (SMin > *RHS) { // smin > 12312.0
8452 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
8453 Pred == ICmpInst::ICMP_SGE)
8454 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8455 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8456 }
8457 } else {
8458 // See if the RHS value is < UnsignedMin.
8459 APFloat UMin(RHS->getSemantics());
8460 UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
8462 if (UMin > *RHS) { // umin > 12312.0
8463 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
8464 Pred == ICmpInst::ICMP_UGE)
8465 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8466 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8467 }
8468 }
8469
8470 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
8471 // [0, UMAX], but it may still be fractional. Check whether this is the case
8472 // using the IsExact flag.
8473 // Don't do this for zero, because -0.0 is not fractional.
8474 APSInt RHSInt(IntWidth, LHSUnsigned);
8475 bool IsExact;
8476 RHS->convertToInteger(RHSInt, APFloat::rmTowardZero, &IsExact);
8477 if (!RHS->isZero()) {
8478 if (!IsExact) {
8479 // If we had a comparison against a fractional value, we have to adjust
8480 // the compare predicate and sometimes the value. RHSC is rounded towards
8481 // zero at this point.
8482 switch (Pred) {
8483 default:
8484 llvm_unreachable("Unexpected integer comparison!");
8485 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
8486 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8487 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
8488 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8489 case ICmpInst::ICMP_ULE:
8490 // (float)int <= 4.4 --> int <= 4
8491 // (float)int <= -4.4 --> false
8492 if (RHS->isNegative())
8493 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8494 break;
8495 case ICmpInst::ICMP_SLE:
8496 // (float)int <= 4.4 --> int <= 4
8497 // (float)int <= -4.4 --> int < -4
8498 if (RHS->isNegative())
8499 Pred = ICmpInst::ICMP_SLT;
8500 break;
8501 case ICmpInst::ICMP_ULT:
8502 // (float)int < -4.4 --> false
8503 // (float)int < 4.4 --> int <= 4
8504 if (RHS->isNegative())
8505 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8506 Pred = ICmpInst::ICMP_ULE;
8507 break;
8508 case ICmpInst::ICMP_SLT:
8509 // (float)int < -4.4 --> int < -4
8510 // (float)int < 4.4 --> int <= 4
8511 if (!RHS->isNegative())
8512 Pred = ICmpInst::ICMP_SLE;
8513 break;
8514 case