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"
18#include "llvm/Analysis/CaptureTracking.h"
19#include "llvm/Analysis/CmpInstAnalysis.h"
20#include "llvm/Analysis/ConstantFolding.h"
21#include "llvm/Analysis/InstructionSimplify.h"
22#include "llvm/Analysis/Loads.h"
23#include "llvm/Analysis/Utils/Local.h"
24#include "llvm/Analysis/VectorUtils.h"
25#include "llvm/IR/ConstantRange.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/IR/PatternMatch.h"
32#include "llvm/Support/KnownBits.h"
33#include "llvm/Transforms/InstCombine/InstCombiner.h"
34#include <bitset>
35
36using namespace llvm;
37using namespace PatternMatch;
38
39#define DEBUG_TYPE "instcombine"
40
41// How many times is a select replaced by one of its operands?
42STATISTIC(NumSel, "Number of select opts");
43
44namespace llvm {
45extern cl::opt<bool> ProfcheckDisableMetadataFixes;
46}
47
48/// Compute Result = In1+In2, returning true if the result overflowed for this
49/// type.
50static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
51 bool IsSigned = false) {
52 bool Overflow;
53 if (IsSigned)
54 Result = In1.sadd_ov(RHS: In2, Overflow);
55 else
56 Result = In1.uadd_ov(RHS: In2, Overflow);
57
58 return Overflow;
59}
60
61/// Compute Result = In1-In2, returning true if the result overflowed for this
62/// type.
63static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
64 bool IsSigned = false) {
65 bool Overflow;
66 if (IsSigned)
67 Result = In1.ssub_ov(RHS: In2, Overflow);
68 else
69 Result = In1.usub_ov(RHS: In2, Overflow);
70
71 return Overflow;
72}
73
74/// Given an icmp instruction, return true if any use of this comparison is a
75/// branch on sign bit comparison.
76static bool hasBranchUse(ICmpInst &I) {
77 for (auto *U : I.users())
78 if (isa<BranchInst>(Val: U))
79 return true;
80 return false;
81}
82
83/// Returns true if the exploded icmp can be expressed as a signed comparison
84/// to zero and updates the predicate accordingly.
85/// The signedness of the comparison is preserved.
86/// TODO: Refactor with decomposeBitTestICmp()?
87static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
88 if (!ICmpInst::isSigned(predicate: Pred))
89 return false;
90
91 if (C.isZero())
92 return ICmpInst::isRelational(P: Pred);
93
94 if (C.isOne()) {
95 if (Pred == ICmpInst::ICMP_SLT) {
96 Pred = ICmpInst::ICMP_SLE;
97 return true;
98 }
99 } else if (C.isAllOnes()) {
100 if (Pred == ICmpInst::ICMP_SGT) {
101 Pred = ICmpInst::ICMP_SGE;
102 return true;
103 }
104 }
105
106 return false;
107}
108
109/// This is called when we see this pattern:
110/// cmp pred (load (gep GV, ...)), cmpcst
111/// where GV is a global variable with a constant initializer. Try to simplify
112/// this into some simple computation that does not need the load. For example
113/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
114///
115/// If AndCst is non-null, then the loaded value is masked with that constant
116/// before doing the comparison. This handles cases like "A[i]&4 == 0".
117Instruction *InstCombinerImpl::foldCmpLoadFromIndexedGlobal(
118 LoadInst *LI, GetElementPtrInst *GEP, CmpInst &ICI, ConstantInt *AndCst) {
119 auto *GV = dyn_cast<GlobalVariable>(Val: getUnderlyingObject(V: GEP));
120 if (LI->isVolatile() || !GV || !GV->isConstant() ||
121 !GV->hasDefinitiveInitializer())
122 return nullptr;
123
124 Type *EltTy = LI->getType();
125 TypeSize EltSize = DL.getTypeStoreSize(Ty: EltTy);
126 if (EltSize.isScalable())
127 return nullptr;
128
129 LinearExpression Expr = decomposeLinearExpression(DL, Ptr: GEP);
130 if (!Expr.Index || Expr.BasePtr != GV || Expr.Offset.getBitWidth() > 64)
131 return nullptr;
132
133 Constant *Init = GV->getInitializer();
134 TypeSize GlobalSize = DL.getTypeAllocSize(Ty: Init->getType());
135
136 Value *Idx = Expr.Index;
137 const APInt &Stride = Expr.Scale;
138 const APInt &ConstOffset = Expr.Offset;
139
140 // Allow an additional context offset, but only within the stride.
141 if (!ConstOffset.ult(RHS: Stride))
142 return nullptr;
143
144 // Don't handle overlapping loads for now.
145 if (!Stride.uge(RHS: EltSize.getFixedValue()))
146 return nullptr;
147
148 // Don't blow up on huge arrays.
149 uint64_t ArrayElementCount =
150 divideCeil(Numerator: (GlobalSize.getFixedValue() - ConstOffset.getZExtValue()),
151 Denominator: Stride.getZExtValue());
152 if (ArrayElementCount > MaxArraySizeForCombine)
153 return nullptr;
154
155 enum { Overdefined = -3, Undefined = -2 };
156
157 // Variables for our state machines.
158
159 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
160 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
161 // and 87 is the second (and last) index. FirstTrueElement is -2 when
162 // undefined, otherwise set to the first true element. SecondTrueElement is
163 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
164 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
165
166 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
167 // form "i != 47 & i != 87". Same state transitions as for true elements.
168 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
169
170 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
171 /// define a state machine that triggers for ranges of values that the index
172 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
173 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
174 /// index in the range (inclusive). We use -2 for undefined here because we
175 /// use relative comparisons and don't want 0-1 to match -1.
176 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
177
178 // MagicBitvector - This is a magic bitvector where we set a bit if the
179 // comparison is true for element 'i'. If there are 64 elements or less in
180 // the array, this will fully represent all the comparison results.
181 uint64_t MagicBitvector = 0;
182
183 // Scan the array and see if one of our patterns matches.
184 Constant *CompareRHS = cast<Constant>(Val: ICI.getOperand(i_nocapture: 1));
185 APInt Offset = ConstOffset;
186 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i, Offset += Stride) {
187 Constant *Elt = ConstantFoldLoadFromConst(C: Init, Ty: EltTy, Offset, DL);
188 if (!Elt)
189 return nullptr;
190
191 // If the element is masked, handle it.
192 if (AndCst) {
193 Elt = ConstantFoldBinaryOpOperands(Opcode: Instruction::And, LHS: Elt, RHS: AndCst, DL);
194 if (!Elt)
195 return nullptr;
196 }
197
198 // Find out if the comparison would be true or false for the i'th element.
199 Constant *C = ConstantFoldCompareInstOperands(Predicate: ICI.getPredicate(), LHS: Elt,
200 RHS: CompareRHS, DL, TLI: &TLI);
201 if (!C)
202 return nullptr;
203
204 // If the result is undef for this element, ignore it.
205 if (isa<UndefValue>(Val: C)) {
206 // Extend range state machines to cover this element in case there is an
207 // undef in the middle of the range.
208 if (TrueRangeEnd == (int)i - 1)
209 TrueRangeEnd = i;
210 if (FalseRangeEnd == (int)i - 1)
211 FalseRangeEnd = i;
212 continue;
213 }
214
215 // If we can't compute the result for any of the elements, we have to give
216 // up evaluating the entire conditional.
217 if (!isa<ConstantInt>(Val: C))
218 return nullptr;
219
220 // Otherwise, we know if the comparison is true or false for this element,
221 // update our state machines.
222 bool IsTrueForElt = !cast<ConstantInt>(Val: C)->isZero();
223
224 // State machine for single/double/range index comparison.
225 if (IsTrueForElt) {
226 // Update the TrueElement state machine.
227 if (FirstTrueElement == Undefined)
228 FirstTrueElement = TrueRangeEnd = i; // First true element.
229 else {
230 // Update double-compare state machine.
231 if (SecondTrueElement == Undefined)
232 SecondTrueElement = i;
233 else
234 SecondTrueElement = Overdefined;
235
236 // Update range state machine.
237 if (TrueRangeEnd == (int)i - 1)
238 TrueRangeEnd = i;
239 else
240 TrueRangeEnd = Overdefined;
241 }
242 } else {
243 // Update the FalseElement state machine.
244 if (FirstFalseElement == Undefined)
245 FirstFalseElement = FalseRangeEnd = i; // First false element.
246 else {
247 // Update double-compare state machine.
248 if (SecondFalseElement == Undefined)
249 SecondFalseElement = i;
250 else
251 SecondFalseElement = Overdefined;
252
253 // Update range state machine.
254 if (FalseRangeEnd == (int)i - 1)
255 FalseRangeEnd = i;
256 else
257 FalseRangeEnd = Overdefined;
258 }
259 }
260
261 // If this element is in range, update our magic bitvector.
262 if (i < 64 && IsTrueForElt)
263 MagicBitvector |= 1ULL << i;
264
265 // If all of our states become overdefined, bail out early. Since the
266 // predicate is expensive, only check it every 8 elements. This is only
267 // really useful for really huge arrays.
268 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
269 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
270 FalseRangeEnd == Overdefined)
271 return nullptr;
272 }
273
274 // Now that we've scanned the entire array, emit our new comparison(s). We
275 // order the state machines in complexity of the generated code.
276
277 // If inbounds keyword is not present, Idx * Stride can overflow.
278 // Let's assume that Stride is 2 and the wanted value is at offset 0.
279 // Then, there are two possible values for Idx to match offset 0:
280 // 0x00..00, 0x80..00.
281 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
282 // comparison is false if Idx was 0x80..00.
283 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
284 auto MaskIdx = [&](Value *Idx) {
285 if (!Expr.Flags.isInBounds() && Stride.countr_zero() != 0) {
286 Value *Mask = Constant::getAllOnesValue(Ty: Idx->getType());
287 Mask = Builder.CreateLShr(LHS: Mask, RHS: Stride.countr_zero());
288 Idx = Builder.CreateAnd(LHS: Idx, RHS: Mask);
289 }
290 return Idx;
291 };
292
293 // If the comparison is only true for one or two elements, emit direct
294 // comparisons.
295 if (SecondTrueElement != Overdefined) {
296 Idx = MaskIdx(Idx);
297 // None true -> false.
298 if (FirstTrueElement == Undefined)
299 return replaceInstUsesWith(I&: ICI, V: Builder.getFalse());
300
301 Value *FirstTrueIdx = ConstantInt::get(Ty: Idx->getType(), V: FirstTrueElement);
302
303 // True for one element -> 'i == 47'.
304 if (SecondTrueElement == Undefined)
305 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
306
307 // True for two elements -> 'i == 47 | i == 72'.
308 Value *C1 = Builder.CreateICmpEQ(LHS: Idx, RHS: FirstTrueIdx);
309 Value *SecondTrueIdx = ConstantInt::get(Ty: Idx->getType(), V: SecondTrueElement);
310 Value *C2 = Builder.CreateICmpEQ(LHS: Idx, RHS: SecondTrueIdx);
311 return BinaryOperator::CreateOr(V1: C1, V2: C2);
312 }
313
314 // If the comparison is only false for one or two elements, emit direct
315 // comparisons.
316 if (SecondFalseElement != Overdefined) {
317 Idx = MaskIdx(Idx);
318 // None false -> true.
319 if (FirstFalseElement == Undefined)
320 return replaceInstUsesWith(I&: ICI, V: Builder.getTrue());
321
322 Value *FirstFalseIdx = ConstantInt::get(Ty: Idx->getType(), V: FirstFalseElement);
323
324 // False for one element -> 'i != 47'.
325 if (SecondFalseElement == Undefined)
326 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
327
328 // False for two elements -> 'i != 47 & i != 72'.
329 Value *C1 = Builder.CreateICmpNE(LHS: Idx, RHS: FirstFalseIdx);
330 Value *SecondFalseIdx =
331 ConstantInt::get(Ty: Idx->getType(), V: SecondFalseElement);
332 Value *C2 = Builder.CreateICmpNE(LHS: Idx, RHS: SecondFalseIdx);
333 return BinaryOperator::CreateAnd(V1: C1, V2: C2);
334 }
335
336 // If the comparison can be replaced with a range comparison for the elements
337 // where it is true, emit the range check.
338 if (TrueRangeEnd != Overdefined) {
339 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
340 Idx = MaskIdx(Idx);
341
342 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
343 if (FirstTrueElement) {
344 Value *Offs = ConstantInt::getSigned(Ty: Idx->getType(), V: -FirstTrueElement);
345 Idx = Builder.CreateAdd(LHS: Idx, RHS: Offs);
346 }
347
348 Value *End =
349 ConstantInt::get(Ty: Idx->getType(), V: TrueRangeEnd - FirstTrueElement + 1);
350 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
351 }
352
353 // False range check.
354 if (FalseRangeEnd != Overdefined) {
355 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
356 Idx = MaskIdx(Idx);
357 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
358 if (FirstFalseElement) {
359 Value *Offs = ConstantInt::getSigned(Ty: Idx->getType(), V: -FirstFalseElement);
360 Idx = Builder.CreateAdd(LHS: Idx, RHS: Offs);
361 }
362
363 Value *End =
364 ConstantInt::get(Ty: Idx->getType(), V: FalseRangeEnd - FirstFalseElement);
365 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
366 }
367
368 // If a magic bitvector captures the entire comparison state
369 // of this load, replace it with computation that does:
370 // ((magic_cst >> i) & 1) != 0
371 {
372 Type *Ty = nullptr;
373
374 // Look for an appropriate type:
375 // - The type of Idx if the magic fits
376 // - The smallest fitting legal type
377 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
378 Ty = Idx->getType();
379 else
380 Ty = DL.getSmallestLegalIntType(C&: Init->getContext(), Width: ArrayElementCount);
381
382 if (Ty) {
383 Idx = MaskIdx(Idx);
384 Value *V = Builder.CreateIntCast(V: Idx, DestTy: Ty, isSigned: false);
385 V = Builder.CreateLShr(LHS: ConstantInt::get(Ty, V: MagicBitvector), RHS: V);
386 V = Builder.CreateAnd(LHS: ConstantInt::get(Ty, V: 1), RHS: V);
387 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, V: 0));
388 }
389 }
390
391 return nullptr;
392}
393
394/// Returns true if we can rewrite Start as a GEP with pointer Base
395/// and some integer offset. The nodes that need to be re-written
396/// for this transformation will be added to Explored.
397static bool canRewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags &NW,
398 const DataLayout &DL,
399 SetVector<Value *> &Explored) {
400 SmallVector<Value *, 16> WorkList(1, Start);
401 Explored.insert(X: Base);
402
403 // The following traversal gives us an order which can be used
404 // when doing the final transformation. Since in the final
405 // transformation we create the PHI replacement instructions first,
406 // we don't have to get them in any particular order.
407 //
408 // However, for other instructions we will have to traverse the
409 // operands of an instruction first, which means that we have to
410 // do a post-order traversal.
411 while (!WorkList.empty()) {
412 SetVector<PHINode *> PHIs;
413
414 while (!WorkList.empty()) {
415 if (Explored.size() >= 100)
416 return false;
417
418 Value *V = WorkList.back();
419
420 if (Explored.contains(key: V)) {
421 WorkList.pop_back();
422 continue;
423 }
424
425 if (!isa<GetElementPtrInst>(Val: V) && !isa<PHINode>(Val: V))
426 // We've found some value that we can't explore which is different from
427 // the base. Therefore we can't do this transformation.
428 return false;
429
430 if (auto *GEP = dyn_cast<GEPOperator>(Val: V)) {
431 // Only allow inbounds GEPs with at most one variable offset.
432 auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(Val: V); };
433 if (!GEP->isInBounds() || count_if(Range: GEP->indices(), P: IsNonConst) > 1)
434 return false;
435
436 NW = NW.intersectForOffsetAdd(Other: GEP->getNoWrapFlags());
437 if (!Explored.contains(key: GEP->getOperand(i_nocapture: 0)))
438 WorkList.push_back(Elt: GEP->getOperand(i_nocapture: 0));
439 }
440
441 if (WorkList.back() == V) {
442 WorkList.pop_back();
443 // We've finished visiting this node, mark it as such.
444 Explored.insert(X: V);
445 }
446
447 if (auto *PN = dyn_cast<PHINode>(Val: V)) {
448 // We cannot transform PHIs on unsplittable basic blocks.
449 if (isa<CatchSwitchInst>(Val: PN->getParent()->getTerminator()))
450 return false;
451 Explored.insert(X: PN);
452 PHIs.insert(X: PN);
453 }
454 }
455
456 // Explore the PHI nodes further.
457 for (auto *PN : PHIs)
458 for (Value *Op : PN->incoming_values())
459 if (!Explored.contains(key: Op))
460 WorkList.push_back(Elt: Op);
461 }
462
463 // Make sure that we can do this. Since we can't insert GEPs in a basic
464 // block before a PHI node, we can't easily do this transformation if
465 // we have PHI node users of transformed instructions.
466 for (Value *Val : Explored) {
467 for (Value *Use : Val->uses()) {
468
469 auto *PHI = dyn_cast<PHINode>(Val: Use);
470 auto *Inst = dyn_cast<Instruction>(Val);
471
472 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
473 !Explored.contains(key: PHI))
474 continue;
475
476 if (PHI->getParent() == Inst->getParent())
477 return false;
478 }
479 }
480 return true;
481}
482
483// Sets the appropriate insert point on Builder where we can add
484// a replacement Instruction for V (if that is possible).
485static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
486 bool Before = true) {
487 if (auto *PHI = dyn_cast<PHINode>(Val: V)) {
488 BasicBlock *Parent = PHI->getParent();
489 Builder.SetInsertPoint(TheBB: Parent, IP: Parent->getFirstInsertionPt());
490 return;
491 }
492 if (auto *I = dyn_cast<Instruction>(Val: V)) {
493 if (!Before)
494 I = &*std::next(x: I->getIterator());
495 Builder.SetInsertPoint(I);
496 return;
497 }
498 if (auto *A = dyn_cast<Argument>(Val: V)) {
499 // Set the insertion point in the entry block.
500 BasicBlock &Entry = A->getParent()->getEntryBlock();
501 Builder.SetInsertPoint(TheBB: &Entry, IP: Entry.getFirstInsertionPt());
502 return;
503 }
504 // Otherwise, this is a constant and we don't need to set a new
505 // insertion point.
506 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
507}
508
509/// Returns a re-written value of Start as an indexed GEP using Base as a
510/// pointer.
511static Value *rewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags NW,
512 const DataLayout &DL,
513 SetVector<Value *> &Explored,
514 InstCombiner &IC) {
515 // Perform all the substitutions. This is a bit tricky because we can
516 // have cycles in our use-def chains.
517 // 1. Create the PHI nodes without any incoming values.
518 // 2. Create all the other values.
519 // 3. Add the edges for the PHI nodes.
520 // 4. Emit GEPs to get the original pointers.
521 // 5. Remove the original instructions.
522 Type *IndexType = IntegerType::get(
523 C&: Base->getContext(), NumBits: DL.getIndexTypeSizeInBits(Ty: Start->getType()));
524
525 DenseMap<Value *, Value *> NewInsts;
526 NewInsts[Base] = ConstantInt::getNullValue(Ty: IndexType);
527
528 // Create the new PHI nodes, without adding any incoming values.
529 for (Value *Val : Explored) {
530 if (Val == Base)
531 continue;
532 // Create empty phi nodes. This avoids cyclic dependencies when creating
533 // the remaining instructions.
534 if (auto *PHI = dyn_cast<PHINode>(Val))
535 NewInsts[PHI] =
536 PHINode::Create(Ty: IndexType, NumReservedValues: PHI->getNumIncomingValues(),
537 NameStr: PHI->getName() + ".idx", InsertBefore: PHI->getIterator());
538 }
539 IRBuilder<> Builder(Base->getContext());
540
541 // Create all the other instructions.
542 for (Value *Val : Explored) {
543 if (NewInsts.contains(Val))
544 continue;
545
546 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
547 setInsertionPoint(Builder, V: GEP);
548 Value *Op = NewInsts[GEP->getOperand(i_nocapture: 0)];
549 Value *OffsetV = emitGEPOffset(Builder: &Builder, DL, GEP);
550 if (isa<ConstantInt>(Val: Op) && cast<ConstantInt>(Val: Op)->isZero())
551 NewInsts[GEP] = OffsetV;
552 else
553 NewInsts[GEP] = Builder.CreateAdd(
554 LHS: Op, RHS: OffsetV, Name: GEP->getOperand(i_nocapture: 0)->getName() + ".add",
555 /*NUW=*/HasNUW: NW.hasNoUnsignedWrap(),
556 /*NSW=*/HasNSW: NW.hasNoUnsignedSignedWrap());
557 continue;
558 }
559 if (isa<PHINode>(Val))
560 continue;
561
562 llvm_unreachable("Unexpected instruction type");
563 }
564
565 // Add the incoming values to the PHI nodes.
566 for (Value *Val : Explored) {
567 if (Val == Base)
568 continue;
569 // All the instructions have been created, we can now add edges to the
570 // phi nodes.
571 if (auto *PHI = dyn_cast<PHINode>(Val)) {
572 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
573 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
574 Value *NewIncoming = PHI->getIncomingValue(i: I);
575
576 auto It = NewInsts.find(Val: NewIncoming);
577 if (It != NewInsts.end())
578 NewIncoming = It->second;
579
580 NewPhi->addIncoming(V: NewIncoming, BB: PHI->getIncomingBlock(i: I));
581 }
582 }
583 }
584
585 for (Value *Val : Explored) {
586 if (Val == Base)
587 continue;
588
589 setInsertionPoint(Builder, V: Val, Before: false);
590 // Create GEP for external users.
591 Value *NewVal = Builder.CreateGEP(Ty: Builder.getInt8Ty(), Ptr: Base, IdxList: NewInsts[Val],
592 Name: Val->getName() + ".ptr", NW);
593 IC.replaceInstUsesWith(I&: *cast<Instruction>(Val), V: NewVal);
594 // Add old instruction to worklist for DCE. We don't directly remove it
595 // here because the original compare is one of the users.
596 IC.addToWorklist(I: cast<Instruction>(Val));
597 }
598
599 return NewInsts[Start];
600}
601
602/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
603/// We can look through PHIs, GEPs and casts in order to determine a common base
604/// between GEPLHS and RHS.
605static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
606 CmpPredicate Cond,
607 const DataLayout &DL,
608 InstCombiner &IC) {
609 // FIXME: Support vector of pointers.
610 if (GEPLHS->getType()->isVectorTy())
611 return nullptr;
612
613 if (!GEPLHS->hasAllConstantIndices())
614 return nullptr;
615
616 APInt Offset(DL.getIndexTypeSizeInBits(Ty: GEPLHS->getType()), 0);
617 Value *PtrBase =
618 GEPLHS->stripAndAccumulateConstantOffsets(DL, Offset,
619 /*AllowNonInbounds*/ false);
620
621 // Bail if we looked through addrspacecast.
622 if (PtrBase->getType() != GEPLHS->getType())
623 return nullptr;
624
625 // The set of nodes that will take part in this transformation.
626 SetVector<Value *> Nodes;
627 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags();
628 if (!canRewriteGEPAsOffset(Start: RHS, Base: PtrBase, NW, DL, Explored&: Nodes))
629 return nullptr;
630
631 // We know we can re-write this as
632 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
633 // Since we've only looked through inbouds GEPs we know that we
634 // can't have overflow on either side. We can therefore re-write
635 // this as:
636 // OFFSET1 cmp OFFSET2
637 Value *NewRHS = rewriteGEPAsOffset(Start: RHS, Base: PtrBase, NW, DL, Explored&: Nodes, IC);
638
639 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
640 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
641 // offset. Since Index is the offset of LHS to the base pointer, we will now
642 // compare the offsets instead of comparing the pointers.
643 return new ICmpInst(ICmpInst::getSignedPredicate(Pred: Cond),
644 IC.Builder.getInt(AI: Offset), NewRHS);
645}
646
647/// Fold comparisons between a GEP instruction and something else. At this point
648/// we know that the GEP is on the LHS of the comparison.
649Instruction *InstCombinerImpl::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
650 CmpPredicate Cond, Instruction &I) {
651 // Don't transform signed compares of GEPs into index compares. Even if the
652 // GEP is inbounds, the final add of the base pointer can have signed overflow
653 // and would change the result of the icmp.
654 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
655 // the maximum signed value for the pointer type.
656 if (ICmpInst::isSigned(predicate: Cond))
657 return nullptr;
658
659 // Look through bitcasts and addrspacecasts. We do not however want to remove
660 // 0 GEPs.
661 if (!isa<GetElementPtrInst>(Val: RHS))
662 RHS = RHS->stripPointerCasts();
663
664 auto CanFold = [Cond](GEPNoWrapFlags NW) {
665 if (ICmpInst::isEquality(P: Cond))
666 return true;
667
668 // Unsigned predicates can be folded if the GEPs have *any* nowrap flags.
669 assert(ICmpInst::isUnsigned(Cond));
670 return NW != GEPNoWrapFlags::none();
671 };
672
673 auto NewICmp = [Cond](GEPNoWrapFlags NW, Value *Op1, Value *Op2) {
674 if (!NW.hasNoUnsignedWrap()) {
675 // Convert signed to unsigned comparison.
676 return new ICmpInst(ICmpInst::getSignedPredicate(Pred: Cond), Op1, Op2);
677 }
678
679 auto *I = new ICmpInst(Cond, Op1, Op2);
680 I->setSameSign(NW.hasNoUnsignedSignedWrap());
681 return I;
682 };
683
684 CommonPointerBase Base = CommonPointerBase::compute(LHS: GEPLHS, RHS);
685 if (Base.Ptr == RHS && CanFold(Base.LHSNW) && !Base.isExpensive()) {
686 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
687 Type *IdxTy = DL.getIndexType(PtrTy: GEPLHS->getType());
688 Value *Offset =
689 EmitGEPOffsets(GEPs: Base.LHSGEPs, NW: Base.LHSNW, IdxTy, /*RewriteGEPs=*/true);
690 return NewICmp(Base.LHSNW, Offset,
691 Constant::getNullValue(Ty: Offset->getType()));
692 }
693
694 if (GEPLHS->isInBounds() && ICmpInst::isEquality(P: Cond) &&
695 isa<Constant>(Val: RHS) && cast<Constant>(Val: RHS)->isNullValue() &&
696 !NullPointerIsDefined(F: I.getFunction(),
697 AS: RHS->getType()->getPointerAddressSpace())) {
698 // For most address spaces, an allocation can't be placed at null, but null
699 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
700 // the only valid inbounds address derived from null, is null itself.
701 // Thus, we have four cases to consider:
702 // 1) Base == nullptr, Offset == 0 -> inbounds, null
703 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
704 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
705 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
706 //
707 // (Note if we're indexing a type of size 0, that simply collapses into one
708 // of the buckets above.)
709 //
710 // In general, we're allowed to make values less poison (i.e. remove
711 // sources of full UB), so in this case, we just select between the two
712 // non-poison cases (1 and 4 above).
713 //
714 // For vectors, we apply the same reasoning on a per-lane basis.
715 auto *Base = GEPLHS->getPointerOperand();
716 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
717 auto EC = cast<VectorType>(Val: GEPLHS->getType())->getElementCount();
718 Base = Builder.CreateVectorSplat(EC, V: Base);
719 }
720 return new ICmpInst(Cond, Base,
721 ConstantExpr::getPointerBitCastOrAddrSpaceCast(
722 C: cast<Constant>(Val: RHS), Ty: Base->getType()));
723 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(Val: RHS)) {
724 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags() & GEPRHS->getNoWrapFlags();
725
726 // If the base pointers are different, but the indices are the same, just
727 // compare the base pointer.
728 if (GEPLHS->getOperand(i_nocapture: 0) != GEPRHS->getOperand(i_nocapture: 0)) {
729 bool IndicesTheSame =
730 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
731 GEPLHS->getPointerOperand()->getType() ==
732 GEPRHS->getPointerOperand()->getType() &&
733 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
734 if (IndicesTheSame)
735 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
736 if (GEPLHS->getOperand(i_nocapture: i) != GEPRHS->getOperand(i_nocapture: i)) {
737 IndicesTheSame = false;
738 break;
739 }
740
741 // If all indices are the same, just compare the base pointers.
742 Type *BaseType = GEPLHS->getOperand(i_nocapture: 0)->getType();
743 if (IndicesTheSame &&
744 CmpInst::makeCmpResultType(opnd_type: BaseType) == I.getType() && CanFold(NW))
745 return new ICmpInst(Cond, GEPLHS->getOperand(i_nocapture: 0), GEPRHS->getOperand(i_nocapture: 0));
746
747 // If we're comparing GEPs with two base pointers that only differ in type
748 // and both GEPs have only constant indices or just one use, then fold
749 // the compare with the adjusted indices.
750 // FIXME: Support vector of pointers.
751 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
752 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
753 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
754 GEPLHS->getOperand(i_nocapture: 0)->stripPointerCasts() ==
755 GEPRHS->getOperand(i_nocapture: 0)->stripPointerCasts() &&
756 !GEPLHS->getType()->isVectorTy()) {
757 Value *LOffset = EmitGEPOffset(GEP: GEPLHS);
758 Value *ROffset = EmitGEPOffset(GEP: GEPRHS);
759
760 // If we looked through an addrspacecast between different sized address
761 // spaces, the LHS and RHS pointers are different sized
762 // integers. Truncate to the smaller one.
763 Type *LHSIndexTy = LOffset->getType();
764 Type *RHSIndexTy = ROffset->getType();
765 if (LHSIndexTy != RHSIndexTy) {
766 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
767 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
768 ROffset = Builder.CreateTrunc(V: ROffset, DestTy: LHSIndexTy);
769 } else
770 LOffset = Builder.CreateTrunc(V: LOffset, DestTy: RHSIndexTy);
771 }
772
773 Value *Cmp = Builder.CreateICmp(P: ICmpInst::getSignedPredicate(Pred: Cond),
774 LHS: LOffset, RHS: ROffset);
775 return replaceInstUsesWith(I, V: Cmp);
776 }
777 }
778
779 if (GEPLHS->getOperand(i_nocapture: 0) == GEPRHS->getOperand(i_nocapture: 0) &&
780 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
781 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
782 // If the GEPs only differ by one index, compare it.
783 unsigned NumDifferences = 0; // Keep track of # differences.
784 unsigned DiffOperand = 0; // The operand that differs.
785 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
786 if (GEPLHS->getOperand(i_nocapture: i) != GEPRHS->getOperand(i_nocapture: i)) {
787 Type *LHSType = GEPLHS->getOperand(i_nocapture: i)->getType();
788 Type *RHSType = GEPRHS->getOperand(i_nocapture: i)->getType();
789 // FIXME: Better support for vector of pointers.
790 if (LHSType->getPrimitiveSizeInBits() !=
791 RHSType->getPrimitiveSizeInBits() ||
792 (GEPLHS->getType()->isVectorTy() &&
793 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
794 // Irreconcilable differences.
795 NumDifferences = 2;
796 break;
797 }
798
799 if (NumDifferences++)
800 break;
801 DiffOperand = i;
802 }
803
804 if (NumDifferences == 0) // SAME GEP?
805 return replaceInstUsesWith(
806 I, // No comparison is needed here.
807 V: ConstantInt::get(Ty: I.getType(), V: ICmpInst::isTrueWhenEqual(predicate: Cond)));
808 // If two GEPs only differ by an index, compare them.
809 // Note that nowrap flags are always needed when comparing two indices.
810 else if (NumDifferences == 1 && NW != GEPNoWrapFlags::none()) {
811 Value *LHSV = GEPLHS->getOperand(i_nocapture: DiffOperand);
812 Value *RHSV = GEPRHS->getOperand(i_nocapture: DiffOperand);
813 return NewICmp(NW, LHSV, RHSV);
814 }
815 }
816
817 if (Base.Ptr && CanFold(Base.LHSNW & Base.RHSNW) && !Base.isExpensive()) {
818 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
819 Type *IdxTy = DL.getIndexType(PtrTy: GEPLHS->getType());
820 Value *L =
821 EmitGEPOffsets(GEPs: Base.LHSGEPs, NW: Base.LHSNW, IdxTy, /*RewriteGEP=*/RewriteGEPs: true);
822 Value *R =
823 EmitGEPOffsets(GEPs: Base.RHSGEPs, NW: Base.RHSNW, IdxTy, /*RewriteGEP=*/RewriteGEPs: true);
824 return NewICmp(Base.LHSNW & Base.RHSNW, L, R);
825 }
826 }
827
828 // Try convert this to an indexed compare by looking through PHIs/casts as a
829 // last resort.
830 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, IC&: *this);
831}
832
833bool InstCombinerImpl::foldAllocaCmp(AllocaInst *Alloca) {
834 // It would be tempting to fold away comparisons between allocas and any
835 // pointer not based on that alloca (e.g. an argument). However, even
836 // though such pointers cannot alias, they can still compare equal.
837 //
838 // But LLVM doesn't specify where allocas get their memory, so if the alloca
839 // doesn't escape we can argue that it's impossible to guess its value, and we
840 // can therefore act as if any such guesses are wrong.
841 //
842 // However, we need to ensure that this folding is consistent: We can't fold
843 // one comparison to false, and then leave a different comparison against the
844 // same value alone (as it might evaluate to true at runtime, leading to a
845 // contradiction). As such, this code ensures that all comparisons are folded
846 // at the same time, and there are no other escapes.
847
848 struct CmpCaptureTracker : public CaptureTracker {
849 AllocaInst *Alloca;
850 bool Captured = false;
851 /// The value of the map is a bit mask of which icmp operands the alloca is
852 /// used in.
853 SmallMapVector<ICmpInst *, unsigned, 4> ICmps;
854
855 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
856
857 void tooManyUses() override { Captured = true; }
858
859 Action captured(const Use *U, UseCaptureInfo CI) override {
860 // TODO(captures): Use UseCaptureInfo.
861 auto *ICmp = dyn_cast<ICmpInst>(Val: U->getUser());
862 // We need to check that U is based *only* on the alloca, and doesn't
863 // have other contributions from a select/phi operand.
864 // TODO: We could check whether getUnderlyingObjects() reduces to one
865 // object, which would allow looking through phi nodes.
866 if (ICmp && ICmp->isEquality() && getUnderlyingObject(V: *U) == Alloca) {
867 // Collect equality icmps of the alloca, and don't treat them as
868 // captures.
869 ICmps[ICmp] |= 1u << U->getOperandNo();
870 return Continue;
871 }
872
873 Captured = true;
874 return Stop;
875 }
876 };
877
878 CmpCaptureTracker Tracker(Alloca);
879 PointerMayBeCaptured(V: Alloca, Tracker: &Tracker);
880 if (Tracker.Captured)
881 return false;
882
883 bool Changed = false;
884 for (auto [ICmp, Operands] : Tracker.ICmps) {
885 switch (Operands) {
886 case 1:
887 case 2: {
888 // The alloca is only used in one icmp operand. Assume that the
889 // equality is false.
890 auto *Res = ConstantInt::get(Ty: ICmp->getType(),
891 V: ICmp->getPredicate() == ICmpInst::ICMP_NE);
892 replaceInstUsesWith(I&: *ICmp, V: Res);
893 eraseInstFromFunction(I&: *ICmp);
894 Changed = true;
895 break;
896 }
897 case 3:
898 // Both icmp operands are based on the alloca, so this is comparing
899 // pointer offsets, without leaking any information about the address
900 // of the alloca. Ignore such comparisons.
901 break;
902 default:
903 llvm_unreachable("Cannot happen");
904 }
905 }
906
907 return Changed;
908}
909
910/// Fold "icmp pred (X+C), X".
911Instruction *InstCombinerImpl::foldICmpAddOpConst(Value *X, const APInt &C,
912 CmpPredicate Pred) {
913 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
914 // so the values can never be equal. Similarly for all other "or equals"
915 // operators.
916 assert(!!C && "C should not be zero!");
917
918 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
919 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
920 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
921 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
922 Constant *R =
923 ConstantInt::get(Ty: X->getType(), V: APInt::getMaxValue(numBits: C.getBitWidth()) - C);
924 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
925 }
926
927 // (X+1) >u X --> X <u (0-1) --> X != 255
928 // (X+2) >u X --> X <u (0-2) --> X <u 254
929 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
930 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
931 return new ICmpInst(ICmpInst::ICMP_ULT, X,
932 ConstantInt::get(Ty: X->getType(), V: -C));
933
934 APInt SMax = APInt::getSignedMaxValue(numBits: C.getBitWidth());
935
936 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
937 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
938 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
939 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
940 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
941 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
942 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
943 return new ICmpInst(ICmpInst::ICMP_SGT, X,
944 ConstantInt::get(Ty: X->getType(), V: SMax - C));
945
946 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
947 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
948 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
949 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
950 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
951 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
952
953 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
954 return new ICmpInst(ICmpInst::ICMP_SLT, X,
955 ConstantInt::get(Ty: X->getType(), V: SMax - (C - 1)));
956}
957
958/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
959/// (icmp eq/ne A, Log2(AP2/AP1)) ->
960/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
961Instruction *InstCombinerImpl::foldICmpShrConstConst(ICmpInst &I, Value *A,
962 const APInt &AP1,
963 const APInt &AP2) {
964 assert(I.isEquality() && "Cannot fold icmp gt/lt");
965
966 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
967 if (I.getPredicate() == I.ICMP_NE)
968 Pred = CmpInst::getInversePredicate(pred: Pred);
969 return new ICmpInst(Pred, LHS, RHS);
970 };
971
972 // Don't bother doing any work for cases which InstSimplify handles.
973 if (AP2.isZero())
974 return nullptr;
975
976 bool IsAShr = isa<AShrOperator>(Val: I.getOperand(i_nocapture: 0));
977 if (IsAShr) {
978 if (AP2.isAllOnes())
979 return nullptr;
980 if (AP2.isNegative() != AP1.isNegative())
981 return nullptr;
982 if (AP2.sgt(RHS: AP1))
983 return nullptr;
984 }
985
986 if (!AP1)
987 // 'A' must be large enough to shift out the highest set bit.
988 return getICmp(I.ICMP_UGT, A,
989 ConstantInt::get(Ty: A->getType(), V: AP2.logBase2()));
990
991 if (AP1 == AP2)
992 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(Ty: A->getType()));
993
994 int Shift;
995 if (IsAShr && AP1.isNegative())
996 Shift = AP1.countl_one() - AP2.countl_one();
997 else
998 Shift = AP1.countl_zero() - AP2.countl_zero();
999
1000 if (Shift > 0) {
1001 if (IsAShr && AP1 == AP2.ashr(ShiftAmt: Shift)) {
1002 // There are multiple solutions if we are comparing against -1 and the LHS
1003 // of the ashr is not a power of two.
1004 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1005 return getICmp(I.ICMP_UGE, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1006 return getICmp(I.ICMP_EQ, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1007 } else if (AP1 == AP2.lshr(shiftAmt: Shift)) {
1008 return getICmp(I.ICMP_EQ, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1009 }
1010 }
1011
1012 // Shifting const2 will never be equal to const1.
1013 // FIXME: This should always be handled by InstSimplify?
1014 auto *TorF = ConstantInt::get(Ty: I.getType(), V: I.getPredicate() == I.ICMP_NE);
1015 return replaceInstUsesWith(I, V: TorF);
1016}
1017
1018/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1019/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1020Instruction *InstCombinerImpl::foldICmpShlConstConst(ICmpInst &I, Value *A,
1021 const APInt &AP1,
1022 const APInt &AP2) {
1023 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1024
1025 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1026 if (I.getPredicate() == I.ICMP_NE)
1027 Pred = CmpInst::getInversePredicate(pred: Pred);
1028 return new ICmpInst(Pred, LHS, RHS);
1029 };
1030
1031 // Don't bother doing any work for cases which InstSimplify handles.
1032 if (AP2.isZero())
1033 return nullptr;
1034
1035 unsigned AP2TrailingZeros = AP2.countr_zero();
1036
1037 if (!AP1 && AP2TrailingZeros != 0)
1038 return getICmp(
1039 I.ICMP_UGE, A,
1040 ConstantInt::get(Ty: A->getType(), V: AP2.getBitWidth() - AP2TrailingZeros));
1041
1042 if (AP1 == AP2)
1043 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(Ty: A->getType()));
1044
1045 // Get the distance between the lowest bits that are set.
1046 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1047
1048 if (Shift > 0 && AP2.shl(shiftAmt: Shift) == AP1)
1049 return getICmp(I.ICMP_EQ, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1050
1051 // Shifting const2 will never be equal to const1.
1052 // FIXME: This should always be handled by InstSimplify?
1053 auto *TorF = ConstantInt::get(Ty: I.getType(), V: I.getPredicate() == I.ICMP_NE);
1054 return replaceInstUsesWith(I, V: TorF);
1055}
1056
1057/// The caller has matched a pattern of the form:
1058/// I = icmp ugt (add (add A, B), CI2), CI1
1059/// If this is of the form:
1060/// sum = a + b
1061/// if (sum+128 >u 255)
1062/// Then replace it with llvm.sadd.with.overflow.i8.
1063///
1064static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1065 ConstantInt *CI2, ConstantInt *CI1,
1066 InstCombinerImpl &IC) {
1067 // The transformation we're trying to do here is to transform this into an
1068 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1069 // with a narrower add, and discard the add-with-constant that is part of the
1070 // range check (if we can't eliminate it, this isn't profitable).
1071
1072 // In order to eliminate the add-with-constant, the compare can be its only
1073 // use.
1074 Instruction *AddWithCst = cast<Instruction>(Val: I.getOperand(i_nocapture: 0));
1075 if (!AddWithCst->hasOneUse())
1076 return nullptr;
1077
1078 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1079 if (!CI2->getValue().isPowerOf2())
1080 return nullptr;
1081 unsigned NewWidth = CI2->getValue().countr_zero();
1082 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1083 return nullptr;
1084
1085 // The width of the new add formed is 1 more than the bias.
1086 ++NewWidth;
1087
1088 // Check to see that CI1 is an all-ones value with NewWidth bits.
1089 if (CI1->getBitWidth() == NewWidth ||
1090 CI1->getValue() != APInt::getLowBitsSet(numBits: CI1->getBitWidth(), loBitsSet: NewWidth))
1091 return nullptr;
1092
1093 // This is only really a signed overflow check if the inputs have been
1094 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1095 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1096 if (IC.ComputeMaxSignificantBits(Op: A, CxtI: &I) > NewWidth ||
1097 IC.ComputeMaxSignificantBits(Op: B, CxtI: &I) > NewWidth)
1098 return nullptr;
1099
1100 // In order to replace the original add with a narrower
1101 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1102 // and truncates that discard the high bits of the add. Verify that this is
1103 // the case.
1104 Instruction *OrigAdd = cast<Instruction>(Val: AddWithCst->getOperand(i: 0));
1105 for (User *U : OrigAdd->users()) {
1106 if (U == AddWithCst)
1107 continue;
1108
1109 // Only accept truncates for now. We would really like a nice recursive
1110 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1111 // chain to see which bits of a value are actually demanded. If the
1112 // original add had another add which was then immediately truncated, we
1113 // could still do the transformation.
1114 TruncInst *TI = dyn_cast<TruncInst>(Val: U);
1115 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1116 return nullptr;
1117 }
1118
1119 // If the pattern matches, truncate the inputs to the narrower type and
1120 // use the sadd_with_overflow intrinsic to efficiently compute both the
1121 // result and the overflow bit.
1122 Type *NewType = IntegerType::get(C&: OrigAdd->getContext(), NumBits: NewWidth);
1123 Function *F = Intrinsic::getOrInsertDeclaration(
1124 M: I.getModule(), id: Intrinsic::sadd_with_overflow, Tys: NewType);
1125
1126 InstCombiner::BuilderTy &Builder = IC.Builder;
1127
1128 // Put the new code above the original add, in case there are any uses of the
1129 // add between the add and the compare.
1130 Builder.SetInsertPoint(OrigAdd);
1131
1132 Value *TruncA = Builder.CreateTrunc(V: A, DestTy: NewType, Name: A->getName() + ".trunc");
1133 Value *TruncB = Builder.CreateTrunc(V: B, DestTy: NewType, Name: B->getName() + ".trunc");
1134 CallInst *Call = Builder.CreateCall(Callee: F, Args: {TruncA, TruncB}, Name: "sadd");
1135 Value *Add = Builder.CreateExtractValue(Agg: Call, Idxs: 0, Name: "sadd.result");
1136 Value *ZExt = Builder.CreateZExt(V: Add, DestTy: OrigAdd->getType());
1137
1138 // The inner add was the result of the narrow add, zero extended to the
1139 // wider type. Replace it with the result computed by the intrinsic.
1140 IC.replaceInstUsesWith(I&: *OrigAdd, V: ZExt);
1141 IC.eraseInstFromFunction(I&: *OrigAdd);
1142
1143 // The original icmp gets replaced with the overflow value.
1144 return ExtractValueInst::Create(Agg: Call, Idxs: 1, NameStr: "sadd.overflow");
1145}
1146
1147/// If we have:
1148/// icmp eq/ne (urem/srem %x, %y), 0
1149/// iff %y is a power-of-two, we can replace this with a bit test:
1150/// icmp eq/ne (and %x, (add %y, -1)), 0
1151Instruction *InstCombinerImpl::foldIRemByPowerOfTwoToBitTest(ICmpInst &I) {
1152 // This fold is only valid for equality predicates.
1153 if (!I.isEquality())
1154 return nullptr;
1155 CmpPredicate Pred;
1156 Value *X, *Y, *Zero;
1157 if (!match(V: &I, P: m_ICmp(Pred, L: m_OneUse(SubPattern: m_IRem(L: m_Value(V&: X), R: m_Value(V&: Y))),
1158 R: m_CombineAnd(L: m_Zero(), R: m_Value(V&: Zero)))))
1159 return nullptr;
1160 if (!isKnownToBeAPowerOfTwo(V: Y, /*OrZero*/ true, CxtI: &I))
1161 return nullptr;
1162 // This may increase instruction count, we don't enforce that Y is a constant.
1163 Value *Mask = Builder.CreateAdd(LHS: Y, RHS: Constant::getAllOnesValue(Ty: Y->getType()));
1164 Value *Masked = Builder.CreateAnd(LHS: X, RHS: Mask);
1165 return ICmpInst::Create(Op: Instruction::ICmp, Pred, S1: Masked, S2: Zero);
1166}
1167
1168/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1169/// by one-less-than-bitwidth into a sign test on the original value.
1170Instruction *InstCombinerImpl::foldSignBitTest(ICmpInst &I) {
1171 Instruction *Val;
1172 CmpPredicate Pred;
1173 if (!I.isEquality() || !match(V: &I, P: m_ICmp(Pred, L: m_Instruction(I&: Val), R: m_Zero())))
1174 return nullptr;
1175
1176 Value *X;
1177 Type *XTy;
1178
1179 Constant *C;
1180 if (match(V: Val, P: m_TruncOrSelf(Op: m_Shr(L: m_Value(V&: X), R: m_Constant(C))))) {
1181 XTy = X->getType();
1182 unsigned XBitWidth = XTy->getScalarSizeInBits();
1183 if (!match(V: C, P: m_SpecificInt_ICMP(Predicate: ICmpInst::Predicate::ICMP_EQ,
1184 Threshold: APInt(XBitWidth, XBitWidth - 1))))
1185 return nullptr;
1186 } else if (isa<BinaryOperator>(Val) &&
1187 (X = reassociateShiftAmtsOfTwoSameDirectionShifts(
1188 Sh0: cast<BinaryOperator>(Val), SQ: SQ.getWithInstruction(I: Val),
1189 /*AnalyzeForSignBitExtraction=*/true))) {
1190 XTy = X->getType();
1191 } else
1192 return nullptr;
1193
1194 return ICmpInst::Create(Op: Instruction::ICmp,
1195 Pred: Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SGE
1196 : ICmpInst::ICMP_SLT,
1197 S1: X, S2: ConstantInt::getNullValue(Ty: XTy));
1198}
1199
1200// Handle icmp pred X, 0
1201Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) {
1202 CmpInst::Predicate Pred = Cmp.getPredicate();
1203 if (!match(V: Cmp.getOperand(i_nocapture: 1), P: m_Zero()))
1204 return nullptr;
1205
1206 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1207 if (Pred == ICmpInst::ICMP_SGT) {
1208 Value *A, *B;
1209 if (match(V: Cmp.getOperand(i_nocapture: 0), P: m_SMin(L: m_Value(V&: A), R: m_Value(V&: B)))) {
1210 if (isKnownPositive(V: A, SQ: SQ.getWithInstruction(I: &Cmp)))
1211 return new ICmpInst(Pred, B, Cmp.getOperand(i_nocapture: 1));
1212 if (isKnownPositive(V: B, SQ: SQ.getWithInstruction(I: &Cmp)))
1213 return new ICmpInst(Pred, A, Cmp.getOperand(i_nocapture: 1));
1214 }
1215 }
1216
1217 if (Instruction *New = foldIRemByPowerOfTwoToBitTest(I&: Cmp))
1218 return New;
1219
1220 // Given:
1221 // icmp eq/ne (urem %x, %y), 0
1222 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1223 // icmp eq/ne %x, 0
1224 Value *X, *Y;
1225 if (match(V: Cmp.getOperand(i_nocapture: 0), P: m_URem(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
1226 ICmpInst::isEquality(P: Pred)) {
1227 KnownBits XKnown = computeKnownBits(V: X, CxtI: &Cmp);
1228 KnownBits YKnown = computeKnownBits(V: Y, CxtI: &Cmp);
1229 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1230 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
1231 }
1232
1233 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1234 // odd/non-zero/there is no overflow.
1235 if (match(V: Cmp.getOperand(i_nocapture: 0), P: m_Mul(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
1236 ICmpInst::isEquality(P: Pred)) {
1237
1238 KnownBits XKnown = computeKnownBits(V: X, CxtI: &Cmp);
1239 // if X % 2 != 0
1240 // (icmp eq/ne Y)
1241 if (XKnown.countMaxTrailingZeros() == 0)
1242 return new ICmpInst(Pred, Y, Cmp.getOperand(i_nocapture: 1));
1243
1244 KnownBits YKnown = computeKnownBits(V: Y, CxtI: &Cmp);
1245 // if Y % 2 != 0
1246 // (icmp eq/ne X)
1247 if (YKnown.countMaxTrailingZeros() == 0)
1248 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
1249
1250 auto *BO0 = cast<OverflowingBinaryOperator>(Val: Cmp.getOperand(i_nocapture: 0));
1251 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1252 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
1253 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1254 // but to avoid unnecessary work, first just if this is an obvious case.
1255
1256 // if X non-zero and NoOverflow(X * Y)
1257 // (icmp eq/ne Y)
1258 if (!XKnown.One.isZero() || isKnownNonZero(V: X, Q))
1259 return new ICmpInst(Pred, Y, Cmp.getOperand(i_nocapture: 1));
1260
1261 // if Y non-zero and NoOverflow(X * Y)
1262 // (icmp eq/ne X)
1263 if (!YKnown.One.isZero() || isKnownNonZero(V: Y, Q))
1264 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
1265 }
1266 // Note, we are skipping cases:
1267 // if Y % 2 != 0 AND X % 2 != 0
1268 // (false/true)
1269 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1270 // (false/true)
1271 // Those can be simplified later as we would have already replaced the (icmp
1272 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1273 // will fold to a constant elsewhere.
1274 }
1275
1276 // (icmp eq/ne f(X), 0) -> (icmp eq/ne X, 0)
1277 // where f(X) == 0 if and only if X == 0
1278 if (ICmpInst::isEquality(P: Pred))
1279 if (Value *Stripped = stripNullTest(V: Cmp.getOperand(i_nocapture: 0)))
1280 return new ICmpInst(Pred, Stripped,
1281 Constant::getNullValue(Ty: Stripped->getType()));
1282
1283 return nullptr;
1284}
1285
1286/// Fold icmp eq (num + mask) & ~mask, num
1287/// to
1288/// icmp eq (and num, mask), 0
1289/// Where mask is a low bit mask.
1290Instruction *InstCombinerImpl::foldIsMultipleOfAPowerOfTwo(ICmpInst &Cmp) {
1291 Value *Num;
1292 CmpPredicate Pred;
1293 const APInt *Mask, *Neg;
1294
1295 if (!match(V: &Cmp,
1296 P: m_c_ICmp(Pred, L: m_Value(V&: Num),
1297 R: m_OneUse(SubPattern: m_c_And(L: m_OneUse(SubPattern: m_c_Add(L: m_Deferred(V: Num),
1298 R: m_LowBitMask(V&: Mask))),
1299 R: m_APInt(Res&: Neg))))))
1300 return nullptr;
1301
1302 if (*Neg != ~*Mask)
1303 return nullptr;
1304
1305 if (!ICmpInst::isEquality(P: Pred))
1306 return nullptr;
1307
1308 // Create new icmp eq (num & mask), 0
1309 auto *NewAnd = Builder.CreateAnd(LHS: Num, RHS: *Mask);
1310 auto *Zero = Constant::getNullValue(Ty: Num->getType());
1311
1312 return new ICmpInst(Pred, NewAnd, Zero);
1313}
1314
1315/// Fold icmp Pred X, C.
1316/// TODO: This code structure does not make sense. The saturating add fold
1317/// should be moved to some other helper and extended as noted below (it is also
1318/// possible that code has been made unnecessary - do we canonicalize IR to
1319/// overflow/saturating intrinsics or not?).
1320Instruction *InstCombinerImpl::foldICmpWithConstant(ICmpInst &Cmp) {
1321 // Match the following pattern, which is a common idiom when writing
1322 // overflow-safe integer arithmetic functions. The source performs an addition
1323 // in wider type and explicitly checks for overflow using comparisons against
1324 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1325 //
1326 // TODO: This could probably be generalized to handle other overflow-safe
1327 // operations if we worked out the formulas to compute the appropriate magic
1328 // constants.
1329 //
1330 // sum = a + b
1331 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1332 CmpInst::Predicate Pred = Cmp.getPredicate();
1333 Value *Op0 = Cmp.getOperand(i_nocapture: 0), *Op1 = Cmp.getOperand(i_nocapture: 1);
1334 Value *A, *B;
1335 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1336 if (Pred == ICmpInst::ICMP_UGT && match(V: Op1, P: m_ConstantInt(CI)) &&
1337 match(V: Op0, P: m_Add(L: m_Add(L: m_Value(V&: A), R: m_Value(V&: B)), R: m_ConstantInt(CI&: CI2))))
1338 if (Instruction *Res = processUGT_ADDCST_ADD(I&: Cmp, A, B, CI2, CI1: CI, IC&: *this))
1339 return Res;
1340
1341 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1342 Constant *C = dyn_cast<Constant>(Val: Op1);
1343 if (!C)
1344 return nullptr;
1345
1346 if (auto *Phi = dyn_cast<PHINode>(Val: Op0))
1347 if (all_of(Range: Phi->operands(), P: IsaPred<Constant>)) {
1348 SmallVector<Constant *> Ops;
1349 for (Value *V : Phi->incoming_values()) {
1350 Constant *Res =
1351 ConstantFoldCompareInstOperands(Predicate: Pred, LHS: cast<Constant>(Val: V), RHS: C, DL);
1352 if (!Res)
1353 return nullptr;
1354 Ops.push_back(Elt: Res);
1355 }
1356 Builder.SetInsertPoint(Phi);
1357 PHINode *NewPhi = Builder.CreatePHI(Ty: Cmp.getType(), NumReservedValues: Phi->getNumOperands());
1358 for (auto [V, Pred] : zip(t&: Ops, u: Phi->blocks()))
1359 NewPhi->addIncoming(V, BB: Pred);
1360 return replaceInstUsesWith(I&: Cmp, V: NewPhi);
1361 }
1362
1363 if (Instruction *R = tryFoldInstWithCtpopWithNot(I: &Cmp))
1364 return R;
1365
1366 return nullptr;
1367}
1368
1369/// Canonicalize icmp instructions based on dominating conditions.
1370Instruction *InstCombinerImpl::foldICmpWithDominatingICmp(ICmpInst &Cmp) {
1371 // We already checked simple implication in InstSimplify, only handle complex
1372 // cases here.
1373 Value *X = Cmp.getOperand(i_nocapture: 0), *Y = Cmp.getOperand(i_nocapture: 1);
1374 const APInt *C;
1375 if (!match(V: Y, P: m_APInt(Res&: C)))
1376 return nullptr;
1377
1378 CmpInst::Predicate Pred = Cmp.getPredicate();
1379 ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, Other: *C);
1380
1381 auto handleDomCond = [&](ICmpInst::Predicate DomPred,
1382 const APInt *DomC) -> Instruction * {
1383 // We have 2 compares of a variable with constants. Calculate the constant
1384 // ranges of those compares to see if we can transform the 2nd compare:
1385 // DomBB:
1386 // DomCond = icmp DomPred X, DomC
1387 // br DomCond, CmpBB, FalseBB
1388 // CmpBB:
1389 // Cmp = icmp Pred X, C
1390 ConstantRange DominatingCR =
1391 ConstantRange::makeExactICmpRegion(Pred: DomPred, Other: *DomC);
1392 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1393 ConstantRange Difference = DominatingCR.difference(CR);
1394 if (Intersection.isEmptySet())
1395 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
1396 if (Difference.isEmptySet())
1397 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
1398
1399 // Canonicalizing a sign bit comparison that gets used in a branch,
1400 // pessimizes codegen by generating branch on zero instruction instead
1401 // of a test and branch. So we avoid canonicalizing in such situations
1402 // because test and branch instruction has better branch displacement
1403 // than compare and branch instruction.
1404 bool UnusedBit;
1405 bool IsSignBit = isSignBitCheck(Pred, RHS: *C, TrueIfSigned&: UnusedBit);
1406 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(I&: Cmp)))
1407 return nullptr;
1408
1409 // Avoid an infinite loop with min/max canonicalization.
1410 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1411 if (Cmp.hasOneUse() &&
1412 match(V: Cmp.user_back(), P: m_MaxOrMin(L: m_Value(), R: m_Value())))
1413 return nullptr;
1414
1415 if (const APInt *EqC = Intersection.getSingleElement())
1416 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(AI: *EqC));
1417 if (const APInt *NeC = Difference.getSingleElement())
1418 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(AI: *NeC));
1419 return nullptr;
1420 };
1421
1422 for (BranchInst *BI : DC.conditionsFor(V: X)) {
1423 CmpPredicate DomPred;
1424 const APInt *DomC;
1425 if (!match(V: BI->getCondition(),
1426 P: m_ICmp(Pred&: DomPred, L: m_Specific(V: X), R: m_APInt(Res&: DomC))))
1427 continue;
1428
1429 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(i: 0));
1430 if (DT.dominates(BBE: Edge0, BB: Cmp.getParent())) {
1431 if (auto *V = handleDomCond(DomPred, DomC))
1432 return V;
1433 } else {
1434 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(i: 1));
1435 if (DT.dominates(BBE: Edge1, BB: Cmp.getParent()))
1436 if (auto *V =
1437 handleDomCond(CmpInst::getInversePredicate(pred: DomPred), DomC))
1438 return V;
1439 }
1440 }
1441
1442 return nullptr;
1443}
1444
1445/// Fold icmp (trunc X), C.
1446Instruction *InstCombinerImpl::foldICmpTruncConstant(ICmpInst &Cmp,
1447 TruncInst *Trunc,
1448 const APInt &C) {
1449 ICmpInst::Predicate Pred = Cmp.getPredicate();
1450 Value *X = Trunc->getOperand(i_nocapture: 0);
1451 Type *SrcTy = X->getType();
1452 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1453 SrcBits = SrcTy->getScalarSizeInBits();
1454
1455 // Match (icmp pred (trunc nuw/nsw X), C)
1456 // Which we can convert to (icmp pred X, (sext/zext C))
1457 if (shouldChangeType(From: Trunc->getType(), To: SrcTy)) {
1458 if (Trunc->hasNoSignedWrap())
1459 return new ICmpInst(Pred, X, ConstantInt::get(Ty: SrcTy, V: C.sext(width: SrcBits)));
1460 if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())
1461 return new ICmpInst(Pred, X, ConstantInt::get(Ty: SrcTy, V: C.zext(width: SrcBits)));
1462 }
1463
1464 if (C.isOne() && C.getBitWidth() > 1) {
1465 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1466 Value *V = nullptr;
1467 if (Pred == ICmpInst::ICMP_SLT && match(V: X, P: m_Signum(V: m_Value(V))))
1468 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1469 ConstantInt::get(Ty: V->getType(), V: 1));
1470 }
1471
1472 // TODO: Handle non-equality predicates.
1473 Value *Y;
1474 const APInt *Pow2;
1475 if (Cmp.isEquality() && match(V: X, P: m_Shl(L: m_Power2(V&: Pow2), R: m_Value(V&: Y))) &&
1476 DstBits > Pow2->logBase2()) {
1477 // (trunc (Pow2 << Y) to iN) == 0 --> Y u>= N - log2(Pow2)
1478 // (trunc (Pow2 << Y) to iN) != 0 --> Y u< N - log2(Pow2)
1479 // iff N > log2(Pow2)
1480 if (C.isZero()) {
1481 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1482 return new ICmpInst(NewPred, Y,
1483 ConstantInt::get(Ty: SrcTy, V: DstBits - Pow2->logBase2()));
1484 }
1485 // (trunc (Pow2 << Y) to iN) == 2**C --> Y == C - log2(Pow2)
1486 // (trunc (Pow2 << Y) to iN) != 2**C --> Y != C - log2(Pow2)
1487 if (C.isPowerOf2())
1488 return new ICmpInst(
1489 Pred, Y, ConstantInt::get(Ty: SrcTy, V: C.logBase2() - Pow2->logBase2()));
1490 }
1491
1492 if (Cmp.isEquality() && (Trunc->hasOneUse() || Trunc->hasNoUnsignedWrap())) {
1493 // Canonicalize to a mask and wider compare if the wide type is suitable:
1494 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1495 if (!SrcTy->isVectorTy() && shouldChangeType(FromBitWidth: DstBits, ToBitWidth: SrcBits)) {
1496 Constant *Mask =
1497 ConstantInt::get(Ty: SrcTy, V: APInt::getLowBitsSet(numBits: SrcBits, loBitsSet: DstBits));
1498 Value *And = Trunc->hasNoUnsignedWrap() ? X : Builder.CreateAnd(LHS: X, RHS: Mask);
1499 Constant *WideC = ConstantInt::get(Ty: SrcTy, V: C.zext(width: SrcBits));
1500 return new ICmpInst(Pred, And, WideC);
1501 }
1502
1503 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1504 // of the high bits truncated out of x are known.
1505 KnownBits Known = computeKnownBits(V: X, CxtI: &Cmp);
1506
1507 // If all the high bits are known, we can do this xform.
1508 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1509 // Pull in the high bits from known-ones set.
1510 APInt NewRHS = C.zext(width: SrcBits);
1511 NewRHS |= Known.One & APInt::getHighBitsSet(numBits: SrcBits, hiBitsSet: SrcBits - DstBits);
1512 return new ICmpInst(Pred, X, ConstantInt::get(Ty: SrcTy, V: NewRHS));
1513 }
1514 }
1515
1516 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1517 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1518 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1519 Value *ShOp;
1520 uint64_t ShAmt;
1521 bool TrueIfSigned;
1522 if (isSignBitCheck(Pred, RHS: C, TrueIfSigned) &&
1523 match(V: X, P: m_Shr(L: m_Value(V&: ShOp), R: m_ConstantInt(V&: ShAmt))) &&
1524 DstBits == SrcBits - ShAmt) {
1525 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1526 ConstantInt::getNullValue(Ty: SrcTy))
1527 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1528 ConstantInt::getAllOnesValue(Ty: SrcTy));
1529 }
1530
1531 return nullptr;
1532}
1533
1534/// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
1535/// Fold icmp (trunc nuw/nsw X), (zext/sext Y).
1536Instruction *
1537InstCombinerImpl::foldICmpTruncWithTruncOrExt(ICmpInst &Cmp,
1538 const SimplifyQuery &Q) {
1539 Value *X, *Y;
1540 CmpPredicate Pred;
1541 bool YIsSExt = false;
1542 // Try to match icmp (trunc X), (trunc Y)
1543 if (match(V: &Cmp, P: m_ICmp(Pred, L: m_Trunc(Op: m_Value(V&: X)), R: m_Trunc(Op: m_Value(V&: Y))))) {
1544 unsigned NoWrapFlags = cast<TruncInst>(Val: Cmp.getOperand(i_nocapture: 0))->getNoWrapKind() &
1545 cast<TruncInst>(Val: Cmp.getOperand(i_nocapture: 1))->getNoWrapKind();
1546 if (Cmp.isSigned()) {
1547 // For signed comparisons, both truncs must be nsw.
1548 if (!(NoWrapFlags & TruncInst::NoSignedWrap))
1549 return nullptr;
1550 } else {
1551 // For unsigned and equality comparisons, either both must be nuw or
1552 // both must be nsw, we don't care which.
1553 if (!NoWrapFlags)
1554 return nullptr;
1555 }
1556
1557 if (X->getType() != Y->getType() &&
1558 (!Cmp.getOperand(i_nocapture: 0)->hasOneUse() || !Cmp.getOperand(i_nocapture: 1)->hasOneUse()))
1559 return nullptr;
1560 if (!isDesirableIntType(BitWidth: X->getType()->getScalarSizeInBits()) &&
1561 isDesirableIntType(BitWidth: Y->getType()->getScalarSizeInBits())) {
1562 std::swap(a&: X, b&: Y);
1563 Pred = Cmp.getSwappedPredicate(pred: Pred);
1564 }
1565 YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);
1566 }
1567 // Try to match icmp (trunc nuw X), (zext Y)
1568 else if (!Cmp.isSigned() &&
1569 match(V: &Cmp, P: m_c_ICmp(Pred, L: m_NUWTrunc(Op: m_Value(V&: X)),
1570 R: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: Y)))))) {
1571 // Can fold trunc nuw + zext for unsigned and equality predicates.
1572 }
1573 // Try to match icmp (trunc nsw X), (sext Y)
1574 else if (match(V: &Cmp, P: m_c_ICmp(Pred, L: m_NSWTrunc(Op: m_Value(V&: X)),
1575 R: m_OneUse(SubPattern: m_ZExtOrSExt(Op: m_Value(V&: Y)))))) {
1576 // Can fold trunc nsw + zext/sext for all predicates.
1577 YIsSExt =
1578 isa<SExtInst>(Val: Cmp.getOperand(i_nocapture: 0)) || isa<SExtInst>(Val: Cmp.getOperand(i_nocapture: 1));
1579 } else
1580 return nullptr;
1581
1582 Type *TruncTy = Cmp.getOperand(i_nocapture: 0)->getType();
1583 unsigned TruncBits = TruncTy->getScalarSizeInBits();
1584
1585 // If this transform will end up changing from desirable types -> undesirable
1586 // types skip it.
1587 if (isDesirableIntType(BitWidth: TruncBits) &&
1588 !isDesirableIntType(BitWidth: X->getType()->getScalarSizeInBits()))
1589 return nullptr;
1590
1591 Value *NewY = Builder.CreateIntCast(V: Y, DestTy: X->getType(), isSigned: YIsSExt);
1592 return new ICmpInst(Pred, X, NewY);
1593}
1594
1595/// Fold icmp (xor X, Y), C.
1596Instruction *InstCombinerImpl::foldICmpXorConstant(ICmpInst &Cmp,
1597 BinaryOperator *Xor,
1598 const APInt &C) {
1599 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1600 return I;
1601
1602 Value *X = Xor->getOperand(i_nocapture: 0);
1603 Value *Y = Xor->getOperand(i_nocapture: 1);
1604 const APInt *XorC;
1605 if (!match(V: Y, P: m_APInt(Res&: XorC)))
1606 return nullptr;
1607
1608 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1609 // fold the xor.
1610 ICmpInst::Predicate Pred = Cmp.getPredicate();
1611 bool TrueIfSigned = false;
1612 if (isSignBitCheck(Pred: Cmp.getPredicate(), RHS: C, TrueIfSigned)) {
1613
1614 // If the sign bit of the XorCst is not set, there is no change to
1615 // the operation, just stop using the Xor.
1616 if (!XorC->isNegative())
1617 return replaceOperand(I&: Cmp, OpNum: 0, V: X);
1618
1619 // Emit the opposite comparison.
1620 if (TrueIfSigned)
1621 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1622 ConstantInt::getAllOnesValue(Ty: X->getType()));
1623 else
1624 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1625 ConstantInt::getNullValue(Ty: X->getType()));
1626 }
1627
1628 if (Xor->hasOneUse()) {
1629 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1630 if (!Cmp.isEquality() && XorC->isSignMask()) {
1631 Pred = Cmp.getFlippedSignednessPredicate();
1632 return new ICmpInst(Pred, X, ConstantInt::get(Ty: X->getType(), V: C ^ *XorC));
1633 }
1634
1635 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1636 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1637 Pred = Cmp.getFlippedSignednessPredicate();
1638 Pred = Cmp.getSwappedPredicate(pred: Pred);
1639 return new ICmpInst(Pred, X, ConstantInt::get(Ty: X->getType(), V: C ^ *XorC));
1640 }
1641 }
1642
1643 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1644 if (Pred == ICmpInst::ICMP_UGT) {
1645 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1646 if (*XorC == ~C && (C + 1).isPowerOf2())
1647 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1648 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1649 if (*XorC == C && (C + 1).isPowerOf2())
1650 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1651 }
1652 if (Pred == ICmpInst::ICMP_ULT) {
1653 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1654 if (*XorC == -C && C.isPowerOf2())
1655 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1656 ConstantInt::get(Ty: X->getType(), V: ~C));
1657 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1658 if (*XorC == C && (-C).isPowerOf2())
1659 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1660 ConstantInt::get(Ty: X->getType(), V: ~C));
1661 }
1662 return nullptr;
1663}
1664
1665/// For power-of-2 C:
1666/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1667/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1668Instruction *InstCombinerImpl::foldICmpXorShiftConst(ICmpInst &Cmp,
1669 BinaryOperator *Xor,
1670 const APInt &C) {
1671 CmpInst::Predicate Pred = Cmp.getPredicate();
1672 APInt PowerOf2;
1673 if (Pred == ICmpInst::ICMP_ULT)
1674 PowerOf2 = C;
1675 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1676 PowerOf2 = C + 1;
1677 else
1678 return nullptr;
1679 if (!PowerOf2.isPowerOf2())
1680 return nullptr;
1681 Value *X;
1682 const APInt *ShiftC;
1683 if (!match(V: Xor, P: m_OneUse(SubPattern: m_c_Xor(L: m_Value(V&: X),
1684 R: m_AShr(L: m_Deferred(V: X), R: m_APInt(Res&: ShiftC))))))
1685 return nullptr;
1686 uint64_t Shift = ShiftC->getLimitedValue();
1687 Type *XType = X->getType();
1688 if (Shift == 0 || PowerOf2.isMinSignedValue())
1689 return nullptr;
1690 Value *Add = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty: XType, V: PowerOf2));
1691 APInt Bound =
1692 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1693 return new ICmpInst(Pred, Add, ConstantInt::get(Ty: XType, V: Bound));
1694}
1695
1696/// Fold icmp (and (sh X, Y), C2), C1.
1697Instruction *InstCombinerImpl::foldICmpAndShift(ICmpInst &Cmp,
1698 BinaryOperator *And,
1699 const APInt &C1,
1700 const APInt &C2) {
1701 BinaryOperator *Shift = dyn_cast<BinaryOperator>(Val: And->getOperand(i_nocapture: 0));
1702 if (!Shift || !Shift->isShift())
1703 return nullptr;
1704
1705 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1706 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1707 // code produced by the clang front-end, for bitfield access.
1708 // This seemingly simple opportunity to fold away a shift turns out to be
1709 // rather complicated. See PR17827 for details.
1710 unsigned ShiftOpcode = Shift->getOpcode();
1711 bool IsShl = ShiftOpcode == Instruction::Shl;
1712 const APInt *C3;
1713 if (match(V: Shift->getOperand(i_nocapture: 1), P: m_APInt(Res&: C3))) {
1714 APInt NewAndCst, NewCmpCst;
1715 bool AnyCmpCstBitsShiftedOut;
1716 if (ShiftOpcode == Instruction::Shl) {
1717 // For a left shift, we can fold if the comparison is not signed. We can
1718 // also fold a signed comparison if the mask value and comparison value
1719 // are not negative. These constraints may not be obvious, but we can
1720 // prove that they are correct using an SMT solver.
1721 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1722 return nullptr;
1723
1724 NewCmpCst = C1.lshr(ShiftAmt: *C3);
1725 NewAndCst = C2.lshr(ShiftAmt: *C3);
1726 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(ShiftAmt: *C3) != C1;
1727 } else if (ShiftOpcode == Instruction::LShr) {
1728 // For a logical right shift, we can fold if the comparison is not signed.
1729 // We can also fold a signed comparison if the shifted mask value and the
1730 // shifted comparison value are not negative. These constraints may not be
1731 // obvious, but we can prove that they are correct using an SMT solver.
1732 NewCmpCst = C1.shl(ShiftAmt: *C3);
1733 NewAndCst = C2.shl(ShiftAmt: *C3);
1734 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(ShiftAmt: *C3) != C1;
1735 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1736 return nullptr;
1737 } else {
1738 // For an arithmetic shift, check that both constants don't use (in a
1739 // signed sense) the top bits being shifted out.
1740 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1741 NewCmpCst = C1.shl(ShiftAmt: *C3);
1742 NewAndCst = C2.shl(ShiftAmt: *C3);
1743 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(ShiftAmt: *C3) != C1;
1744 if (NewAndCst.ashr(ShiftAmt: *C3) != C2)
1745 return nullptr;
1746 }
1747
1748 if (AnyCmpCstBitsShiftedOut) {
1749 // If we shifted bits out, the fold is not going to work out. As a
1750 // special case, check to see if this means that the result is always
1751 // true or false now.
1752 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1753 return replaceInstUsesWith(I&: Cmp, V: ConstantInt::getFalse(Ty: Cmp.getType()));
1754 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1755 return replaceInstUsesWith(I&: Cmp, V: ConstantInt::getTrue(Ty: Cmp.getType()));
1756 } else {
1757 Value *NewAnd = Builder.CreateAnd(
1758 LHS: Shift->getOperand(i_nocapture: 0), RHS: ConstantInt::get(Ty: And->getType(), V: NewAndCst));
1759 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1760 ConstantInt::get(Ty: And->getType(), V: NewCmpCst));
1761 }
1762 }
1763
1764 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1765 // preferable because it allows the C2 << Y expression to be hoisted out of a
1766 // loop if Y is invariant and X is not.
1767 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1768 !Shift->isArithmeticShift() &&
1769 ((!IsShl && C2.isOne()) || !isa<Constant>(Val: Shift->getOperand(i_nocapture: 0)))) {
1770 // Compute C2 << Y.
1771 Value *NewShift =
1772 IsShl ? Builder.CreateLShr(LHS: And->getOperand(i_nocapture: 1), RHS: Shift->getOperand(i_nocapture: 1))
1773 : Builder.CreateShl(LHS: And->getOperand(i_nocapture: 1), RHS: Shift->getOperand(i_nocapture: 1));
1774
1775 // Compute X & (C2 << Y).
1776 Value *NewAnd = Builder.CreateAnd(LHS: Shift->getOperand(i_nocapture: 0), RHS: NewShift);
1777 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(i_nocapture: 1));
1778 }
1779
1780 return nullptr;
1781}
1782
1783/// Fold icmp (and X, C2), C1.
1784Instruction *InstCombinerImpl::foldICmpAndConstConst(ICmpInst &Cmp,
1785 BinaryOperator *And,
1786 const APInt &C1) {
1787 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1788
1789 // icmp ne (and X, 1), 0 --> trunc X to i1
1790 if (isICMP_NE && C1.isZero() && match(V: And->getOperand(i_nocapture: 1), P: m_One()))
1791 return new TruncInst(And->getOperand(i_nocapture: 0), Cmp.getType());
1792
1793 const APInt *C2;
1794 Value *X;
1795 if (!match(V: And, P: m_And(L: m_Value(V&: X), R: m_APInt(Res&: C2))))
1796 return nullptr;
1797
1798 // (and X, highmask) s> [0, ~highmask] --> X s> ~highmask
1799 if (Cmp.getPredicate() == ICmpInst::ICMP_SGT && C1.ule(RHS: ~*C2) &&
1800 C2->isNegatedPowerOf2())
1801 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1802 ConstantInt::get(Ty: X->getType(), V: ~*C2));
1803 // (and X, highmask) s< [1, -highmask] --> X s< -highmask
1804 if (Cmp.getPredicate() == ICmpInst::ICMP_SLT && !C1.isSignMask() &&
1805 (C1 - 1).ule(RHS: ~*C2) && C2->isNegatedPowerOf2() && !C2->isSignMask())
1806 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1807 ConstantInt::get(Ty: X->getType(), V: -*C2));
1808
1809 // Don't perform the following transforms if the AND has multiple uses
1810 if (!And->hasOneUse())
1811 return nullptr;
1812
1813 if (Cmp.isEquality() && C1.isZero()) {
1814 // Restrict this fold to single-use 'and' (PR10267).
1815 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1816 if (C2->isSignMask()) {
1817 Constant *Zero = Constant::getNullValue(Ty: X->getType());
1818 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1819 return new ICmpInst(NewPred, X, Zero);
1820 }
1821
1822 APInt NewC2 = *C2;
1823 KnownBits Know = computeKnownBits(V: And->getOperand(i_nocapture: 0), CxtI: And);
1824 // Set high zeros of C2 to allow matching negated power-of-2.
1825 NewC2 = *C2 | APInt::getHighBitsSet(numBits: C2->getBitWidth(),
1826 hiBitsSet: Know.countMinLeadingZeros());
1827
1828 // Restrict this fold only for single-use 'and' (PR10267).
1829 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1830 if (NewC2.isNegatedPowerOf2()) {
1831 Constant *NegBOC = ConstantInt::get(Ty: And->getType(), V: -NewC2);
1832 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1833 return new ICmpInst(NewPred, X, NegBOC);
1834 }
1835 }
1836
1837 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1838 // the input width without changing the value produced, eliminate the cast:
1839 //
1840 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1841 //
1842 // We can do this transformation if the constants do not have their sign bits
1843 // set or if it is an equality comparison. Extending a relational comparison
1844 // when we're checking the sign bit would not work.
1845 Value *W;
1846 if (match(V: And->getOperand(i_nocapture: 0), P: m_OneUse(SubPattern: m_Trunc(Op: m_Value(V&: W)))) &&
1847 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1848 // TODO: Is this a good transform for vectors? Wider types may reduce
1849 // throughput. Should this transform be limited (even for scalars) by using
1850 // shouldChangeType()?
1851 if (!Cmp.getType()->isVectorTy()) {
1852 Type *WideType = W->getType();
1853 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1854 Constant *ZextC1 = ConstantInt::get(Ty: WideType, V: C1.zext(width: WideScalarBits));
1855 Constant *ZextC2 = ConstantInt::get(Ty: WideType, V: C2->zext(width: WideScalarBits));
1856 Value *NewAnd = Builder.CreateAnd(LHS: W, RHS: ZextC2, Name: And->getName());
1857 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1858 }
1859 }
1860
1861 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, C2: *C2))
1862 return I;
1863
1864 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1865 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1866 //
1867 // iff pred isn't signed
1868 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(i_nocapture: 0)->hasOneUse() &&
1869 match(V: And->getOperand(i_nocapture: 1), P: m_One())) {
1870 Constant *One = cast<Constant>(Val: And->getOperand(i_nocapture: 1));
1871 Value *Or = And->getOperand(i_nocapture: 0);
1872 Value *A, *B, *LShr;
1873 if (match(V: Or, P: m_Or(L: m_Value(V&: LShr), R: m_Value(V&: A))) &&
1874 match(V: LShr, P: m_LShr(L: m_Specific(V: A), R: m_Value(V&: B)))) {
1875 unsigned UsesRemoved = 0;
1876 if (And->hasOneUse())
1877 ++UsesRemoved;
1878 if (Or->hasOneUse())
1879 ++UsesRemoved;
1880 if (LShr->hasOneUse())
1881 ++UsesRemoved;
1882
1883 // Compute A & ((1 << B) | 1)
1884 unsigned RequireUsesRemoved = match(V: B, P: m_ImmConstant()) ? 1 : 3;
1885 if (UsesRemoved >= RequireUsesRemoved) {
1886 Value *NewOr =
1887 Builder.CreateOr(LHS: Builder.CreateShl(LHS: One, RHS: B, Name: LShr->getName(),
1888 /*HasNUW=*/true),
1889 RHS: One, Name: Or->getName());
1890 Value *NewAnd = Builder.CreateAnd(LHS: A, RHS: NewOr, Name: And->getName());
1891 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(i_nocapture: 1));
1892 }
1893 }
1894 }
1895
1896 // (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->
1897 // llvm.is.fpclass(X, fcInf|fcNan)
1898 // (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->
1899 // llvm.is.fpclass(X, ~(fcInf|fcNan))
1900 // (icmp eq (and (bitcast X to int), ExponentMask), 0) -->
1901 // llvm.is.fpclass(X, fcSubnormal|fcZero)
1902 // (icmp ne (and (bitcast X to int), ExponentMask), 0) -->
1903 // llvm.is.fpclass(X, ~(fcSubnormal|fcZero))
1904 Value *V;
1905 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1906 Kind: Attribute::NoImplicitFloat) &&
1907 Cmp.isEquality() &&
1908 match(V: X, P: m_OneUse(SubPattern: m_ElementWiseBitCast(Op: m_Value(V))))) {
1909 Type *FPType = V->getType()->getScalarType();
1910 if (FPType->isIEEELikeFPTy() && (C1.isZero() || C1 == *C2)) {
1911 APInt ExponentMask =
1912 APFloat::getInf(Sem: FPType->getFltSemantics()).bitcastToAPInt();
1913 if (*C2 == ExponentMask) {
1914 unsigned Mask = C1.isZero()
1915 ? FPClassTest::fcZero | FPClassTest::fcSubnormal
1916 : FPClassTest::fcNan | FPClassTest::fcInf;
1917 if (isICMP_NE)
1918 Mask = ~Mask & fcAllFlags;
1919 return replaceInstUsesWith(I&: Cmp, V: Builder.createIsFPClass(FPNum: V, Test: Mask));
1920 }
1921 }
1922 }
1923
1924 return nullptr;
1925}
1926
1927/// Fold icmp (and X, Y), C.
1928Instruction *InstCombinerImpl::foldICmpAndConstant(ICmpInst &Cmp,
1929 BinaryOperator *And,
1930 const APInt &C) {
1931 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C1: C))
1932 return I;
1933
1934 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1935 bool TrueIfNeg;
1936 if (isSignBitCheck(Pred, RHS: C, TrueIfSigned&: TrueIfNeg)) {
1937 // ((X - 1) & ~X) < 0 --> X == 0
1938 // ((X - 1) & ~X) >= 0 --> X != 0
1939 Value *X;
1940 if (match(V: And->getOperand(i_nocapture: 0), P: m_Add(L: m_Value(V&: X), R: m_AllOnes())) &&
1941 match(V: And->getOperand(i_nocapture: 1), P: m_Not(V: m_Specific(V: X)))) {
1942 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1943 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(Ty: X->getType()));
1944 }
1945 // (X & -X) < 0 --> X == MinSignedC
1946 // (X & -X) > -1 --> X != MinSignedC
1947 if (match(V: And, P: m_c_And(L: m_Neg(V: m_Value(V&: X)), R: m_Deferred(V: X)))) {
1948 Constant *MinSignedC = ConstantInt::get(
1949 Ty: X->getType(),
1950 V: APInt::getSignedMinValue(numBits: X->getType()->getScalarSizeInBits()));
1951 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1952 return new ICmpInst(NewPred, X, MinSignedC);
1953 }
1954 }
1955
1956 // TODO: These all require that Y is constant too, so refactor with the above.
1957
1958 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1959 Value *X = And->getOperand(i_nocapture: 0);
1960 Value *Y = And->getOperand(i_nocapture: 1);
1961 if (auto *C2 = dyn_cast<ConstantInt>(Val: Y))
1962 if (auto *LI = dyn_cast<LoadInst>(Val: X))
1963 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: LI->getOperand(i_nocapture: 0)))
1964 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(LI, GEP, ICI&: Cmp, AndCst: C2))
1965 return Res;
1966
1967 if (!Cmp.isEquality())
1968 return nullptr;
1969
1970 // X & -C == -C -> X > u ~C
1971 // X & -C != -C -> X <= u ~C
1972 // iff C is a power of 2
1973 if (Cmp.getOperand(i_nocapture: 1) == Y && C.isNegatedPowerOf2()) {
1974 auto NewPred =
1975 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT : CmpInst::ICMP_ULE;
1976 return new ICmpInst(NewPred, X, SubOne(C: cast<Constant>(Val: Cmp.getOperand(i_nocapture: 1))));
1977 }
1978
1979 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
1980 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
1981 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
1982 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
1983 if (match(V: And, P: m_OneUse(SubPattern: m_c_And(L: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X))), R: m_Value(V&: Y)))) &&
1984 X->getType()->isIntOrIntVectorTy(BitWidth: 1) && (C.isZero() || C.isOne())) {
1985 Value *TruncY = Builder.CreateTrunc(V: Y, DestTy: X->getType());
1986 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
1987 Value *And = Builder.CreateAnd(LHS: TruncY, RHS: X);
1988 return BinaryOperator::CreateNot(Op: And);
1989 }
1990 return BinaryOperator::CreateAnd(V1: TruncY, V2: X);
1991 }
1992
1993 // (icmp eq/ne (and (shl -1, X), Y), 0)
1994 // -> (icmp eq/ne (lshr Y, X), 0)
1995 // We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems
1996 // highly unlikely the non-zero case will ever show up in code.
1997 if (C.isZero() &&
1998 match(V: And, P: m_OneUse(SubPattern: m_c_And(L: m_OneUse(SubPattern: m_Shl(L: m_AllOnes(), R: m_Value(V&: X))),
1999 R: m_Value(V&: Y))))) {
2000 Value *LShr = Builder.CreateLShr(LHS: Y, RHS: X);
2001 return new ICmpInst(Pred, LShr, Constant::getNullValue(Ty: LShr->getType()));
2002 }
2003
2004 // (icmp eq/ne (and (add A, Addend), Msk), C)
2005 // -> (icmp eq/ne (and A, Msk), (and (sub C, Addend), Msk))
2006 {
2007 Value *A;
2008 const APInt *Addend, *Msk;
2009 if (match(V: And, P: m_OneUse(SubPattern: m_And(L: m_OneUse(SubPattern: m_Add(L: m_Value(V&: A), R: m_APInt(Res&: Addend))),
2010 R: m_LowBitMask(V&: Msk)))) &&
2011 C.ule(RHS: *Msk)) {
2012 APInt NewComperand = (C - *Addend) & *Msk;
2013 Value *MaskA = Builder.CreateAnd(LHS: A, RHS: ConstantInt::get(Ty: A->getType(), V: *Msk));
2014 return new ICmpInst(Pred, MaskA,
2015 ConstantInt::get(Ty: MaskA->getType(), V: NewComperand));
2016 }
2017 }
2018
2019 return nullptr;
2020}
2021
2022/// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
2023static Value *foldICmpOrXorSubChain(ICmpInst &Cmp, BinaryOperator *Or,
2024 InstCombiner::BuilderTy &Builder) {
2025 // Are we using xors or subs to bitwise check for a pair or pairs of
2026 // (in)equalities? Convert to a shorter form that has more potential to be
2027 // folded even further.
2028 // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
2029 // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
2030 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
2031 // (X1 == X2) && (X3 == X4) && (X5 == X6)
2032 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
2033 // (X1 != X2) || (X3 != X4) || (X5 != X6)
2034 SmallVector<std::pair<Value *, Value *>, 2> CmpValues;
2035 SmallVector<Value *, 16> WorkList(1, Or);
2036
2037 while (!WorkList.empty()) {
2038 auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
2039 Value *Lhs, *Rhs;
2040
2041 if (match(V: OrOperatorArgument,
2042 P: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: Lhs), R: m_Value(V&: Rhs))))) {
2043 CmpValues.emplace_back(Args&: Lhs, Args&: Rhs);
2044 return;
2045 }
2046
2047 if (match(V: OrOperatorArgument,
2048 P: m_OneUse(SubPattern: m_Sub(L: m_Value(V&: Lhs), R: m_Value(V&: Rhs))))) {
2049 CmpValues.emplace_back(Args&: Lhs, Args&: Rhs);
2050 return;
2051 }
2052
2053 WorkList.push_back(Elt: OrOperatorArgument);
2054 };
2055
2056 Value *CurrentValue = WorkList.pop_back_val();
2057 Value *OrOperatorLhs, *OrOperatorRhs;
2058
2059 if (!match(V: CurrentValue,
2060 P: m_Or(L: m_Value(V&: OrOperatorLhs), R: m_Value(V&: OrOperatorRhs)))) {
2061 return nullptr;
2062 }
2063
2064 MatchOrOperatorArgument(OrOperatorRhs);
2065 MatchOrOperatorArgument(OrOperatorLhs);
2066 }
2067
2068 ICmpInst::Predicate Pred = Cmp.getPredicate();
2069 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2070 Value *LhsCmp = Builder.CreateICmp(P: Pred, LHS: CmpValues.rbegin()->first,
2071 RHS: CmpValues.rbegin()->second);
2072
2073 for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
2074 Value *RhsCmp = Builder.CreateICmp(P: Pred, LHS: It->first, RHS: It->second);
2075 LhsCmp = Builder.CreateBinOp(Opc: BOpc, LHS: LhsCmp, RHS: RhsCmp);
2076 }
2077
2078 return LhsCmp;
2079}
2080
2081/// Fold icmp (or X, Y), C.
2082Instruction *InstCombinerImpl::foldICmpOrConstant(ICmpInst &Cmp,
2083 BinaryOperator *Or,
2084 const APInt &C) {
2085 ICmpInst::Predicate Pred = Cmp.getPredicate();
2086 if (C.isOne()) {
2087 // icmp slt signum(V) 1 --> icmp slt V, 1
2088 Value *V = nullptr;
2089 if (Pred == ICmpInst::ICMP_SLT && match(V: Or, P: m_Signum(V: m_Value(V))))
2090 return new ICmpInst(ICmpInst::ICMP_SLT, V,
2091 ConstantInt::get(Ty: V->getType(), V: 1));
2092 }
2093
2094 Value *OrOp0 = Or->getOperand(i_nocapture: 0), *OrOp1 = Or->getOperand(i_nocapture: 1);
2095
2096 // (icmp eq/ne (or disjoint x, C0), C1)
2097 // -> (icmp eq/ne x, C0^C1)
2098 if (Cmp.isEquality() && match(V: OrOp1, P: m_ImmConstant()) &&
2099 cast<PossiblyDisjointInst>(Val: Or)->isDisjoint()) {
2100 Value *NewC =
2101 Builder.CreateXor(LHS: OrOp1, RHS: ConstantInt::get(Ty: OrOp1->getType(), V: C));
2102 return new ICmpInst(Pred, OrOp0, NewC);
2103 }
2104
2105 const APInt *MaskC;
2106 if (match(V: OrOp1, P: m_APInt(Res&: MaskC)) && Cmp.isEquality()) {
2107 if (*MaskC == C && (C + 1).isPowerOf2()) {
2108 // X | C == C --> X <=u C
2109 // X | C != C --> X >u C
2110 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
2111 Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT;
2112 return new ICmpInst(Pred, OrOp0, OrOp1);
2113 }
2114
2115 // More general: canonicalize 'equality with set bits mask' to
2116 // 'equality with clear bits mask'.
2117 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2118 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2119 if (Or->hasOneUse()) {
2120 Value *And = Builder.CreateAnd(LHS: OrOp0, RHS: ~(*MaskC));
2121 Constant *NewC = ConstantInt::get(Ty: Or->getType(), V: C ^ (*MaskC));
2122 return new ICmpInst(Pred, And, NewC);
2123 }
2124 }
2125
2126 // (X | (X-1)) s< 0 --> X s< 1
2127 // (X | (X-1)) s> -1 --> X s> 0
2128 Value *X;
2129 bool TrueIfSigned;
2130 if (isSignBitCheck(Pred, RHS: C, TrueIfSigned) &&
2131 match(V: Or, P: m_c_Or(L: m_Add(L: m_Value(V&: X), R: m_AllOnes()), R: m_Deferred(V: X)))) {
2132 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2133 Constant *NewC = ConstantInt::get(Ty: X->getType(), V: TrueIfSigned ? 1 : 0);
2134 return new ICmpInst(NewPred, X, NewC);
2135 }
2136
2137 const APInt *OrC;
2138 // icmp(X | OrC, C) --> icmp(X, 0)
2139 if (C.isNonNegative() && match(V: Or, P: m_Or(L: m_Value(V&: X), R: m_APInt(Res&: OrC)))) {
2140 switch (Pred) {
2141 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2142 case ICmpInst::ICMP_SLT:
2143 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2144 case ICmpInst::ICMP_SGE:
2145 if (OrC->sge(RHS: C))
2146 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: X->getType()));
2147 break;
2148 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2149 case ICmpInst::ICMP_SLE:
2150 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2151 case ICmpInst::ICMP_SGT:
2152 if (OrC->sgt(RHS: C))
2153 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), X,
2154 ConstantInt::getNullValue(Ty: X->getType()));
2155 break;
2156 default:
2157 break;
2158 }
2159 }
2160
2161 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2162 return nullptr;
2163
2164 Value *P, *Q;
2165 if (match(V: Or, P: m_Or(L: m_PtrToInt(Op: m_Value(V&: P)), R: m_PtrToInt(Op: m_Value(V&: Q))))) {
2166 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2167 // -> and (icmp eq P, null), (icmp eq Q, null).
2168 Value *CmpP =
2169 Builder.CreateICmp(P: Pred, LHS: P, RHS: ConstantInt::getNullValue(Ty: P->getType()));
2170 Value *CmpQ =
2171 Builder.CreateICmp(P: Pred, LHS: Q, RHS: ConstantInt::getNullValue(Ty: Q->getType()));
2172 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2173 return BinaryOperator::Create(Op: BOpc, S1: CmpP, S2: CmpQ);
2174 }
2175
2176 if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2177 return replaceInstUsesWith(I&: Cmp, V);
2178
2179 return nullptr;
2180}
2181
2182/// Fold icmp (mul X, Y), C.
2183Instruction *InstCombinerImpl::foldICmpMulConstant(ICmpInst &Cmp,
2184 BinaryOperator *Mul,
2185 const APInt &C) {
2186 ICmpInst::Predicate Pred = Cmp.getPredicate();
2187 Type *MulTy = Mul->getType();
2188 Value *X = Mul->getOperand(i_nocapture: 0);
2189
2190 // If there's no overflow:
2191 // X * X == 0 --> X == 0
2192 // X * X != 0 --> X != 0
2193 if (Cmp.isEquality() && C.isZero() && X == Mul->getOperand(i_nocapture: 1) &&
2194 (Mul->hasNoUnsignedWrap() || Mul->hasNoSignedWrap()))
2195 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: MulTy));
2196
2197 const APInt *MulC;
2198 if (!match(V: Mul->getOperand(i_nocapture: 1), P: m_APInt(Res&: MulC)))
2199 return nullptr;
2200
2201 // If this is a test of the sign bit and the multiply is sign-preserving with
2202 // a constant operand, use the multiply LHS operand instead:
2203 // (X * +MulC) < 0 --> X < 0
2204 // (X * -MulC) < 0 --> X > 0
2205 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2206 if (MulC->isNegative())
2207 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
2208 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: MulTy));
2209 }
2210
2211 if (MulC->isZero())
2212 return nullptr;
2213
2214 // If the multiply does not wrap or the constant is odd, try to divide the
2215 // compare constant by the multiplication factor.
2216 if (Cmp.isEquality()) {
2217 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2218 if (Mul->hasNoSignedWrap() && C.srem(RHS: *MulC).isZero()) {
2219 Constant *NewC = ConstantInt::get(Ty: MulTy, V: C.sdiv(RHS: *MulC));
2220 return new ICmpInst(Pred, X, NewC);
2221 }
2222
2223 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2224 // correct to transform if MulC * N == C including overflow. I.e with i8
2225 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2226 // miss that case.
2227 if (C.urem(RHS: *MulC).isZero()) {
2228 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2229 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2230 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2231 Constant *NewC = ConstantInt::get(Ty: MulTy, V: C.udiv(RHS: *MulC));
2232 return new ICmpInst(Pred, X, NewC);
2233 }
2234 }
2235 }
2236
2237 // With a matching no-overflow guarantee, fold the constants:
2238 // (X * MulC) < C --> X < (C / MulC)
2239 // (X * MulC) > C --> X > (C / MulC)
2240 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2241 Constant *NewC = nullptr;
2242 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(predicate: Pred)) {
2243 // MININT / -1 --> overflow.
2244 if (C.isMinSignedValue() && MulC->isAllOnes())
2245 return nullptr;
2246 if (MulC->isNegative())
2247 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
2248
2249 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2250 NewC = ConstantInt::get(
2251 Ty: MulTy, V: APIntOps::RoundingSDiv(A: C, B: *MulC, RM: APInt::Rounding::UP));
2252 } else {
2253 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2254 "Unexpected predicate");
2255 NewC = ConstantInt::get(
2256 Ty: MulTy, V: APIntOps::RoundingSDiv(A: C, B: *MulC, RM: APInt::Rounding::DOWN));
2257 }
2258 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(predicate: Pred)) {
2259 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2260 NewC = ConstantInt::get(
2261 Ty: MulTy, V: APIntOps::RoundingUDiv(A: C, B: *MulC, RM: APInt::Rounding::UP));
2262 } else {
2263 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2264 "Unexpected predicate");
2265 NewC = ConstantInt::get(
2266 Ty: MulTy, V: APIntOps::RoundingUDiv(A: C, B: *MulC, RM: APInt::Rounding::DOWN));
2267 }
2268 }
2269
2270 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2271}
2272
2273/// Fold icmp (shl nuw C2, Y), C.
2274static Instruction *foldICmpShlLHSC(ICmpInst &Cmp, Instruction *Shl,
2275 const APInt &C) {
2276 Value *Y;
2277 const APInt *C2;
2278 if (!match(V: Shl, P: m_NUWShl(L: m_APInt(Res&: C2), R: m_Value(V&: Y))))
2279 return nullptr;
2280
2281 Type *ShiftType = Shl->getType();
2282 unsigned TypeBits = C.getBitWidth();
2283 ICmpInst::Predicate Pred = Cmp.getPredicate();
2284 if (Cmp.isUnsigned()) {
2285 if (C2->isZero() || C2->ugt(RHS: C))
2286 return nullptr;
2287 APInt Div, Rem;
2288 APInt::udivrem(LHS: C, RHS: *C2, Quotient&: Div, Remainder&: Rem);
2289 bool CIsPowerOf2 = Rem.isZero() && Div.isPowerOf2();
2290
2291 // (1 << Y) pred C -> Y pred Log2(C)
2292 if (!CIsPowerOf2) {
2293 // (1 << Y) < 30 -> Y <= 4
2294 // (1 << Y) <= 30 -> Y <= 4
2295 // (1 << Y) >= 30 -> Y > 4
2296 // (1 << Y) > 30 -> Y > 4
2297 if (Pred == ICmpInst::ICMP_ULT)
2298 Pred = ICmpInst::ICMP_ULE;
2299 else if (Pred == ICmpInst::ICMP_UGE)
2300 Pred = ICmpInst::ICMP_UGT;
2301 }
2302
2303 unsigned CLog2 = Div.logBase2();
2304 return new ICmpInst(Pred, Y, ConstantInt::get(Ty: ShiftType, V: CLog2));
2305 } else if (Cmp.isSigned() && C2->isOne()) {
2306 Constant *BitWidthMinusOne = ConstantInt::get(Ty: ShiftType, V: TypeBits - 1);
2307 // (1 << Y) > 0 -> Y != 31
2308 // (1 << Y) > C -> Y != 31 if C is negative.
2309 if (Pred == ICmpInst::ICMP_SGT && C.sle(RHS: 0))
2310 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2311
2312 // (1 << Y) < 0 -> Y == 31
2313 // (1 << Y) < 1 -> Y == 31
2314 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2315 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2316 if (Pred == ICmpInst::ICMP_SLT && (C - 1).sle(RHS: 0))
2317 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2318 }
2319
2320 return nullptr;
2321}
2322
2323/// Fold icmp (shl X, Y), C.
2324Instruction *InstCombinerImpl::foldICmpShlConstant(ICmpInst &Cmp,
2325 BinaryOperator *Shl,
2326 const APInt &C) {
2327 const APInt *ShiftVal;
2328 if (Cmp.isEquality() && match(V: Shl->getOperand(i_nocapture: 0), P: m_APInt(Res&: ShiftVal)))
2329 return foldICmpShlConstConst(I&: Cmp, A: Shl->getOperand(i_nocapture: 1), AP1: C, AP2: *ShiftVal);
2330
2331 ICmpInst::Predicate Pred = Cmp.getPredicate();
2332 // (icmp pred (shl nuw&nsw X, Y), Csle0)
2333 // -> (icmp pred X, Csle0)
2334 //
2335 // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2336 // so X's must be what is used.
2337 if (C.sle(RHS: 0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2338 return new ICmpInst(Pred, Shl->getOperand(i_nocapture: 0), Cmp.getOperand(i_nocapture: 1));
2339
2340 // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2341 // -> (icmp eq/ne X, 0)
2342 if (ICmpInst::isEquality(P: Pred) && C.isZero() &&
2343 (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2344 return new ICmpInst(Pred, Shl->getOperand(i_nocapture: 0), Cmp.getOperand(i_nocapture: 1));
2345
2346 // (icmp slt (shl nsw X, Y), 0/1)
2347 // -> (icmp slt X, 0/1)
2348 // (icmp sgt (shl nsw X, Y), 0/-1)
2349 // -> (icmp sgt X, 0/-1)
2350 //
2351 // NB: sge/sle with a constant will canonicalize to sgt/slt.
2352 if (Shl->hasNoSignedWrap() &&
2353 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2354 if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2355 return new ICmpInst(Pred, Shl->getOperand(i_nocapture: 0), Cmp.getOperand(i_nocapture: 1));
2356
2357 const APInt *ShiftAmt;
2358 if (!match(V: Shl->getOperand(i_nocapture: 1), P: m_APInt(Res&: ShiftAmt)))
2359 return foldICmpShlLHSC(Cmp, Shl, C);
2360
2361 // Check that the shift amount is in range. If not, don't perform undefined
2362 // shifts. When the shift is visited, it will be simplified.
2363 unsigned TypeBits = C.getBitWidth();
2364 if (ShiftAmt->uge(RHS: TypeBits))
2365 return nullptr;
2366
2367 Value *X = Shl->getOperand(i_nocapture: 0);
2368 Type *ShType = Shl->getType();
2369
2370 // NSW guarantees that we are only shifting out sign bits from the high bits,
2371 // so we can ASHR the compare constant without needing a mask and eliminate
2372 // the shift.
2373 if (Shl->hasNoSignedWrap()) {
2374 if (Pred == ICmpInst::ICMP_SGT) {
2375 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2376 APInt ShiftedC = C.ashr(ShiftAmt: *ShiftAmt);
2377 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2378 }
2379 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2380 C.ashr(ShiftAmt: *ShiftAmt).shl(ShiftAmt: *ShiftAmt) == C) {
2381 APInt ShiftedC = C.ashr(ShiftAmt: *ShiftAmt);
2382 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2383 }
2384 if (Pred == ICmpInst::ICMP_SLT) {
2385 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2386 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2387 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2388 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2389 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2390 APInt ShiftedC = (C - 1).ashr(ShiftAmt: *ShiftAmt) + 1;
2391 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2392 }
2393 }
2394
2395 // NUW guarantees that we are only shifting out zero bits from the high bits,
2396 // so we can LSHR the compare constant without needing a mask and eliminate
2397 // the shift.
2398 if (Shl->hasNoUnsignedWrap()) {
2399 if (Pred == ICmpInst::ICMP_UGT) {
2400 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2401 APInt ShiftedC = C.lshr(ShiftAmt: *ShiftAmt);
2402 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2403 }
2404 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2405 C.lshr(ShiftAmt: *ShiftAmt).shl(ShiftAmt: *ShiftAmt) == C) {
2406 APInt ShiftedC = C.lshr(ShiftAmt: *ShiftAmt);
2407 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2408 }
2409 if (Pred == ICmpInst::ICMP_ULT) {
2410 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2411 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2412 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2413 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2414 assert(C.ugt(0) && "ult 0 should have been eliminated");
2415 APInt ShiftedC = (C - 1).lshr(ShiftAmt: *ShiftAmt) + 1;
2416 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2417 }
2418 }
2419
2420 if (Cmp.isEquality() && Shl->hasOneUse()) {
2421 // Strength-reduce the shift into an 'and'.
2422 Constant *Mask = ConstantInt::get(
2423 Ty: ShType,
2424 V: APInt::getLowBitsSet(numBits: TypeBits, loBitsSet: TypeBits - ShiftAmt->getZExtValue()));
2425 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask, Name: Shl->getName() + ".mask");
2426 Constant *LShrC = ConstantInt::get(Ty: ShType, V: C.lshr(ShiftAmt: *ShiftAmt));
2427 return new ICmpInst(Pred, And, LShrC);
2428 }
2429
2430 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2431 bool TrueIfSigned = false;
2432 if (Shl->hasOneUse() && isSignBitCheck(Pred, RHS: C, TrueIfSigned)) {
2433 // (X << 31) <s 0 --> (X & 1) != 0
2434 Constant *Mask = ConstantInt::get(
2435 Ty: ShType,
2436 V: APInt::getOneBitSet(numBits: TypeBits, BitNo: TypeBits - ShiftAmt->getZExtValue() - 1));
2437 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask, Name: Shl->getName() + ".mask");
2438 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2439 And, Constant::getNullValue(Ty: ShType));
2440 }
2441
2442 // Simplify 'shl' inequality test into 'and' equality test.
2443 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2444 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2445 if ((C + 1).isPowerOf2() &&
2446 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2447 Value *And = Builder.CreateAnd(LHS: X, RHS: (~C).lshr(shiftAmt: ShiftAmt->getZExtValue()));
2448 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2449 : ICmpInst::ICMP_NE,
2450 And, Constant::getNullValue(Ty: ShType));
2451 }
2452 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2453 if (C.isPowerOf2() &&
2454 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2455 Value *And =
2456 Builder.CreateAnd(LHS: X, RHS: (~(C - 1)).lshr(shiftAmt: ShiftAmt->getZExtValue()));
2457 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2458 : ICmpInst::ICMP_NE,
2459 And, Constant::getNullValue(Ty: ShType));
2460 }
2461 }
2462
2463 // Transform (icmp pred iM (shl iM %v, N), C)
2464 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2465 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2466 // This enables us to get rid of the shift in favor of a trunc that may be
2467 // free on the target. It has the additional benefit of comparing to a
2468 // smaller constant that may be more target-friendly.
2469 unsigned Amt = ShiftAmt->getLimitedValue(Limit: TypeBits - 1);
2470 if (Shl->hasOneUse() && Amt != 0 &&
2471 shouldChangeType(FromBitWidth: ShType->getScalarSizeInBits(), ToBitWidth: TypeBits - Amt)) {
2472 ICmpInst::Predicate CmpPred = Pred;
2473 APInt RHSC = C;
2474
2475 if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(predicate: CmpPred)) {
2476 // Try the flipped strictness predicate.
2477 // e.g.:
2478 // icmp ult i64 (shl X, 32), 8589934593 ->
2479 // icmp ule i64 (shl X, 32), 8589934592 ->
2480 // icmp ule i32 (trunc X, i32), 2 ->
2481 // icmp ult i32 (trunc X, i32), 3
2482 if (auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(
2483 Pred, C: ConstantInt::get(Context&: ShType->getContext(), V: C))) {
2484 CmpPred = FlippedStrictness->first;
2485 RHSC = cast<ConstantInt>(Val: FlippedStrictness->second)->getValue();
2486 }
2487 }
2488
2489 if (RHSC.countr_zero() >= Amt) {
2490 Type *TruncTy = ShType->getWithNewBitWidth(NewBitWidth: TypeBits - Amt);
2491 Constant *NewC =
2492 ConstantInt::get(Ty: TruncTy, V: RHSC.ashr(ShiftAmt: *ShiftAmt).trunc(width: TypeBits - Amt));
2493 return new ICmpInst(CmpPred,
2494 Builder.CreateTrunc(V: X, DestTy: TruncTy, Name: "", /*IsNUW=*/false,
2495 IsNSW: Shl->hasNoSignedWrap()),
2496 NewC);
2497 }
2498 }
2499
2500 return nullptr;
2501}
2502
2503/// Fold icmp ({al}shr X, Y), C.
2504Instruction *InstCombinerImpl::foldICmpShrConstant(ICmpInst &Cmp,
2505 BinaryOperator *Shr,
2506 const APInt &C) {
2507 // An exact shr only shifts out zero bits, so:
2508 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2509 Value *X = Shr->getOperand(i_nocapture: 0);
2510 CmpInst::Predicate Pred = Cmp.getPredicate();
2511 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2512 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
2513
2514 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2515 const APInt *ShiftValC;
2516 if (match(V: X, P: m_APInt(Res&: ShiftValC))) {
2517 if (Cmp.isEquality())
2518 return foldICmpShrConstConst(I&: Cmp, A: Shr->getOperand(i_nocapture: 1), AP1: C, AP2: *ShiftValC);
2519
2520 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2521 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2522 bool TrueIfSigned;
2523 if (!IsAShr && ShiftValC->isNegative() &&
2524 isSignBitCheck(Pred, RHS: C, TrueIfSigned))
2525 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2526 Shr->getOperand(i_nocapture: 1),
2527 ConstantInt::getNullValue(Ty: X->getType()));
2528
2529 // If the shifted constant is a power-of-2, test the shift amount directly:
2530 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2531 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2532 if (!IsAShr && ShiftValC->isPowerOf2() &&
2533 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2534 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2535 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2536 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2537
2538 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2539 unsigned ShiftLZ = ShiftValC->countl_zero();
2540 Constant *NewC = ConstantInt::get(Ty: Shr->getType(), V: CmpLZ - ShiftLZ);
2541 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2542 return new ICmpInst(NewPred, Shr->getOperand(i_nocapture: 1), NewC);
2543 }
2544 }
2545
2546 const APInt *ShiftAmtC;
2547 if (!match(V: Shr->getOperand(i_nocapture: 1), P: m_APInt(Res&: ShiftAmtC)))
2548 return nullptr;
2549
2550 // Check that the shift amount is in range. If not, don't perform undefined
2551 // shifts. When the shift is visited it will be simplified.
2552 unsigned TypeBits = C.getBitWidth();
2553 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(Limit: TypeBits);
2554 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2555 return nullptr;
2556
2557 bool IsExact = Shr->isExact();
2558 Type *ShrTy = Shr->getType();
2559 // TODO: If we could guarantee that InstSimplify would handle all of the
2560 // constant-value-based preconditions in the folds below, then we could assert
2561 // those conditions rather than checking them. This is difficult because of
2562 // undef/poison (PR34838).
2563 if (IsAShr && Shr->hasOneUse()) {
2564 if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&
2565 (C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {
2566 // When C - 1 is a power of two and the transform can be legally
2567 // performed, prefer this form so the produced constant is close to a
2568 // power of two.
2569 // icmp slt/ult (ashr exact X, ShAmtC), C
2570 // --> icmp slt/ult X, (C - 1) << ShAmtC) + 1
2571 APInt ShiftedC = (C - 1).shl(shiftAmt: ShAmtVal) + 1;
2572 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2573 }
2574 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2575 // When ShAmtC can be shifted losslessly:
2576 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2577 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2578 APInt ShiftedC = C.shl(shiftAmt: ShAmtVal);
2579 if (ShiftedC.ashr(ShiftAmt: ShAmtVal) == C)
2580 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2581 }
2582 if (Pred == CmpInst::ICMP_SGT) {
2583 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2584 APInt ShiftedC = (C + 1).shl(shiftAmt: ShAmtVal) - 1;
2585 if (!C.isMaxSignedValue() && !(C + 1).shl(shiftAmt: ShAmtVal).isMinSignedValue() &&
2586 (ShiftedC + 1).ashr(ShiftAmt: ShAmtVal) == (C + 1))
2587 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2588 }
2589 if (Pred == CmpInst::ICMP_UGT) {
2590 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2591 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2592 // clause accounts for that pattern.
2593 APInt ShiftedC = (C + 1).shl(shiftAmt: ShAmtVal) - 1;
2594 if ((ShiftedC + 1).ashr(ShiftAmt: ShAmtVal) == (C + 1) ||
2595 (C + 1).shl(shiftAmt: ShAmtVal).isMinSignedValue())
2596 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2597 }
2598
2599 // If the compare constant has significant bits above the lowest sign-bit,
2600 // then convert an unsigned cmp to a test of the sign-bit:
2601 // (ashr X, ShiftC) u> C --> X s< 0
2602 // (ashr X, ShiftC) u< C --> X s> -1
2603 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2604 if (Pred == CmpInst::ICMP_UGT) {
2605 return new ICmpInst(CmpInst::ICMP_SLT, X,
2606 ConstantInt::getNullValue(Ty: ShrTy));
2607 }
2608 if (Pred == CmpInst::ICMP_ULT) {
2609 return new ICmpInst(CmpInst::ICMP_SGT, X,
2610 ConstantInt::getAllOnesValue(Ty: ShrTy));
2611 }
2612 }
2613 } else if (!IsAShr) {
2614 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2615 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2616 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2617 APInt ShiftedC = C.shl(shiftAmt: ShAmtVal);
2618 if (ShiftedC.lshr(shiftAmt: ShAmtVal) == C)
2619 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2620 }
2621 if (Pred == CmpInst::ICMP_UGT) {
2622 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2623 APInt ShiftedC = (C + 1).shl(shiftAmt: ShAmtVal) - 1;
2624 if ((ShiftedC + 1).lshr(shiftAmt: ShAmtVal) == (C + 1))
2625 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2626 }
2627 }
2628
2629 if (!Cmp.isEquality())
2630 return nullptr;
2631
2632 // Handle equality comparisons of shift-by-constant.
2633
2634 // If the comparison constant changes with the shift, the comparison cannot
2635 // succeed (bits of the comparison constant cannot match the shifted value).
2636 // This should be known by InstSimplify and already be folded to true/false.
2637 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2638 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2639 "Expected icmp+shr simplify did not occur.");
2640
2641 // If the bits shifted out are known zero, compare the unshifted value:
2642 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2643 if (Shr->isExact())
2644 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: C << ShAmtVal));
2645
2646 if (Shr->hasOneUse()) {
2647 // Canonicalize the shift into an 'and':
2648 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2649 APInt Val(APInt::getHighBitsSet(numBits: TypeBits, hiBitsSet: TypeBits - ShAmtVal));
2650 Constant *Mask = ConstantInt::get(Ty: ShrTy, V: Val);
2651 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask, Name: Shr->getName() + ".mask");
2652 return new ICmpInst(Pred, And, ConstantInt::get(Ty: ShrTy, V: C << ShAmtVal));
2653 }
2654
2655 return nullptr;
2656}
2657
2658Instruction *InstCombinerImpl::foldICmpSRemConstant(ICmpInst &Cmp,
2659 BinaryOperator *SRem,
2660 const APInt &C) {
2661 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2662 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT) {
2663 // Canonicalize unsigned predicates to signed:
2664 // (X s% DivisorC) u> C -> (X s% DivisorC) s< 0
2665 // iff (C s< 0 ? ~C : C) u>= abs(DivisorC)-1
2666 // (X s% DivisorC) u< C+1 -> (X s% DivisorC) s> -1
2667 // iff (C+1 s< 0 ? ~C : C) u>= abs(DivisorC)-1
2668
2669 const APInt *DivisorC;
2670 if (!match(V: SRem->getOperand(i_nocapture: 1), P: m_APInt(Res&: DivisorC)))
2671 return nullptr;
2672 if (DivisorC->isZero())
2673 return nullptr;
2674
2675 APInt NormalizedC = C;
2676 if (Pred == ICmpInst::ICMP_ULT) {
2677 assert(!NormalizedC.isZero() &&
2678 "ult X, 0 should have been simplified already.");
2679 --NormalizedC;
2680 }
2681 if (C.isNegative())
2682 NormalizedC.flipAllBits();
2683 if (!NormalizedC.uge(RHS: DivisorC->abs() - 1))
2684 return nullptr;
2685
2686 Type *Ty = SRem->getType();
2687 if (Pred == ICmpInst::ICMP_UGT)
2688 return new ICmpInst(ICmpInst::ICMP_SLT, SRem,
2689 ConstantInt::getNullValue(Ty));
2690 return new ICmpInst(ICmpInst::ICMP_SGT, SRem,
2691 ConstantInt::getAllOnesValue(Ty));
2692 }
2693 // Match an 'is positive' or 'is negative' comparison of remainder by a
2694 // constant power-of-2 value:
2695 // (X % pow2C) sgt/slt 0
2696 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2697 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2698 return nullptr;
2699
2700 // TODO: The one-use check is standard because we do not typically want to
2701 // create longer instruction sequences, but this might be a special-case
2702 // because srem is not good for analysis or codegen.
2703 if (!SRem->hasOneUse())
2704 return nullptr;
2705
2706 const APInt *DivisorC;
2707 if (!match(V: SRem->getOperand(i_nocapture: 1), P: m_Power2(V&: DivisorC)))
2708 return nullptr;
2709
2710 // For cmp_sgt/cmp_slt only zero valued C is handled.
2711 // For cmp_eq/cmp_ne only positive valued C is handled.
2712 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2713 !C.isZero()) ||
2714 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2715 !C.isStrictlyPositive()))
2716 return nullptr;
2717
2718 // Mask off the sign bit and the modulo bits (low-bits).
2719 Type *Ty = SRem->getType();
2720 APInt SignMask = APInt::getSignMask(BitWidth: Ty->getScalarSizeInBits());
2721 Constant *MaskC = ConstantInt::get(Ty, V: SignMask | (*DivisorC - 1));
2722 Value *And = Builder.CreateAnd(LHS: SRem->getOperand(i_nocapture: 0), RHS: MaskC);
2723
2724 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2725 return new ICmpInst(Pred, And, ConstantInt::get(Ty, V: C));
2726
2727 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2728 // bit is set. Example:
2729 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2730 if (Pred == ICmpInst::ICMP_SGT)
2731 return new ICmpInst(ICmpInst::ICMP_SGT, And, ConstantInt::getNullValue(Ty));
2732
2733 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2734 // bit is set. Example:
2735 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2736 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, V: SignMask));
2737}
2738
2739/// Fold icmp (udiv X, Y), C.
2740Instruction *InstCombinerImpl::foldICmpUDivConstant(ICmpInst &Cmp,
2741 BinaryOperator *UDiv,
2742 const APInt &C) {
2743 ICmpInst::Predicate Pred = Cmp.getPredicate();
2744 Value *X = UDiv->getOperand(i_nocapture: 0);
2745 Value *Y = UDiv->getOperand(i_nocapture: 1);
2746 Type *Ty = UDiv->getType();
2747
2748 const APInt *C2;
2749 if (!match(V: X, P: m_APInt(Res&: C2)))
2750 return nullptr;
2751
2752 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2753
2754 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2755 if (Pred == ICmpInst::ICMP_UGT) {
2756 assert(!C.isMaxValue() &&
2757 "icmp ugt X, UINT_MAX should have been simplified already.");
2758 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2759 ConstantInt::get(Ty, V: C2->udiv(RHS: C + 1)));
2760 }
2761
2762 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2763 if (Pred == ICmpInst::ICMP_ULT) {
2764 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2765 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2766 ConstantInt::get(Ty, V: C2->udiv(RHS: C)));
2767 }
2768
2769 return nullptr;
2770}
2771
2772/// Fold icmp ({su}div X, Y), C.
2773Instruction *InstCombinerImpl::foldICmpDivConstant(ICmpInst &Cmp,
2774 BinaryOperator *Div,
2775 const APInt &C) {
2776 ICmpInst::Predicate Pred = Cmp.getPredicate();
2777 Value *X = Div->getOperand(i_nocapture: 0);
2778 Value *Y = Div->getOperand(i_nocapture: 1);
2779 Type *Ty = Div->getType();
2780 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2781
2782 // If unsigned division and the compare constant is bigger than
2783 // UMAX/2 (negative), there's only one pair of values that satisfies an
2784 // equality check, so eliminate the division:
2785 // (X u/ Y) == C --> (X == C) && (Y == 1)
2786 // (X u/ Y) != C --> (X != C) || (Y != 1)
2787 // Similarly, if signed division and the compare constant is exactly SMIN:
2788 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2789 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2790 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2791 (!DivIsSigned || C.isMinSignedValue())) {
2792 Value *XBig = Builder.CreateICmp(P: Pred, LHS: X, RHS: ConstantInt::get(Ty, V: C));
2793 Value *YOne = Builder.CreateICmp(P: Pred, LHS: Y, RHS: ConstantInt::get(Ty, V: 1));
2794 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2795 return BinaryOperator::Create(Op: Logic, S1: XBig, S2: YOne);
2796 }
2797
2798 // Fold: icmp pred ([us]div X, C2), C -> range test
2799 // Fold this div into the comparison, producing a range check.
2800 // Determine, based on the divide type, what the range is being
2801 // checked. If there is an overflow on the low or high side, remember
2802 // it, otherwise compute the range [low, hi) bounding the new value.
2803 // See: InsertRangeTest above for the kinds of replacements possible.
2804 const APInt *C2;
2805 if (!match(V: Y, P: m_APInt(Res&: C2)))
2806 return nullptr;
2807
2808 // FIXME: If the operand types don't match the type of the divide
2809 // then don't attempt this transform. The code below doesn't have the
2810 // logic to deal with a signed divide and an unsigned compare (and
2811 // vice versa). This is because (x /s C2) <s C produces different
2812 // results than (x /s C2) <u C or (x /u C2) <s C or even
2813 // (x /u C2) <u C. Simply casting the operands and result won't
2814 // work. :( The if statement below tests that condition and bails
2815 // if it finds it.
2816 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
2817 return nullptr;
2818
2819 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2820 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2821 // division-by-constant cases should be present, we can not assert that they
2822 // have happened before we reach this icmp instruction.
2823 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2824 return nullptr;
2825
2826 // Compute Prod = C * C2. We are essentially solving an equation of
2827 // form X / C2 = C. We solve for X by multiplying C2 and C.
2828 // By solving for X, we can turn this into a range check instead of computing
2829 // a divide.
2830 APInt Prod = C * *C2;
2831
2832 // Determine if the product overflows by seeing if the product is not equal to
2833 // the divide. Make sure we do the same kind of divide as in the LHS
2834 // instruction that we're folding.
2835 bool ProdOV = (DivIsSigned ? Prod.sdiv(RHS: *C2) : Prod.udiv(RHS: *C2)) != C;
2836
2837 // If the division is known to be exact, then there is no remainder from the
2838 // divide, so the covered range size is unit, otherwise it is the divisor.
2839 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2840
2841 // Figure out the interval that is being checked. For example, a comparison
2842 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2843 // Compute this interval based on the constants involved and the signedness of
2844 // the compare/divide. This computes a half-open interval, keeping track of
2845 // whether either value in the interval overflows. After analysis each
2846 // overflow variable is set to 0 if it's corresponding bound variable is valid
2847 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2848 int LoOverflow = 0, HiOverflow = 0;
2849 APInt LoBound, HiBound;
2850
2851 if (!DivIsSigned) { // udiv
2852 // e.g. X/5 op 3 --> [15, 20)
2853 LoBound = Prod;
2854 HiOverflow = LoOverflow = ProdOV;
2855 if (!HiOverflow) {
2856 // If this is not an exact divide, then many values in the range collapse
2857 // to the same result value.
2858 HiOverflow = addWithOverflow(Result&: HiBound, In1: LoBound, In2: RangeSize, IsSigned: false);
2859 }
2860 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2861 if (C.isZero()) { // (X / pos) op 0
2862 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2863 LoBound = -(RangeSize - 1);
2864 HiBound = RangeSize;
2865 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2866 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2867 HiOverflow = LoOverflow = ProdOV;
2868 if (!HiOverflow)
2869 HiOverflow = addWithOverflow(Result&: HiBound, In1: Prod, In2: RangeSize, IsSigned: true);
2870 } else { // (X / pos) op neg
2871 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2872 HiBound = Prod + 1;
2873 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2874 if (!LoOverflow) {
2875 APInt DivNeg = -RangeSize;
2876 LoOverflow = addWithOverflow(Result&: LoBound, In1: HiBound, In2: DivNeg, IsSigned: true) ? -1 : 0;
2877 }
2878 }
2879 } else if (C2->isNegative()) { // Divisor is < 0.
2880 if (Div->isExact())
2881 RangeSize.negate();
2882 if (C.isZero()) { // (X / neg) op 0
2883 // e.g. X/-5 op 0 --> [-4, 5)
2884 LoBound = RangeSize + 1;
2885 HiBound = -RangeSize;
2886 if (HiBound == *C2) { // -INTMIN = INTMIN
2887 HiOverflow = 1; // [INTMIN+1, overflow)
2888 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2889 }
2890 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2891 // e.g. X/-5 op 3 --> [-19, -14)
2892 HiBound = Prod + 1;
2893 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2894 if (!LoOverflow)
2895 LoOverflow =
2896 addWithOverflow(Result&: LoBound, In1: HiBound, In2: RangeSize, IsSigned: true) ? -1 : 0;
2897 } else { // (X / neg) op neg
2898 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2899 LoOverflow = HiOverflow = ProdOV;
2900 if (!HiOverflow)
2901 HiOverflow = subWithOverflow(Result&: HiBound, In1: Prod, In2: RangeSize, IsSigned: true);
2902 }
2903
2904 // Dividing by a negative swaps the condition. LT <-> GT
2905 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
2906 }
2907
2908 switch (Pred) {
2909 default:
2910 llvm_unreachable("Unhandled icmp predicate!");
2911 case ICmpInst::ICMP_EQ:
2912 if (LoOverflow && HiOverflow)
2913 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
2914 if (HiOverflow)
2915 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2916 X, ConstantInt::get(Ty, V: LoBound));
2917 if (LoOverflow)
2918 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2919 X, ConstantInt::get(Ty, V: HiBound));
2920 return replaceInstUsesWith(
2921 I&: Cmp, V: insertRangeTest(V: X, Lo: LoBound, Hi: HiBound, isSigned: DivIsSigned, Inside: true));
2922 case ICmpInst::ICMP_NE:
2923 if (LoOverflow && HiOverflow)
2924 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
2925 if (HiOverflow)
2926 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2927 X, ConstantInt::get(Ty, V: LoBound));
2928 if (LoOverflow)
2929 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2930 X, ConstantInt::get(Ty, V: HiBound));
2931 return replaceInstUsesWith(
2932 I&: Cmp, V: insertRangeTest(V: X, Lo: LoBound, Hi: HiBound, isSigned: DivIsSigned, Inside: false));
2933 case ICmpInst::ICMP_ULT:
2934 case ICmpInst::ICMP_SLT:
2935 if (LoOverflow == +1) // Low bound is greater than input range.
2936 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
2937 if (LoOverflow == -1) // Low bound is less than input range.
2938 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
2939 return new ICmpInst(Pred, X, ConstantInt::get(Ty, V: LoBound));
2940 case ICmpInst::ICMP_UGT:
2941 case ICmpInst::ICMP_SGT:
2942 if (HiOverflow == +1) // High bound greater than input range.
2943 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
2944 if (HiOverflow == -1) // High bound less than input range.
2945 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
2946 if (Pred == ICmpInst::ICMP_UGT)
2947 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, V: HiBound));
2948 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, V: HiBound));
2949 }
2950
2951 return nullptr;
2952}
2953
2954/// Fold icmp (sub X, Y), C.
2955Instruction *InstCombinerImpl::foldICmpSubConstant(ICmpInst &Cmp,
2956 BinaryOperator *Sub,
2957 const APInt &C) {
2958 Value *X = Sub->getOperand(i_nocapture: 0), *Y = Sub->getOperand(i_nocapture: 1);
2959 ICmpInst::Predicate Pred = Cmp.getPredicate();
2960 Type *Ty = Sub->getType();
2961
2962 // (SubC - Y) == C) --> Y == (SubC - C)
2963 // (SubC - Y) != C) --> Y != (SubC - C)
2964 Constant *SubC;
2965 if (Cmp.isEquality() && match(V: X, P: m_ImmConstant(C&: SubC))) {
2966 return new ICmpInst(Pred, Y,
2967 ConstantExpr::getSub(C1: SubC, C2: ConstantInt::get(Ty, V: C)));
2968 }
2969
2970 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
2971 const APInt *C2;
2972 APInt SubResult;
2973 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
2974 bool HasNSW = Sub->hasNoSignedWrap();
2975 bool HasNUW = Sub->hasNoUnsignedWrap();
2976 if (match(V: X, P: m_APInt(Res&: C2)) &&
2977 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
2978 !subWithOverflow(Result&: SubResult, In1: *C2, In2: C, IsSigned: Cmp.isSigned()))
2979 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, V: SubResult));
2980
2981 // X - Y == 0 --> X == Y.
2982 // X - Y != 0 --> X != Y.
2983 // TODO: We allow this with multiple uses as long as the other uses are not
2984 // in phis. The phi use check is guarding against a codegen regression
2985 // for a loop test. If the backend could undo this (and possibly
2986 // subsequent transforms), we would not need this hack.
2987 if (Cmp.isEquality() && C.isZero() &&
2988 none_of(Range: (Sub->users()), P: [](const User *U) { return isa<PHINode>(Val: U); }))
2989 return new ICmpInst(Pred, X, Y);
2990
2991 // The following transforms are only worth it if the only user of the subtract
2992 // is the icmp.
2993 // TODO: This is an artificial restriction for all of the transforms below
2994 // that only need a single replacement icmp. Can these use the phi test
2995 // like the transform above here?
2996 if (!Sub->hasOneUse())
2997 return nullptr;
2998
2999 if (Sub->hasNoSignedWrap()) {
3000 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
3001 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3002 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3003
3004 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
3005 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
3006 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3007
3008 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
3009 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
3010 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3011
3012 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
3013 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3014 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3015 }
3016
3017 if (!match(V: X, P: m_APInt(Res&: C2)))
3018 return nullptr;
3019
3020 // C2 - Y <u C -> (Y | (C - 1)) == C2
3021 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
3022 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
3023 (*C2 & (C - 1)) == (C - 1))
3024 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(LHS: Y, RHS: C - 1), X);
3025
3026 // C2 - Y >u C -> (Y | C) != C2
3027 // iff C2 & C == C and C + 1 is a power of 2
3028 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
3029 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(LHS: Y, RHS: C), X);
3030
3031 // We have handled special cases that reduce.
3032 // Canonicalize any remaining sub to add as:
3033 // (C2 - Y) > C --> (Y + ~C2) < ~C
3034 Value *Add = Builder.CreateAdd(LHS: Y, RHS: ConstantInt::get(Ty, V: ~(*C2)), Name: "notsub",
3035 HasNUW, HasNSW);
3036 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, V: ~C));
3037}
3038
3039static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
3040 Value *Op1, IRBuilderBase &Builder,
3041 bool HasOneUse) {
3042 auto FoldConstant = [&](bool Val) {
3043 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3044 if (Op0->getType()->isVectorTy())
3045 Res = ConstantVector::getSplat(
3046 EC: cast<VectorType>(Val: Op0->getType())->getElementCount(), Elt: Res);
3047 return Res;
3048 };
3049
3050 switch (Table.to_ulong()) {
3051 case 0: // 0 0 0 0
3052 return FoldConstant(false);
3053 case 1: // 0 0 0 1
3054 return HasOneUse ? Builder.CreateNot(V: Builder.CreateOr(LHS: Op0, RHS: Op1)) : nullptr;
3055 case 2: // 0 0 1 0
3056 return HasOneUse ? Builder.CreateAnd(LHS: Builder.CreateNot(V: Op0), RHS: Op1) : nullptr;
3057 case 3: // 0 0 1 1
3058 return Builder.CreateNot(V: Op0);
3059 case 4: // 0 1 0 0
3060 return HasOneUse ? Builder.CreateAnd(LHS: Op0, RHS: Builder.CreateNot(V: Op1)) : nullptr;
3061 case 5: // 0 1 0 1
3062 return Builder.CreateNot(V: Op1);
3063 case 6: // 0 1 1 0
3064 return Builder.CreateXor(LHS: Op0, RHS: Op1);
3065 case 7: // 0 1 1 1
3066 return HasOneUse ? Builder.CreateNot(V: Builder.CreateAnd(LHS: Op0, RHS: Op1)) : nullptr;
3067 case 8: // 1 0 0 0
3068 return Builder.CreateAnd(LHS: Op0, RHS: Op1);
3069 case 9: // 1 0 0 1
3070 return HasOneUse ? Builder.CreateNot(V: Builder.CreateXor(LHS: Op0, RHS: Op1)) : nullptr;
3071 case 10: // 1 0 1 0
3072 return Op1;
3073 case 11: // 1 0 1 1
3074 return HasOneUse ? Builder.CreateOr(LHS: Builder.CreateNot(V: Op0), RHS: Op1) : nullptr;
3075 case 12: // 1 1 0 0
3076 return Op0;
3077 case 13: // 1 1 0 1
3078 return HasOneUse ? Builder.CreateOr(LHS: Op0, RHS: Builder.CreateNot(V: Op1)) : nullptr;
3079 case 14: // 1 1 1 0
3080 return Builder.CreateOr(LHS: Op0, RHS: Op1);
3081 case 15: // 1 1 1 1
3082 return FoldConstant(true);
3083 default:
3084 llvm_unreachable("Invalid Operation");
3085 }
3086 return nullptr;
3087}
3088
3089Instruction *InstCombinerImpl::foldICmpBinOpWithConstantViaTruthTable(
3090 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3091 Value *A, *B;
3092 Constant *C1, *C2, *C3, *C4;
3093 if (!(match(V: BO->getOperand(i_nocapture: 0),
3094 P: m_Select(C: m_Value(V&: A), L: m_Constant(C&: C1), R: m_Constant(C&: C2)))) ||
3095 !match(V: BO->getOperand(i_nocapture: 1),
3096 P: m_Select(C: m_Value(V&: B), L: m_Constant(C&: C3), R: m_Constant(C&: C4))) ||
3097 Cmp.getType() != A->getType() || Cmp.getType() != B->getType())
3098 return nullptr;
3099
3100 std::bitset<4> Table;
3101 auto ComputeTable = [&](bool First, bool Second) -> std::optional<bool> {
3102 Constant *L = First ? C1 : C2;
3103 Constant *R = Second ? C3 : C4;
3104 if (auto *Res = ConstantFoldBinaryOpOperands(Opcode: BO->getOpcode(), LHS: L, RHS: R, DL)) {
3105 auto *Val = Res->getType()->isVectorTy() ? Res->getSplatValue() : Res;
3106 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val))
3107 return ICmpInst::compare(LHS: CI->getValue(), RHS: C, Pred: Cmp.getPredicate());
3108 }
3109 return std::nullopt;
3110 };
3111
3112 for (unsigned I = 0; I < 4; ++I) {
3113 bool First = (I >> 1) & 1;
3114 bool Second = I & 1;
3115 if (auto Res = ComputeTable(First, Second))
3116 Table[I] = *Res;
3117 else
3118 return nullptr;
3119 }
3120
3121 // Synthesize optimal logic.
3122 if (auto *Cond = createLogicFromTable(Table, Op0: A, Op1: B, Builder, HasOneUse: BO->hasOneUse()))
3123 return replaceInstUsesWith(I&: Cmp, V: Cond);
3124 return nullptr;
3125}
3126
3127/// Fold icmp (add X, Y), C.
3128Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp,
3129 BinaryOperator *Add,
3130 const APInt &C) {
3131 Value *Y = Add->getOperand(i_nocapture: 1);
3132 Value *X = Add->getOperand(i_nocapture: 0);
3133
3134 Value *Op0, *Op1;
3135 Instruction *Ext0, *Ext1;
3136 const CmpPredicate Pred = Cmp.getCmpPredicate();
3137 if (match(V: Add,
3138 P: m_Add(L: m_CombineAnd(L: m_Instruction(I&: Ext0), R: m_ZExtOrSExt(Op: m_Value(V&: Op0))),
3139 R: m_CombineAnd(L: m_Instruction(I&: Ext1),
3140 R: m_ZExtOrSExt(Op: m_Value(V&: Op1))))) &&
3141 Op0->getType()->isIntOrIntVectorTy(BitWidth: 1) &&
3142 Op1->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
3143 unsigned BW = C.getBitWidth();
3144 std::bitset<4> Table;
3145 auto ComputeTable = [&](bool Op0Val, bool Op1Val) {
3146 APInt Res(BW, 0);
3147 if (Op0Val)
3148 Res += APInt(BW, isa<ZExtInst>(Val: Ext0) ? 1 : -1, /*isSigned=*/true);
3149 if (Op1Val)
3150 Res += APInt(BW, isa<ZExtInst>(Val: Ext1) ? 1 : -1, /*isSigned=*/true);
3151 return ICmpInst::compare(LHS: Res, RHS: C, Pred);
3152 };
3153
3154 Table[0] = ComputeTable(false, false);
3155 Table[1] = ComputeTable(false, true);
3156 Table[2] = ComputeTable(true, false);
3157 Table[3] = ComputeTable(true, true);
3158 if (auto *Cond =
3159 createLogicFromTable(Table, Op0, Op1, Builder, HasOneUse: Add->hasOneUse()))
3160 return replaceInstUsesWith(I&: Cmp, V: Cond);
3161 }
3162
3163 // icmp ult (add nuw A, (lshr A, ShAmtC)), C --> icmp ult A, C
3164 // when C <= (1 << ShAmtC).
3165 const APInt *ShAmtC;
3166 Value *A;
3167 unsigned BitWidth = C.getBitWidth();
3168 if (Pred == ICmpInst::ICMP_ULT &&
3169 match(V: Add,
3170 P: m_c_NUWAdd(L: m_Value(V&: A), R: m_LShr(L: m_Deferred(V: A), R: m_APInt(Res&: ShAmtC)))) &&
3171 ShAmtC->ult(RHS: BitWidth) &&
3172 C.ule(RHS: APInt::getOneBitSet(numBits: BitWidth, BitNo: ShAmtC->getZExtValue())))
3173 return new ICmpInst(Pred, A, ConstantInt::get(Ty: A->getType(), V: C));
3174
3175 const APInt *C2;
3176 if (Cmp.isEquality() || !match(V: Y, P: m_APInt(Res&: C2)))
3177 return nullptr;
3178
3179 // Fold icmp pred (add X, C2), C.
3180 Type *Ty = Add->getType();
3181
3182 // If the add does not wrap, we can always adjust the compare by subtracting
3183 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3184 // have been canonicalized to SGT/SLT/UGT/ULT.
3185 if (Add->hasNoUnsignedWrap() &&
3186 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT)) {
3187 bool Overflow;
3188 APInt NewC = C.usub_ov(RHS: *C2, Overflow);
3189 // If there is overflow, the result must be true or false.
3190 if (!Overflow)
3191 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
3192 return new ICmpInst(Pred, X, ConstantInt::get(Ty, V: NewC));
3193 }
3194
3195 CmpInst::Predicate ChosenPred = Pred.getPreferredSignedPredicate();
3196
3197 if (Add->hasNoSignedWrap() &&
3198 (ChosenPred == ICmpInst::ICMP_SGT || ChosenPred == ICmpInst::ICMP_SLT)) {
3199 bool Overflow;
3200 APInt NewC = C.ssub_ov(RHS: *C2, Overflow);
3201 if (!Overflow)
3202 // icmp samesign ugt/ult (add nsw X, C2), C
3203 // -> icmp sgt/slt X, (C - C2)
3204 return new ICmpInst(ChosenPred, X, ConstantInt::get(Ty, V: NewC));
3205 }
3206
3207 if (ICmpInst::isUnsigned(predicate: Pred) && Add->hasNoSignedWrap() &&
3208 C.isNonNegative() && (C - *C2).isNonNegative() &&
3209 computeConstantRange(V: X, /*ForSigned=*/true).add(Other: *C2).isAllNonNegative())
3210 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), X,
3211 ConstantInt::get(Ty, V: C - *C2));
3212
3213 auto CR = ConstantRange::makeExactICmpRegion(Pred, Other: C).subtract(CI: *C2);
3214 const APInt &Upper = CR.getUpper();
3215 const APInt &Lower = CR.getLower();
3216 if (Cmp.isSigned()) {
3217 if (Lower.isSignMask())
3218 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, V: Upper));
3219 if (Upper.isSignMask())
3220 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, V: Lower));
3221 } else {
3222 if (Lower.isMinValue())
3223 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, V: Upper));
3224 if (Upper.isMinValue())
3225 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, V: Lower));
3226 }
3227
3228 // This set of folds is intentionally placed after folds that use no-wrapping
3229 // flags because those folds are likely better for later analysis/codegen.
3230 const APInt SMax = APInt::getSignedMaxValue(numBits: Ty->getScalarSizeInBits());
3231 const APInt SMin = APInt::getSignedMinValue(numBits: Ty->getScalarSizeInBits());
3232
3233 // Fold compare with offset to opposite sign compare if it eliminates offset:
3234 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3235 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3236 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, V: -(*C2)));
3237
3238 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3239 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3240 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, V: ~(*C2)));
3241
3242 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3243 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3244 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, V: SMax - C));
3245
3246 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3247 if (Pred == CmpInst::ICMP_SLT && C == *C2)
3248 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, V: C ^ SMax));
3249
3250 // (X + -1) <u C --> X <=u C (if X is never null)
3251 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3252 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
3253 if (llvm::isKnownNonZero(V: X, Q))
3254 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, V: C));
3255 }
3256
3257 if (!Add->hasOneUse())
3258 return nullptr;
3259
3260 // X+C <u C2 -> (X & -C2) == C
3261 // iff C & (C2-1) == 0
3262 // C2 is a power of 2
3263 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3264 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(LHS: X, RHS: -C),
3265 ConstantExpr::getNeg(C: cast<Constant>(Val: Y)));
3266
3267 // X+C2 <u C -> (X & C) == 2C
3268 // iff C == -(C2)
3269 // C2 is a power of 2
3270 if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)
3271 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(LHS: X, RHS: C),
3272 ConstantInt::get(Ty, V: C * 2));
3273
3274 // X+C >u C2 -> (X & ~C2) != C
3275 // iff C & C2 == 0
3276 // C2+1 is a power of 2
3277 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3278 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(LHS: X, RHS: ~C),
3279 ConstantExpr::getNeg(C: cast<Constant>(Val: Y)));
3280
3281 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3282 // to the ult form.
3283 // X+C2 >u C -> X+(C2-C-1) <u ~C
3284 if (Pred == ICmpInst::ICMP_UGT)
3285 return new ICmpInst(ICmpInst::ICMP_ULT,
3286 Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: *C2 - C - 1)),
3287 ConstantInt::get(Ty, V: ~C));
3288
3289 // zext(V) + C2 pred C -> V + C3 pred' C4
3290 Value *V;
3291 if (match(V: X, P: m_ZExt(Op: m_Value(V)))) {
3292 Type *NewCmpTy = V->getType();
3293 unsigned NewCmpBW = NewCmpTy->getScalarSizeInBits();
3294 if (shouldChangeType(From: Ty, To: NewCmpTy)) {
3295 ConstantRange SrcCR = CR.truncate(BitWidth: NewCmpBW, NoWrapKind: TruncInst::NoUnsignedWrap);
3296 CmpInst::Predicate EquivPred;
3297 APInt EquivInt;
3298 APInt EquivOffset;
3299
3300 SrcCR.getEquivalentICmp(Pred&: EquivPred, RHS&: EquivInt, Offset&: EquivOffset);
3301 return new ICmpInst(
3302 EquivPred,
3303 EquivOffset.isZero()
3304 ? V
3305 : Builder.CreateAdd(LHS: V, RHS: ConstantInt::get(Ty: NewCmpTy, V: EquivOffset)),
3306 ConstantInt::get(Ty: NewCmpTy, V: EquivInt));
3307 }
3308 }
3309
3310 return nullptr;
3311}
3312
3313bool InstCombinerImpl::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS,
3314 Value *&RHS, ConstantInt *&Less,
3315 ConstantInt *&Equal,
3316 ConstantInt *&Greater) {
3317 // TODO: Generalize this to work with other comparison idioms or ensure
3318 // they get canonicalized into this form.
3319
3320 // select i1 (a == b),
3321 // i32 Equal,
3322 // i32 (select i1 (a < b), i32 Less, i32 Greater)
3323 // where Equal, Less and Greater are placeholders for any three constants.
3324 CmpPredicate PredA;
3325 if (!match(V: SI->getCondition(), P: m_ICmp(Pred&: PredA, L: m_Value(V&: LHS), R: m_Value(V&: RHS))) ||
3326 !ICmpInst::isEquality(P: PredA))
3327 return false;
3328 Value *EqualVal = SI->getTrueValue();
3329 Value *UnequalVal = SI->getFalseValue();
3330 // We still can get non-canonical predicate here, so canonicalize.
3331 if (PredA == ICmpInst::ICMP_NE)
3332 std::swap(a&: EqualVal, b&: UnequalVal);
3333 if (!match(V: EqualVal, P: m_ConstantInt(CI&: Equal)))
3334 return false;
3335 CmpPredicate PredB;
3336 Value *LHS2, *RHS2;
3337 if (!match(V: UnequalVal, P: m_Select(C: m_ICmp(Pred&: PredB, L: m_Value(V&: LHS2), R: m_Value(V&: RHS2)),
3338 L: m_ConstantInt(CI&: Less), R: m_ConstantInt(CI&: Greater))))
3339 return false;
3340 // We can get predicate mismatch here, so canonicalize if possible:
3341 // First, ensure that 'LHS' match.
3342 if (LHS2 != LHS) {
3343 // x sgt y <--> y slt x
3344 std::swap(a&: LHS2, b&: RHS2);
3345 PredB = ICmpInst::getSwappedPredicate(pred: PredB);
3346 }
3347 if (LHS2 != LHS)
3348 return false;
3349 // We also need to canonicalize 'RHS'.
3350 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(Val: RHS2)) {
3351 // x sgt C-1 <--> x sge C <--> not(x slt C)
3352 auto FlippedStrictness =
3353 getFlippedStrictnessPredicateAndConstant(Pred: PredB, C: cast<Constant>(Val: RHS2));
3354 if (!FlippedStrictness)
3355 return false;
3356 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3357 "basic correctness failure");
3358 RHS2 = FlippedStrictness->second;
3359 // And kind-of perform the result swap.
3360 std::swap(a&: Less, b&: Greater);
3361 PredB = ICmpInst::ICMP_SLT;
3362 }
3363 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3364}
3365
3366Instruction *InstCombinerImpl::foldICmpSelectConstant(ICmpInst &Cmp,
3367 SelectInst *Select,
3368 ConstantInt *C) {
3369
3370 assert(C && "Cmp RHS should be a constant int!");
3371 // If we're testing a constant value against the result of a three way
3372 // comparison, the result can be expressed directly in terms of the
3373 // original values being compared. Note: We could possibly be more
3374 // aggressive here and remove the hasOneUse test. The original select is
3375 // really likely to simplify or sink when we remove a test of the result.
3376 Value *OrigLHS, *OrigRHS;
3377 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3378 if (Cmp.hasOneUse() &&
3379 matchThreeWayIntCompare(SI: Select, LHS&: OrigLHS, RHS&: OrigRHS, Less&: C1LessThan, Equal&: C2Equal,
3380 Greater&: C3GreaterThan)) {
3381 assert(C1LessThan && C2Equal && C3GreaterThan);
3382
3383 bool TrueWhenLessThan = ICmpInst::compare(
3384 LHS: C1LessThan->getValue(), RHS: C->getValue(), Pred: Cmp.getPredicate());
3385 bool TrueWhenEqual = ICmpInst::compare(LHS: C2Equal->getValue(), RHS: C->getValue(),
3386 Pred: Cmp.getPredicate());
3387 bool TrueWhenGreaterThan = ICmpInst::compare(
3388 LHS: C3GreaterThan->getValue(), RHS: C->getValue(), Pred: Cmp.getPredicate());
3389
3390 // This generates the new instruction that will replace the original Cmp
3391 // Instruction. Instead of enumerating the various combinations when
3392 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3393 // false, we rely on chaining of ORs and future passes of InstCombine to
3394 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3395
3396 // When none of the three constants satisfy the predicate for the RHS (C),
3397 // the entire original Cmp can be simplified to a false.
3398 Value *Cond = Builder.getFalse();
3399 if (TrueWhenLessThan)
3400 Cond = Builder.CreateOr(
3401 LHS: Cond, RHS: Builder.CreateICmp(P: ICmpInst::ICMP_SLT, LHS: OrigLHS, RHS: OrigRHS));
3402 if (TrueWhenEqual)
3403 Cond = Builder.CreateOr(
3404 LHS: Cond, RHS: Builder.CreateICmp(P: ICmpInst::ICMP_EQ, LHS: OrigLHS, RHS: OrigRHS));
3405 if (TrueWhenGreaterThan)
3406 Cond = Builder.CreateOr(
3407 LHS: Cond, RHS: Builder.CreateICmp(P: ICmpInst::ICMP_SGT, LHS: OrigLHS, RHS: OrigRHS));
3408
3409 return replaceInstUsesWith(I&: Cmp, V: Cond);
3410 }
3411 return nullptr;
3412}
3413
3414Instruction *InstCombinerImpl::foldICmpBitCast(ICmpInst &Cmp) {
3415 auto *Bitcast = dyn_cast<BitCastInst>(Val: Cmp.getOperand(i_nocapture: 0));
3416 if (!Bitcast)
3417 return nullptr;
3418
3419 ICmpInst::Predicate Pred = Cmp.getPredicate();
3420 Value *Op1 = Cmp.getOperand(i_nocapture: 1);
3421 Value *BCSrcOp = Bitcast->getOperand(i_nocapture: 0);
3422 Type *SrcType = Bitcast->getSrcTy();
3423 Type *DstType = Bitcast->getType();
3424
3425 // Make sure the bitcast doesn't change between scalar and vector and
3426 // doesn't change the number of vector elements.
3427 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3428 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3429 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3430 Value *X;
3431 if (match(V: BCSrcOp, P: m_SIToFP(Op: m_Value(V&: X)))) {
3432 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3433 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3434 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3435 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3436 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3437 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3438 match(V: Op1, P: m_Zero()))
3439 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: X->getType()));
3440
3441 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3442 if (Pred == ICmpInst::ICMP_SLT && match(V: Op1, P: m_One()))
3443 return new ICmpInst(Pred, X, ConstantInt::get(Ty: X->getType(), V: 1));
3444
3445 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3446 if (Pred == ICmpInst::ICMP_SGT && match(V: Op1, P: m_AllOnes()))
3447 return new ICmpInst(Pred, X,
3448 ConstantInt::getAllOnesValue(Ty: X->getType()));
3449 }
3450
3451 // Zero-equality checks are preserved through unsigned floating-point casts:
3452 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3453 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3454 if (match(V: BCSrcOp, P: m_UIToFP(Op: m_Value(V&: X))))
3455 if (Cmp.isEquality() && match(V: Op1, P: m_Zero()))
3456 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: X->getType()));
3457
3458 const APInt *C;
3459 bool TrueIfSigned;
3460 if (match(V: Op1, P: m_APInt(Res&: C)) && Bitcast->hasOneUse()) {
3461 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3462 // the FP extend/truncate because that cast does not change the sign-bit.
3463 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3464 // The sign-bit is always the most significant bit in those types.
3465 if (isSignBitCheck(Pred, RHS: *C, TrueIfSigned) &&
3466 (match(V: BCSrcOp, P: m_FPExt(Op: m_Value(V&: X))) ||
3467 match(V: BCSrcOp, P: m_FPTrunc(Op: m_Value(V&: X))))) {
3468 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3469 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3470 Type *XType = X->getType();
3471
3472 // We can't currently handle Power style floating point operations here.
3473 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3474 Type *NewType = Builder.getIntNTy(N: XType->getScalarSizeInBits());
3475 if (auto *XVTy = dyn_cast<VectorType>(Val: XType))
3476 NewType = VectorType::get(ElementType: NewType, EC: XVTy->getElementCount());
3477 Value *NewBitcast = Builder.CreateBitCast(V: X, DestTy: NewType);
3478 if (TrueIfSigned)
3479 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3480 ConstantInt::getNullValue(Ty: NewType));
3481 else
3482 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3483 ConstantInt::getAllOnesValue(Ty: NewType));
3484 }
3485 }
3486
3487 // icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)
3488 Type *FPType = SrcType->getScalarType();
3489 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3490 Kind: Attribute::NoImplicitFloat) &&
3491 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3492 FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();
3493 if (Mask & (fcInf | fcZero)) {
3494 if (Pred == ICmpInst::ICMP_NE)
3495 Mask = ~Mask;
3496 return replaceInstUsesWith(I&: Cmp,
3497 V: Builder.createIsFPClass(FPNum: BCSrcOp, Test: Mask));
3498 }
3499 }
3500 }
3501 }
3502
3503 const APInt *C;
3504 if (!match(V: Cmp.getOperand(i_nocapture: 1), P: m_APInt(Res&: C)) || !DstType->isIntegerTy() ||
3505 !SrcType->isIntOrIntVectorTy())
3506 return nullptr;
3507
3508 // If this is checking if all elements of a vector compare are set or not,
3509 // invert the casted vector equality compare and test if all compare
3510 // elements are clear or not. Compare against zero is generally easier for
3511 // analysis and codegen.
3512 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3513 // Example: are all elements equal? --> are zero elements not equal?
3514 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3515 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3516 if (Value *NotBCSrcOp =
3517 getFreelyInverted(V: BCSrcOp, WillInvertAllUses: BCSrcOp->hasOneUse(), Builder: &Builder)) {
3518 Value *Cast = Builder.CreateBitCast(V: NotBCSrcOp, DestTy: DstType);
3519 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(Ty: DstType));
3520 }
3521 }
3522
3523 // If this is checking if all elements of an extended vector are clear or not,
3524 // compare in a narrow type to eliminate the extend:
3525 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3526 Value *X;
3527 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3528 match(V: BCSrcOp, P: m_ZExtOrSExt(Op: m_Value(V&: X)))) {
3529 if (auto *VecTy = dyn_cast<FixedVectorType>(Val: X->getType())) {
3530 Type *NewType = Builder.getIntNTy(N: VecTy->getPrimitiveSizeInBits());
3531 Value *NewCast = Builder.CreateBitCast(V: X, DestTy: NewType);
3532 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(Ty: NewType));
3533 }
3534 }
3535
3536 // Folding: icmp <pred> iN X, C
3537 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3538 // and C is a splat of a K-bit pattern
3539 // and SC is a constant vector = <C', C', C', ..., C'>
3540 // Into:
3541 // %E = extractelement <M x iK> %vec, i32 C'
3542 // icmp <pred> iK %E, trunc(C)
3543 Value *Vec;
3544 ArrayRef<int> Mask;
3545 if (match(V: BCSrcOp, P: m_Shuffle(v1: m_Value(V&: Vec), v2: m_Undef(), mask: m_Mask(Mask)))) {
3546 // Check whether every element of Mask is the same constant
3547 if (all_equal(Range&: Mask)) {
3548 auto *VecTy = cast<VectorType>(Val: SrcType);
3549 auto *EltTy = cast<IntegerType>(Val: VecTy->getElementType());
3550 if (C->isSplat(SplatSizeInBits: EltTy->getBitWidth())) {
3551 // Fold the icmp based on the value of C
3552 // If C is M copies of an iK sized bit pattern,
3553 // then:
3554 // => %E = extractelement <N x iK> %vec, i32 Elem
3555 // icmp <pred> iK %SplatVal, <pattern>
3556 Value *Elem = Builder.getInt32(C: Mask[0]);
3557 Value *Extract = Builder.CreateExtractElement(Vec, Idx: Elem);
3558 Value *NewC = ConstantInt::get(Ty: EltTy, V: C->trunc(width: EltTy->getBitWidth()));
3559 return new ICmpInst(Pred, Extract, NewC);
3560 }
3561 }
3562 }
3563 return nullptr;
3564}
3565
3566/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3567/// where X is some kind of instruction.
3568Instruction *InstCombinerImpl::foldICmpInstWithConstant(ICmpInst &Cmp) {
3569 const APInt *C;
3570
3571 if (match(V: Cmp.getOperand(i_nocapture: 1), P: m_APInt(Res&: C))) {
3572 if (auto *BO = dyn_cast<BinaryOperator>(Val: Cmp.getOperand(i_nocapture: 0)))
3573 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, C: *C))
3574 return I;
3575
3576 if (auto *SI = dyn_cast<SelectInst>(Val: Cmp.getOperand(i_nocapture: 0)))
3577 // For now, we only support constant integers while folding the
3578 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3579 // similar to the cases handled by binary ops above.
3580 if (auto *ConstRHS = dyn_cast<ConstantInt>(Val: Cmp.getOperand(i_nocapture: 1)))
3581 if (Instruction *I = foldICmpSelectConstant(Cmp, Select: SI, C: ConstRHS))
3582 return I;
3583
3584 if (auto *TI = dyn_cast<TruncInst>(Val: Cmp.getOperand(i_nocapture: 0)))
3585 if (Instruction *I = foldICmpTruncConstant(Cmp, Trunc: TI, C: *C))
3586 return I;
3587
3588 if (auto *II = dyn_cast<IntrinsicInst>(Val: Cmp.getOperand(i_nocapture: 0)))
3589 if (Instruction *I = foldICmpIntrinsicWithConstant(ICI&: Cmp, II, C: *C))
3590 return I;
3591
3592 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3593 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3594 // TODO: This checks one-use, but that is not strictly necessary.
3595 Value *Cmp0 = Cmp.getOperand(i_nocapture: 0);
3596 Value *X, *Y;
3597 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3598 (match(V: Cmp0,
3599 P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::ssub_with_overflow>(
3600 Op0: m_Value(V&: X), Op1: m_Value(V&: Y)))) ||
3601 match(V: Cmp0,
3602 P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::usub_with_overflow>(
3603 Op0: m_Value(V&: X), Op1: m_Value(V&: Y))))))
3604 return new ICmpInst(Cmp.getPredicate(), X, Y);
3605 }
3606
3607 if (match(V: Cmp.getOperand(i_nocapture: 1), P: m_APIntAllowPoison(Res&: C)))
3608 return foldICmpInstWithConstantAllowPoison(Cmp, C: *C);
3609
3610 return nullptr;
3611}
3612
3613/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3614/// icmp eq/ne BO, C.
3615Instruction *InstCombinerImpl::foldICmpBinOpEqualityWithConstant(
3616 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3617 // TODO: Some of these folds could work with arbitrary constants, but this
3618 // function is limited to scalar and vector splat constants.
3619 if (!Cmp.isEquality())
3620 return nullptr;
3621
3622 ICmpInst::Predicate Pred = Cmp.getPredicate();
3623 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3624 Constant *RHS = cast<Constant>(Val: Cmp.getOperand(i_nocapture: 1));
3625 Value *BOp0 = BO->getOperand(i_nocapture: 0), *BOp1 = BO->getOperand(i_nocapture: 1);
3626
3627 switch (BO->getOpcode()) {
3628 case Instruction::SRem:
3629 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3630 if (C.isZero() && BO->hasOneUse()) {
3631 const APInt *BOC;
3632 if (match(V: BOp1, P: m_APInt(Res&: BOC)) && BOC->sgt(RHS: 1) && BOC->isPowerOf2()) {
3633 Value *NewRem = Builder.CreateURem(LHS: BOp0, RHS: BOp1, Name: BO->getName());
3634 return new ICmpInst(Pred, NewRem,
3635 Constant::getNullValue(Ty: BO->getType()));
3636 }
3637 }
3638 break;
3639 case Instruction::Add: {
3640 // (A + C2) == C --> A == (C - C2)
3641 // (A + C2) != C --> A != (C - C2)
3642 // TODO: Remove the one-use limitation? See discussion in D58633.
3643 if (Constant *C2 = dyn_cast<Constant>(Val: BOp1)) {
3644 if (BO->hasOneUse())
3645 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(C1: RHS, C2));
3646 } else if (C.isZero()) {
3647 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3648 // efficiently invertible, or if the add has just this one use.
3649 if (Value *NegVal = dyn_castNegVal(V: BOp1))
3650 return new ICmpInst(Pred, BOp0, NegVal);
3651 if (Value *NegVal = dyn_castNegVal(V: BOp0))
3652 return new ICmpInst(Pred, NegVal, BOp1);
3653 if (BO->hasOneUse()) {
3654 // (add nuw A, B) != 0 -> (or A, B) != 0
3655 if (match(V: BO, P: m_NUWAdd(L: m_Value(), R: m_Value()))) {
3656 Value *Or = Builder.CreateOr(LHS: BOp0, RHS: BOp1);
3657 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty: BO->getType()));
3658 }
3659 Value *Neg = Builder.CreateNeg(V: BOp1);
3660 Neg->takeName(V: BO);
3661 return new ICmpInst(Pred, BOp0, Neg);
3662 }
3663 }
3664 break;
3665 }
3666 case Instruction::Xor:
3667 if (Constant *BOC = dyn_cast<Constant>(Val: BOp1)) {
3668 // For the xor case, we can xor two constants together, eliminating
3669 // the explicit xor.
3670 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(C1: RHS, C2: BOC));
3671 } else if (C.isZero()) {
3672 // Replace ((xor A, B) != 0) with (A != B)
3673 return new ICmpInst(Pred, BOp0, BOp1);
3674 }
3675 break;
3676 case Instruction::Or: {
3677 const APInt *BOC;
3678 if (match(V: BOp1, P: m_APInt(Res&: BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3679 // Comparing if all bits outside of a constant mask are set?
3680 // Replace (X | C) == -1 with (X & ~C) == ~C.
3681 // This removes the -1 constant.
3682 Constant *NotBOC = ConstantExpr::getNot(C: cast<Constant>(Val: BOp1));
3683 Value *And = Builder.CreateAnd(LHS: BOp0, RHS: NotBOC);
3684 return new ICmpInst(Pred, And, NotBOC);
3685 }
3686 // (icmp eq (or (select cond, 0, NonZero), Other), 0)
3687 // -> (and cond, (icmp eq Other, 0))
3688 // (icmp ne (or (select cond, NonZero, 0), Other), 0)
3689 // -> (or cond, (icmp ne Other, 0))
3690 Value *Cond, *TV, *FV, *Other, *Sel;
3691 if (C.isZero() &&
3692 match(V: BO,
3693 P: m_OneUse(SubPattern: m_c_Or(L: m_CombineAnd(L: m_Value(V&: Sel),
3694 R: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: TV),
3695 R: m_Value(V&: FV))),
3696 R: m_Value(V&: Other)))) &&
3697 Cond->getType() == Cmp.getType()) {
3698 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
3699 // Easy case is if eq/ne matches whether 0 is trueval/falseval.
3700 if (Pred == ICmpInst::ICMP_EQ
3701 ? (match(V: TV, P: m_Zero()) && isKnownNonZero(V: FV, Q))
3702 : (match(V: FV, P: m_Zero()) && isKnownNonZero(V: TV, Q))) {
3703 Value *Cmp = Builder.CreateICmp(
3704 P: Pred, LHS: Other, RHS: Constant::getNullValue(Ty: Other->getType()));
3705 return BinaryOperator::Create(
3706 Op: Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, S1: Cmp,
3707 S2: Cond);
3708 }
3709 // Harder case is if eq/ne matches whether 0 is falseval/trueval. In this
3710 // case we need to invert the select condition so we need to be careful to
3711 // avoid creating extra instructions.
3712 // (icmp ne (or (select cond, 0, NonZero), Other), 0)
3713 // -> (or (not cond), (icmp ne Other, 0))
3714 // (icmp eq (or (select cond, NonZero, 0), Other), 0)
3715 // -> (and (not cond), (icmp eq Other, 0))
3716 //
3717 // Only do this if the inner select has one use, in which case we are
3718 // replacing `select` with `(not cond)`. Otherwise, we will create more
3719 // uses. NB: Trying to freely invert cond doesn't make sense here, as if
3720 // cond was freely invertable, the select arms would have been inverted.
3721 if (Sel->hasOneUse() &&
3722 (Pred == ICmpInst::ICMP_EQ
3723 ? (match(V: FV, P: m_Zero()) && isKnownNonZero(V: TV, Q))
3724 : (match(V: TV, P: m_Zero()) && isKnownNonZero(V: FV, Q)))) {
3725 Value *NotCond = Builder.CreateNot(V: Cond);
3726 Value *Cmp = Builder.CreateICmp(
3727 P: Pred, LHS: Other, RHS: Constant::getNullValue(Ty: Other->getType()));
3728 return BinaryOperator::Create(
3729 Op: Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, S1: Cmp,
3730 S2: NotCond);
3731 }
3732 }
3733 break;
3734 }
3735 case Instruction::UDiv:
3736 case Instruction::SDiv:
3737 if (BO->isExact()) {
3738 // div exact X, Y eq/ne 0 -> X eq/ne 0
3739 // div exact X, Y eq/ne 1 -> X eq/ne Y
3740 // div exact X, Y eq/ne C ->
3741 // if Y * C never-overflow && OneUse:
3742 // -> Y * C eq/ne X
3743 if (C.isZero())
3744 return new ICmpInst(Pred, BOp0, Constant::getNullValue(Ty: BO->getType()));
3745 else if (C.isOne())
3746 return new ICmpInst(Pred, BOp0, BOp1);
3747 else if (BO->hasOneUse()) {
3748 OverflowResult OR = computeOverflow(
3749 BinaryOp: Instruction::Mul, IsSigned: BO->getOpcode() == Instruction::SDiv, LHS: BOp1,
3750 RHS: Cmp.getOperand(i_nocapture: 1), CxtI: BO);
3751 if (OR == OverflowResult::NeverOverflows) {
3752 Value *YC =
3753 Builder.CreateMul(LHS: BOp1, RHS: ConstantInt::get(Ty: BO->getType(), V: C));
3754 return new ICmpInst(Pred, YC, BOp0);
3755 }
3756 }
3757 }
3758 if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3759 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3760 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3761 return new ICmpInst(NewPred, BOp1, BOp0);
3762 }
3763 break;
3764 default:
3765 break;
3766 }
3767 return nullptr;
3768}
3769
3770static Instruction *foldCtpopPow2Test(ICmpInst &I, IntrinsicInst *CtpopLhs,
3771 const APInt &CRhs,
3772 InstCombiner::BuilderTy &Builder,
3773 const SimplifyQuery &Q) {
3774 assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3775 "Non-ctpop intrin in ctpop fold");
3776 if (!CtpopLhs->hasOneUse())
3777 return nullptr;
3778
3779 // Power of 2 test:
3780 // isPow2OrZero : ctpop(X) u< 2
3781 // isPow2 : ctpop(X) == 1
3782 // NotPow2OrZero: ctpop(X) u> 1
3783 // NotPow2 : ctpop(X) != 1
3784 // If we know any bit of X can be folded to:
3785 // IsPow2 : X & (~Bit) == 0
3786 // NotPow2 : X & (~Bit) != 0
3787 const ICmpInst::Predicate Pred = I.getPredicate();
3788 if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3789 (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3790 Value *Op = CtpopLhs->getArgOperand(i: 0);
3791 KnownBits OpKnown = computeKnownBits(V: Op, DL: Q.DL, AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT);
3792 // No need to check for count > 1, that should be already constant folded.
3793 if (OpKnown.countMinPopulation() == 1) {
3794 Value *And = Builder.CreateAnd(
3795 LHS: Op, RHS: Constant::getIntegerValue(Ty: Op->getType(), V: ~(OpKnown.One)));
3796 return new ICmpInst(
3797 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3798 ? ICmpInst::ICMP_EQ
3799 : ICmpInst::ICMP_NE,
3800 And, Constant::getNullValue(Ty: Op->getType()));
3801 }
3802 }
3803
3804 return nullptr;
3805}
3806
3807/// Fold an equality icmp with LLVM intrinsic and constant operand.
3808Instruction *InstCombinerImpl::foldICmpEqIntrinsicWithConstant(
3809 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3810 Type *Ty = II->getType();
3811 unsigned BitWidth = C.getBitWidth();
3812 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3813
3814 switch (II->getIntrinsicID()) {
3815 case Intrinsic::abs:
3816 // abs(A) == 0 -> A == 0
3817 // abs(A) == INT_MIN -> A == INT_MIN
3818 if (C.isZero() || C.isMinSignedValue())
3819 return new ICmpInst(Pred, II->getArgOperand(i: 0), ConstantInt::get(Ty, V: C));
3820 break;
3821
3822 case Intrinsic::bswap:
3823 // bswap(A) == C -> A == bswap(C)
3824 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3825 ConstantInt::get(Ty, V: C.byteSwap()));
3826
3827 case Intrinsic::bitreverse:
3828 // bitreverse(A) == C -> A == bitreverse(C)
3829 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3830 ConstantInt::get(Ty, V: C.reverseBits()));
3831
3832 case Intrinsic::ctlz:
3833 case Intrinsic::cttz: {
3834 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3835 if (C == BitWidth)
3836 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3837 ConstantInt::getNullValue(Ty));
3838
3839 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3840 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3841 // Limit to one use to ensure we don't increase instruction count.
3842 unsigned Num = C.getLimitedValue(Limit: BitWidth);
3843 if (Num != BitWidth && II->hasOneUse()) {
3844 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3845 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: Num + 1)
3846 : APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: Num + 1);
3847 APInt Mask2 = IsTrailing
3848 ? APInt::getOneBitSet(numBits: BitWidth, BitNo: Num)
3849 : APInt::getOneBitSet(numBits: BitWidth, BitNo: BitWidth - Num - 1);
3850 return new ICmpInst(Pred, Builder.CreateAnd(LHS: II->getArgOperand(i: 0), RHS: Mask1),
3851 ConstantInt::get(Ty, V: Mask2));
3852 }
3853 break;
3854 }
3855
3856 case Intrinsic::ctpop: {
3857 // popcount(A) == 0 -> A == 0 and likewise for !=
3858 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3859 bool IsZero = C.isZero();
3860 if (IsZero || C == BitWidth)
3861 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3862 IsZero ? Constant::getNullValue(Ty)
3863 : Constant::getAllOnesValue(Ty));
3864
3865 break;
3866 }
3867
3868 case Intrinsic::fshl:
3869 case Intrinsic::fshr:
3870 if (II->getArgOperand(i: 0) == II->getArgOperand(i: 1)) {
3871 const APInt *RotAmtC;
3872 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3873 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3874 if (match(V: II->getArgOperand(i: 2), P: m_APInt(Res&: RotAmtC)))
3875 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3876 II->getIntrinsicID() == Intrinsic::fshl
3877 ? ConstantInt::get(Ty, V: C.rotr(rotateAmt: *RotAmtC))
3878 : ConstantInt::get(Ty, V: C.rotl(rotateAmt: *RotAmtC)));
3879 }
3880 break;
3881
3882 case Intrinsic::umax:
3883 case Intrinsic::uadd_sat: {
3884 // uadd.sat(a, b) == 0 -> (a | b) == 0
3885 // umax(a, b) == 0 -> (a | b) == 0
3886 if (C.isZero() && II->hasOneUse()) {
3887 Value *Or = Builder.CreateOr(LHS: II->getArgOperand(i: 0), RHS: II->getArgOperand(i: 1));
3888 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
3889 }
3890 break;
3891 }
3892
3893 case Intrinsic::ssub_sat:
3894 // ssub.sat(a, b) == 0 -> a == b
3895 //
3896 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
3897 // (because 1 saturates to 0). Just skip the optimization for i1.
3898 if (C.isZero() && II->getType()->getScalarSizeInBits() > 1)
3899 return new ICmpInst(Pred, II->getArgOperand(i: 0), II->getArgOperand(i: 1));
3900 break;
3901 case Intrinsic::usub_sat: {
3902 // usub.sat(a, b) == 0 -> a <= b
3903 if (C.isZero()) {
3904 ICmpInst::Predicate NewPred =
3905 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3906 return new ICmpInst(NewPred, II->getArgOperand(i: 0), II->getArgOperand(i: 1));
3907 }
3908 break;
3909 }
3910 default:
3911 break;
3912 }
3913
3914 return nullptr;
3915}
3916
3917/// Fold an icmp with LLVM intrinsics
3918static Instruction *
3919foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp,
3920 InstCombiner::BuilderTy &Builder) {
3921 assert(Cmp.isEquality());
3922
3923 ICmpInst::Predicate Pred = Cmp.getPredicate();
3924 Value *Op0 = Cmp.getOperand(i_nocapture: 0);
3925 Value *Op1 = Cmp.getOperand(i_nocapture: 1);
3926 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Val: Op0);
3927 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Val: Op1);
3928 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
3929 return nullptr;
3930
3931 switch (IIOp0->getIntrinsicID()) {
3932 case Intrinsic::bswap:
3933 case Intrinsic::bitreverse:
3934 // If both operands are byte-swapped or bit-reversed, just compare the
3935 // original values.
3936 return new ICmpInst(Pred, IIOp0->getOperand(i_nocapture: 0), IIOp1->getOperand(i_nocapture: 0));
3937 case Intrinsic::fshl:
3938 case Intrinsic::fshr: {
3939 // If both operands are rotated by same amount, just compare the
3940 // original values.
3941 if (IIOp0->getOperand(i_nocapture: 0) != IIOp0->getOperand(i_nocapture: 1))
3942 break;
3943 if (IIOp1->getOperand(i_nocapture: 0) != IIOp1->getOperand(i_nocapture: 1))
3944 break;
3945 if (IIOp0->getOperand(i_nocapture: 2) == IIOp1->getOperand(i_nocapture: 2))
3946 return new ICmpInst(Pred, IIOp0->getOperand(i_nocapture: 0), IIOp1->getOperand(i_nocapture: 0));
3947
3948 // rotate(X, AmtX) == rotate(Y, AmtY)
3949 // -> rotate(X, AmtX - AmtY) == Y
3950 // Do this if either both rotates have one use or if only one has one use
3951 // and AmtX/AmtY are constants.
3952 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
3953 if (OneUses == 2 ||
3954 (OneUses == 1 && match(V: IIOp0->getOperand(i_nocapture: 2), P: m_ImmConstant()) &&
3955 match(V: IIOp1->getOperand(i_nocapture: 2), P: m_ImmConstant()))) {
3956 Value *SubAmt =
3957 Builder.CreateSub(LHS: IIOp0->getOperand(i_nocapture: 2), RHS: IIOp1->getOperand(i_nocapture: 2));
3958 Value *CombinedRotate = Builder.CreateIntrinsic(
3959 RetTy: Op0->getType(), ID: IIOp0->getIntrinsicID(),
3960 Args: {IIOp0->getOperand(i_nocapture: 0), IIOp0->getOperand(i_nocapture: 0), SubAmt});
3961 return new ICmpInst(Pred, IIOp1->getOperand(i_nocapture: 0), CombinedRotate);
3962 }
3963 } break;
3964 default:
3965 break;
3966 }
3967
3968 return nullptr;
3969}
3970
3971/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3972/// where X is some kind of instruction and C is AllowPoison.
3973/// TODO: Move more folds which allow poison to this function.
3974Instruction *
3975InstCombinerImpl::foldICmpInstWithConstantAllowPoison(ICmpInst &Cmp,
3976 const APInt &C) {
3977 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3978 if (auto *II = dyn_cast<IntrinsicInst>(Val: Cmp.getOperand(i_nocapture: 0))) {
3979 switch (II->getIntrinsicID()) {
3980 default:
3981 break;
3982 case Intrinsic::fshl:
3983 case Intrinsic::fshr:
3984 if (Cmp.isEquality() && II->getArgOperand(i: 0) == II->getArgOperand(i: 1)) {
3985 // (rot X, ?) == 0/-1 --> X == 0/-1
3986 if (C.isZero() || C.isAllOnes())
3987 return new ICmpInst(Pred, II->getArgOperand(i: 0), Cmp.getOperand(i_nocapture: 1));
3988 }
3989 break;
3990 }
3991 }
3992
3993 return nullptr;
3994}
3995
3996/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
3997Instruction *InstCombinerImpl::foldICmpBinOpWithConstant(ICmpInst &Cmp,
3998 BinaryOperator *BO,
3999 const APInt &C) {
4000 switch (BO->getOpcode()) {
4001 case Instruction::Xor:
4002 if (Instruction *I = foldICmpXorConstant(Cmp, Xor: BO, C))
4003 return I;
4004 break;
4005 case Instruction::And:
4006 if (Instruction *I = foldICmpAndConstant(Cmp, And: BO, C))
4007 return I;
4008 break;
4009 case Instruction::Or:
4010 if (Instruction *I = foldICmpOrConstant(Cmp, Or: BO, C))
4011 return I;
4012 break;
4013 case Instruction::Mul:
4014 if (Instruction *I = foldICmpMulConstant(Cmp, Mul: BO, C))
4015 return I;
4016 break;
4017 case Instruction::Shl:
4018 if (Instruction *I = foldICmpShlConstant(Cmp, Shl: BO, C))
4019 return I;
4020 break;
4021 case Instruction::LShr:
4022 case Instruction::AShr:
4023 if (Instruction *I = foldICmpShrConstant(Cmp, Shr: BO, C))
4024 return I;
4025 break;
4026 case Instruction::SRem:
4027 if (Instruction *I = foldICmpSRemConstant(Cmp, SRem: BO, C))
4028 return I;
4029 break;
4030 case Instruction::UDiv:
4031 if (Instruction *I = foldICmpUDivConstant(Cmp, UDiv: BO, C))
4032 return I;
4033 [[fallthrough]];
4034 case Instruction::SDiv:
4035 if (Instruction *I = foldICmpDivConstant(Cmp, Div: BO, C))
4036 return I;
4037 break;
4038 case Instruction::Sub:
4039 if (Instruction *I = foldICmpSubConstant(Cmp, Sub: BO, C))
4040 return I;
4041 break;
4042 case Instruction::Add:
4043 if (Instruction *I = foldICmpAddConstant(Cmp, Add: BO, C))
4044 return I;
4045 break;
4046 default:
4047 break;
4048 }
4049
4050 // TODO: These folds could be refactored to be part of the above calls.
4051 if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, C))
4052 return I;
4053
4054 // Fall back to handling `icmp pred (select A ? C1 : C2) binop (select B ? C3
4055 // : C4), C5` pattern, by computing a truth table of the four constant
4056 // variants.
4057 return foldICmpBinOpWithConstantViaTruthTable(Cmp, BO, C);
4058}
4059
4060static Instruction *
4061foldICmpUSubSatOrUAddSatWithConstant(CmpPredicate Pred, SaturatingInst *II,
4062 const APInt &C,
4063 InstCombiner::BuilderTy &Builder) {
4064 // This transform may end up producing more than one instruction for the
4065 // intrinsic, so limit it to one user of the intrinsic.
4066 if (!II->hasOneUse())
4067 return nullptr;
4068
4069 // Let Y = [add/sub]_sat(X, C) pred C2
4070 // SatVal = The saturating value for the operation
4071 // WillWrap = Whether or not the operation will underflow / overflow
4072 // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
4073 // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
4074 //
4075 // When (SatVal pred C2) is true, then
4076 // Y = WillWrap ? true : ((X binop C) pred C2)
4077 // => Y = WillWrap || ((X binop C) pred C2)
4078 // else
4079 // Y = WillWrap ? false : ((X binop C) pred C2)
4080 // => Y = !WillWrap ? ((X binop C) pred C2) : false
4081 // => Y = !WillWrap && ((X binop C) pred C2)
4082 Value *Op0 = II->getOperand(i_nocapture: 0);
4083 Value *Op1 = II->getOperand(i_nocapture: 1);
4084
4085 const APInt *COp1;
4086 // This transform only works when the intrinsic has an integral constant or
4087 // splat vector as the second operand.
4088 if (!match(V: Op1, P: m_APInt(Res&: COp1)))
4089 return nullptr;
4090
4091 APInt SatVal;
4092 switch (II->getIntrinsicID()) {
4093 default:
4094 llvm_unreachable(
4095 "This function only works with usub_sat and uadd_sat for now!");
4096 case Intrinsic::uadd_sat:
4097 SatVal = APInt::getAllOnes(numBits: C.getBitWidth());
4098 break;
4099 case Intrinsic::usub_sat:
4100 SatVal = APInt::getZero(numBits: C.getBitWidth());
4101 break;
4102 }
4103
4104 // Check (SatVal pred C2)
4105 bool SatValCheck = ICmpInst::compare(LHS: SatVal, RHS: C, Pred);
4106
4107 // !WillWrap.
4108 ConstantRange C1 = ConstantRange::makeExactNoWrapRegion(
4109 BinOp: II->getBinaryOp(), Other: *COp1, NoWrapKind: II->getNoWrapKind());
4110
4111 // WillWrap.
4112 if (SatValCheck)
4113 C1 = C1.inverse();
4114
4115 ConstantRange C2 = ConstantRange::makeExactICmpRegion(Pred, Other: C);
4116 if (II->getBinaryOp() == Instruction::Add)
4117 C2 = C2.sub(Other: *COp1);
4118 else
4119 C2 = C2.add(Other: *COp1);
4120
4121 Instruction::BinaryOps CombiningOp =
4122 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4123
4124 std::optional<ConstantRange> Combination;
4125 if (CombiningOp == Instruction::BinaryOps::Or)
4126 Combination = C1.exactUnionWith(CR: C2);
4127 else /* CombiningOp == Instruction::BinaryOps::And */
4128 Combination = C1.exactIntersectWith(CR: C2);
4129
4130 if (!Combination)
4131 return nullptr;
4132
4133 CmpInst::Predicate EquivPred;
4134 APInt EquivInt;
4135 APInt EquivOffset;
4136
4137 Combination->getEquivalentICmp(Pred&: EquivPred, RHS&: EquivInt, Offset&: EquivOffset);
4138
4139 return new ICmpInst(
4140 EquivPred,
4141 Builder.CreateAdd(LHS: Op0, RHS: ConstantInt::get(Ty: Op1->getType(), V: EquivOffset)),
4142 ConstantInt::get(Ty: Op1->getType(), V: EquivInt));
4143}
4144
4145static Instruction *
4146foldICmpOfCmpIntrinsicWithConstant(CmpPredicate Pred, IntrinsicInst *I,
4147 const APInt &C,
4148 InstCombiner::BuilderTy &Builder) {
4149 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4150 switch (Pred) {
4151 case ICmpInst::ICMP_EQ:
4152 case ICmpInst::ICMP_NE:
4153 if (C.isZero())
4154 NewPredicate = Pred;
4155 else if (C.isOne())
4156 NewPredicate =
4157 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
4158 else if (C.isAllOnes())
4159 NewPredicate =
4160 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
4161 break;
4162
4163 case ICmpInst::ICMP_SGT:
4164 if (C.isAllOnes())
4165 NewPredicate = ICmpInst::ICMP_UGE;
4166 else if (C.isZero())
4167 NewPredicate = ICmpInst::ICMP_UGT;
4168 break;
4169
4170 case ICmpInst::ICMP_SLT:
4171 if (C.isZero())
4172 NewPredicate = ICmpInst::ICMP_ULT;
4173 else if (C.isOne())
4174 NewPredicate = ICmpInst::ICMP_ULE;
4175 break;
4176
4177 case ICmpInst::ICMP_ULT:
4178 if (C.ugt(RHS: 1))
4179 NewPredicate = ICmpInst::ICMP_UGE;
4180 break;
4181
4182 case ICmpInst::ICMP_UGT:
4183 if (!C.isZero() && !C.isAllOnes())
4184 NewPredicate = ICmpInst::ICMP_ULT;
4185 break;
4186
4187 default:
4188 break;
4189 }
4190
4191 if (!NewPredicate)
4192 return nullptr;
4193
4194 if (I->getIntrinsicID() == Intrinsic::scmp)
4195 NewPredicate = ICmpInst::getSignedPredicate(Pred: *NewPredicate);
4196 Value *LHS = I->getOperand(i_nocapture: 0);
4197 Value *RHS = I->getOperand(i_nocapture: 1);
4198 return new ICmpInst(*NewPredicate, LHS, RHS);
4199}
4200
4201/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
4202Instruction *InstCombinerImpl::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
4203 IntrinsicInst *II,
4204 const APInt &C) {
4205 ICmpInst::Predicate Pred = Cmp.getPredicate();
4206
4207 // Handle folds that apply for any kind of icmp.
4208 switch (II->getIntrinsicID()) {
4209 default:
4210 break;
4211 case Intrinsic::uadd_sat:
4212 case Intrinsic::usub_sat:
4213 if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(
4214 Pred, II: cast<SaturatingInst>(Val: II), C, Builder))
4215 return Folded;
4216 break;
4217 case Intrinsic::ctpop: {
4218 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
4219 if (Instruction *R = foldCtpopPow2Test(I&: Cmp, CtpopLhs: II, CRhs: C, Builder, Q))
4220 return R;
4221 } break;
4222 case Intrinsic::scmp:
4223 case Intrinsic::ucmp:
4224 if (auto *Folded = foldICmpOfCmpIntrinsicWithConstant(Pred, I: II, C, Builder))
4225 return Folded;
4226 break;
4227 }
4228
4229 if (Cmp.isEquality())
4230 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
4231
4232 Type *Ty = II->getType();
4233 unsigned BitWidth = C.getBitWidth();
4234 switch (II->getIntrinsicID()) {
4235 case Intrinsic::ctpop: {
4236 // (ctpop X > BitWidth - 1) --> X == -1
4237 Value *X = II->getArgOperand(i: 0);
4238 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
4239 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_EQ, S1: X,
4240 S2: ConstantInt::getAllOnesValue(Ty));
4241 // (ctpop X < BitWidth) --> X != -1
4242 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
4243 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_NE, S1: X,
4244 S2: ConstantInt::getAllOnesValue(Ty));
4245 break;
4246 }
4247 case Intrinsic::ctlz: {
4248 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
4249 if (Pred == ICmpInst::ICMP_UGT && C.ult(RHS: BitWidth)) {
4250 unsigned Num = C.getLimitedValue();
4251 APInt Limit = APInt::getOneBitSet(numBits: BitWidth, BitNo: BitWidth - Num - 1);
4252 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_ULT,
4253 S1: II->getArgOperand(i: 0), S2: ConstantInt::get(Ty, V: Limit));
4254 }
4255
4256 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
4257 if (Pred == ICmpInst::ICMP_ULT && C.uge(RHS: 1) && C.ule(RHS: BitWidth)) {
4258 unsigned Num = C.getLimitedValue();
4259 APInt Limit = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: BitWidth - Num);
4260 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_UGT,
4261 S1: II->getArgOperand(i: 0), S2: ConstantInt::get(Ty, V: Limit));
4262 }
4263 break;
4264 }
4265 case Intrinsic::cttz: {
4266 // Limit to one use to ensure we don't increase instruction count.
4267 if (!II->hasOneUse())
4268 return nullptr;
4269
4270 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
4271 if (Pred == ICmpInst::ICMP_UGT && C.ult(RHS: BitWidth)) {
4272 APInt Mask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: C.getLimitedValue() + 1);
4273 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_EQ,
4274 S1: Builder.CreateAnd(LHS: II->getArgOperand(i: 0), RHS: Mask),
4275 S2: ConstantInt::getNullValue(Ty));
4276 }
4277
4278 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
4279 if (Pred == ICmpInst::ICMP_ULT && C.uge(RHS: 1) && C.ule(RHS: BitWidth)) {
4280 APInt Mask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: C.getLimitedValue());
4281 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_NE,
4282 S1: Builder.CreateAnd(LHS: II->getArgOperand(i: 0), RHS: Mask),
4283 S2: ConstantInt::getNullValue(Ty));
4284 }
4285 break;
4286 }
4287 case Intrinsic::ssub_sat:
4288 // ssub.sat(a, b) spred 0 -> a spred b
4289 //
4290 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4291 // (because 1 saturates to 0). Just skip the optimization for i1.
4292 if (ICmpInst::isSigned(predicate: Pred) && C.getBitWidth() > 1) {
4293 if (C.isZero())
4294 return new ICmpInst(Pred, II->getArgOperand(i: 0), II->getArgOperand(i: 1));
4295 // X s<= 0 is cannonicalized to X s< 1
4296 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
4297 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(i: 0),
4298 II->getArgOperand(i: 1));
4299 // X s>= 0 is cannonicalized to X s> -1
4300 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
4301 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(i: 0),
4302 II->getArgOperand(i: 1));
4303 }
4304 break;
4305 case Intrinsic::abs: {
4306 if (!II->hasOneUse())
4307 return nullptr;
4308
4309 Value *X = II->getArgOperand(i: 0);
4310 bool IsIntMinPoison =
4311 cast<ConstantInt>(Val: II->getArgOperand(i: 1))->getValue().isOne();
4312
4313 // If C >= 0:
4314 // abs(X) u> C --> X + C u> 2 * C
4315 if (Pred == CmpInst::ICMP_UGT && C.isNonNegative()) {
4316 return new ICmpInst(ICmpInst::ICMP_UGT,
4317 Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: C)),
4318 ConstantInt::get(Ty, V: 2 * C));
4319 }
4320
4321 // If abs(INT_MIN) is poison and C >= 1:
4322 // abs(X) u< C --> X + (C - 1) u<= 2 * (C - 1)
4323 if (IsIntMinPoison && Pred == CmpInst::ICMP_ULT && C.sge(RHS: 1)) {
4324 return new ICmpInst(ICmpInst::ICMP_ULE,
4325 Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: C - 1)),
4326 ConstantInt::get(Ty, V: 2 * (C - 1)));
4327 }
4328
4329 break;
4330 }
4331 default:
4332 break;
4333 }
4334
4335 return nullptr;
4336}
4337
4338/// Handle icmp with constant (but not simple integer constant) RHS.
4339Instruction *InstCombinerImpl::foldICmpInstWithConstantNotInt(ICmpInst &I) {
4340 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
4341 Constant *RHSC = dyn_cast<Constant>(Val: Op1);
4342 Instruction *LHSI = dyn_cast<Instruction>(Val: Op0);
4343 if (!RHSC || !LHSI)
4344 return nullptr;
4345
4346 switch (LHSI->getOpcode()) {
4347 case Instruction::IntToPtr:
4348 // icmp pred inttoptr(X), null -> icmp pred X, 0
4349 if (RHSC->isNullValue() &&
4350 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(i: 0)->getType())
4351 return new ICmpInst(
4352 I.getPredicate(), LHSI->getOperand(i: 0),
4353 Constant::getNullValue(Ty: LHSI->getOperand(i: 0)->getType()));
4354 break;
4355
4356 case Instruction::Load:
4357 // Try to optimize things like "A[i] > 4" to index computations.
4358 if (GetElementPtrInst *GEP =
4359 dyn_cast<GetElementPtrInst>(Val: LHSI->getOperand(i: 0)))
4360 if (Instruction *Res =
4361 foldCmpLoadFromIndexedGlobal(LI: cast<LoadInst>(Val: LHSI), GEP, ICI&: I))
4362 return Res;
4363 break;
4364 }
4365
4366 return nullptr;
4367}
4368
4369Instruction *InstCombinerImpl::foldSelectICmp(CmpPredicate Pred, SelectInst *SI,
4370 Value *RHS, const ICmpInst &I) {
4371 // Try to fold the comparison into the select arms, which will cause the
4372 // select to be converted into a logical and/or.
4373 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
4374 if (Value *Res = simplifyICmpInst(Pred, LHS: Op, RHS, Q: SQ))
4375 return Res;
4376 if (std::optional<bool> Impl = isImpliedCondition(
4377 LHS: SI->getCondition(), RHSPred: Pred, RHSOp0: Op, RHSOp1: RHS, DL, LHSIsTrue: SelectCondIsTrue))
4378 return ConstantInt::get(Ty: I.getType(), V: *Impl);
4379 return nullptr;
4380 };
4381
4382 ConstantInt *CI = nullptr;
4383 Value *Op1 = SimplifyOp(SI->getOperand(i_nocapture: 1), true);
4384 if (Op1)
4385 CI = dyn_cast<ConstantInt>(Val: Op1);
4386
4387 Value *Op2 = SimplifyOp(SI->getOperand(i_nocapture: 2), false);
4388 if (Op2)
4389 CI = dyn_cast<ConstantInt>(Val: Op2);
4390
4391 auto Simplifies = [&](Value *Op, unsigned Idx) {
4392 // A comparison of ucmp/scmp with a constant will fold into an icmp.
4393 const APInt *Dummy;
4394 return Op ||
4395 (isa<CmpIntrinsic>(Val: SI->getOperand(i_nocapture: Idx)) &&
4396 SI->getOperand(i_nocapture: Idx)->hasOneUse() && match(V: RHS, P: m_APInt(Res&: Dummy)));
4397 };
4398
4399 // We only want to perform this transformation if it will not lead to
4400 // additional code. This is true if either both sides of the select
4401 // fold to a constant (in which case the icmp is replaced with a select
4402 // which will usually simplify) or this is the only user of the
4403 // select (in which case we are trading a select+icmp for a simpler
4404 // select+icmp) or all uses of the select can be replaced based on
4405 // dominance information ("Global cases").
4406 bool Transform = false;
4407 if (Op1 && Op2)
4408 Transform = true;
4409 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4410 // Local case
4411 if (SI->hasOneUse())
4412 Transform = true;
4413 // Global cases
4414 else if (CI && !CI->isZero())
4415 // When Op1 is constant try replacing select with second operand.
4416 // Otherwise Op2 is constant and try replacing select with first
4417 // operand.
4418 Transform = replacedSelectWithOperand(SI, Icmp: &I, SIOpd: Op1 ? 2 : 1);
4419 }
4420 if (Transform) {
4421 if (!Op1)
4422 Op1 = Builder.CreateICmp(P: Pred, LHS: SI->getOperand(i_nocapture: 1), RHS, Name: I.getName());
4423 if (!Op2)
4424 Op2 = Builder.CreateICmp(P: Pred, LHS: SI->getOperand(i_nocapture: 2), RHS, Name: I.getName());
4425 return SelectInst::Create(C: SI->getOperand(i_nocapture: 0), S1: Op1, S2: Op2, NameStr: "", InsertBefore: nullptr,
4426 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : SI);
4427 }
4428
4429 return nullptr;
4430}
4431
4432// Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)
4433static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,
4434 unsigned Depth = 0) {
4435 if (Not ? match(V, P: m_NegatedPower2OrZero()) : match(V, P: m_LowBitMaskOrZero()))
4436 return true;
4437 if (V->getType()->getScalarSizeInBits() == 1)
4438 return true;
4439 if (Depth++ >= MaxAnalysisRecursionDepth)
4440 return false;
4441 Value *X;
4442 const Instruction *I = dyn_cast<Instruction>(Val: V);
4443 if (!I)
4444 return false;
4445 switch (I->getOpcode()) {
4446 case Instruction::ZExt:
4447 // ZExt(Mask) is a Mask.
4448 return !Not && isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4449 case Instruction::SExt:
4450 // SExt(Mask) is a Mask.
4451 // SExt(~Mask) is a ~Mask.
4452 return isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4453 case Instruction::And:
4454 case Instruction::Or:
4455 // Mask0 | Mask1 is a Mask.
4456 // Mask0 & Mask1 is a Mask.
4457 // ~Mask0 | ~Mask1 is a ~Mask.
4458 // ~Mask0 & ~Mask1 is a ~Mask.
4459 return isMaskOrZero(V: I->getOperand(i: 1), Not, Q, Depth) &&
4460 isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4461 case Instruction::Xor:
4462 if (match(V, P: m_Not(V: m_Value(V&: X))))
4463 return isMaskOrZero(V: X, Not: !Not, Q, Depth);
4464
4465 // (X ^ -X) is a ~Mask
4466 if (Not)
4467 return match(V, P: m_c_Xor(L: m_Value(V&: X), R: m_Neg(V: m_Deferred(V: X))));
4468 // (X ^ (X - 1)) is a Mask
4469 else
4470 return match(V, P: m_c_Xor(L: m_Value(V&: X), R: m_Add(L: m_Deferred(V: X), R: m_AllOnes())));
4471 case Instruction::Select:
4472 // c ? Mask0 : Mask1 is a Mask.
4473 return isMaskOrZero(V: I->getOperand(i: 1), Not, Q, Depth) &&
4474 isMaskOrZero(V: I->getOperand(i: 2), Not, Q, Depth);
4475 case Instruction::Shl:
4476 // (~Mask) << X is a ~Mask.
4477 return Not && isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4478 case Instruction::LShr:
4479 // Mask >> X is a Mask.
4480 return !Not && isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4481 case Instruction::AShr:
4482 // Mask s>> X is a Mask.
4483 // ~Mask s>> X is a ~Mask.
4484 return isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4485 case Instruction::Add:
4486 // Pow2 - 1 is a Mask.
4487 if (!Not && match(V: I->getOperand(i: 1), P: m_AllOnes()))
4488 return isKnownToBeAPowerOfTwo(V: I->getOperand(i: 0), DL: Q.DL, /*OrZero*/ true,
4489 AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT, UseInstrInfo: Depth);
4490 break;
4491 case Instruction::Sub:
4492 // -Pow2 is a ~Mask.
4493 if (Not && match(V: I->getOperand(i: 0), P: m_Zero()))
4494 return isKnownToBeAPowerOfTwo(V: I->getOperand(i: 1), DL: Q.DL, /*OrZero*/ true,
4495 AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT, UseInstrInfo: Depth);
4496 break;
4497 case Instruction::Call: {
4498 if (auto *II = dyn_cast<IntrinsicInst>(Val: I)) {
4499 switch (II->getIntrinsicID()) {
4500 // min/max(Mask0, Mask1) is a Mask.
4501 // min/max(~Mask0, ~Mask1) is a ~Mask.
4502 case Intrinsic::umax:
4503 case Intrinsic::smax:
4504 case Intrinsic::umin:
4505 case Intrinsic::smin:
4506 return isMaskOrZero(V: II->getArgOperand(i: 1), Not, Q, Depth) &&
4507 isMaskOrZero(V: II->getArgOperand(i: 0), Not, Q, Depth);
4508
4509 // In the context of masks, bitreverse(Mask) == ~Mask
4510 case Intrinsic::bitreverse:
4511 return isMaskOrZero(V: II->getArgOperand(i: 0), Not: !Not, Q, Depth);
4512 default:
4513 break;
4514 }
4515 }
4516 break;
4517 }
4518 default:
4519 break;
4520 }
4521 return false;
4522}
4523
4524/// Some comparisons can be simplified.
4525/// In this case, we are looking for comparisons that look like
4526/// a check for a lossy truncation.
4527/// Folds:
4528/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
4529/// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask
4530/// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask
4531/// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask
4532/// Where Mask is some pattern that produces all-ones in low bits:
4533/// (-1 >> y)
4534/// ((-1 << y) >> y) <- non-canonical, has extra uses
4535/// ~(-1 << y)
4536/// ((1 << y) + (-1)) <- non-canonical, has extra uses
4537/// The Mask can be a constant, too.
4538/// For some predicates, the operands are commutative.
4539/// For others, x can only be on a specific side.
4540static Value *foldICmpWithLowBitMaskedVal(CmpPredicate Pred, Value *Op0,
4541 Value *Op1, const SimplifyQuery &Q,
4542 InstCombiner &IC) {
4543
4544 ICmpInst::Predicate DstPred;
4545 switch (Pred) {
4546 case ICmpInst::Predicate::ICMP_EQ:
4547 // x & Mask == x
4548 // x & ~Mask == 0
4549 // ~x | Mask == -1
4550 // -> x u<= Mask
4551 // x & ~Mask == ~Mask
4552 // -> ~Mask u<= x
4553 DstPred = ICmpInst::Predicate::ICMP_ULE;
4554 break;
4555 case ICmpInst::Predicate::ICMP_NE:
4556 // x & Mask != x
4557 // x & ~Mask != 0
4558 // ~x | Mask != -1
4559 // -> x u> Mask
4560 // x & ~Mask != ~Mask
4561 // -> ~Mask u> x
4562 DstPred = ICmpInst::Predicate::ICMP_UGT;
4563 break;
4564 case ICmpInst::Predicate::ICMP_ULT:
4565 // x & Mask u< x
4566 // -> x u> Mask
4567 // x & ~Mask u< ~Mask
4568 // -> ~Mask u> x
4569 DstPred = ICmpInst::Predicate::ICMP_UGT;
4570 break;
4571 case ICmpInst::Predicate::ICMP_UGE:
4572 // x & Mask u>= x
4573 // -> x u<= Mask
4574 // x & ~Mask u>= ~Mask
4575 // -> ~Mask u<= x
4576 DstPred = ICmpInst::Predicate::ICMP_ULE;
4577 break;
4578 case ICmpInst::Predicate::ICMP_SLT:
4579 // x & Mask s< x [iff Mask s>= 0]
4580 // -> x s> Mask
4581 // x & ~Mask s< ~Mask [iff ~Mask != 0]
4582 // -> ~Mask s> x
4583 DstPred = ICmpInst::Predicate::ICMP_SGT;
4584 break;
4585 case ICmpInst::Predicate::ICMP_SGE:
4586 // x & Mask s>= x [iff Mask s>= 0]
4587 // -> x s<= Mask
4588 // x & ~Mask s>= ~Mask [iff ~Mask != 0]
4589 // -> ~Mask s<= x
4590 DstPred = ICmpInst::Predicate::ICMP_SLE;
4591 break;
4592 default:
4593 // We don't support sgt,sle
4594 // ult/ugt are simplified to true/false respectively.
4595 return nullptr;
4596 }
4597
4598 Value *X, *M;
4599 // Put search code in lambda for early positive returns.
4600 auto IsLowBitMask = [&]() {
4601 if (match(V: Op0, P: m_c_And(L: m_Specific(V: Op1), R: m_Value(V&: M)))) {
4602 X = Op1;
4603 // Look for: x & Mask pred x
4604 if (isMaskOrZero(V: M, /*Not=*/false, Q)) {
4605 return !ICmpInst::isSigned(predicate: Pred) ||
4606 (match(V: M, P: m_NonNegative()) || isKnownNonNegative(V: M, SQ: Q));
4607 }
4608
4609 // Look for: x & ~Mask pred ~Mask
4610 if (isMaskOrZero(V: X, /*Not=*/true, Q)) {
4611 return !ICmpInst::isSigned(predicate: Pred) || isKnownNonZero(V: X, Q);
4612 }
4613 return false;
4614 }
4615 if (ICmpInst::isEquality(P: Pred) && match(V: Op1, P: m_AllOnes()) &&
4616 match(V: Op0, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: X), R: m_Value(V&: M))))) {
4617
4618 auto Check = [&]() {
4619 // Look for: ~x | Mask == -1
4620 if (isMaskOrZero(V: M, /*Not=*/false, Q)) {
4621 if (Value *NotX =
4622 IC.getFreelyInverted(V: X, WillInvertAllUses: X->hasOneUse(), Builder: &IC.Builder)) {
4623 X = NotX;
4624 return true;
4625 }
4626 }
4627 return false;
4628 };
4629 if (Check())
4630 return true;
4631 std::swap(a&: X, b&: M);
4632 return Check();
4633 }
4634 if (ICmpInst::isEquality(P: Pred) && match(V: Op1, P: m_Zero()) &&
4635 match(V: Op0, P: m_OneUse(SubPattern: m_And(L: m_Value(V&: X), R: m_Value(V&: M))))) {
4636 auto Check = [&]() {
4637 // Look for: x & ~Mask == 0
4638 if (isMaskOrZero(V: M, /*Not=*/true, Q)) {
4639 if (Value *NotM =
4640 IC.getFreelyInverted(V: M, WillInvertAllUses: M->hasOneUse(), Builder: &IC.Builder)) {
4641 M = NotM;
4642 return true;
4643 }
4644 }
4645 return false;
4646 };
4647 if (Check())
4648 return true;
4649 std::swap(a&: X, b&: M);
4650 return Check();
4651 }
4652 return false;
4653 };
4654
4655 if (!IsLowBitMask())
4656 return nullptr;
4657
4658 return IC.Builder.CreateICmp(P: DstPred, LHS: X, RHS: M);
4659}
4660
4661/// Some comparisons can be simplified.
4662/// In this case, we are looking for comparisons that look like
4663/// a check for a lossy signed truncation.
4664/// Folds: (MaskedBits is a constant.)
4665/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4666/// Into:
4667/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4668/// Where KeptBits = bitwidth(%x) - MaskedBits
4669static Value *
4670foldICmpWithTruncSignExtendedVal(ICmpInst &I,
4671 InstCombiner::BuilderTy &Builder) {
4672 CmpPredicate SrcPred;
4673 Value *X;
4674 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4675 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4676 if (!match(V: &I, P: m_c_ICmp(Pred&: SrcPred,
4677 L: m_OneUse(SubPattern: m_AShr(L: m_Shl(L: m_Value(V&: X), R: m_APInt(Res&: C0)),
4678 R: m_APInt(Res&: C1))),
4679 R: m_Deferred(V: X))))
4680 return nullptr;
4681
4682 // Potential handling of non-splats: for each element:
4683 // * if both are undef, replace with constant 0.
4684 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4685 // * if both are not undef, and are different, bailout.
4686 // * else, only one is undef, then pick the non-undef one.
4687
4688 // The shift amount must be equal.
4689 if (*C0 != *C1)
4690 return nullptr;
4691 const APInt &MaskedBits = *C0;
4692 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4693
4694 ICmpInst::Predicate DstPred;
4695 switch (SrcPred) {
4696 case ICmpInst::Predicate::ICMP_EQ:
4697 // ((%x << MaskedBits) a>> MaskedBits) == %x
4698 // =>
4699 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4700 DstPred = ICmpInst::Predicate::ICMP_ULT;
4701 break;
4702 case ICmpInst::Predicate::ICMP_NE:
4703 // ((%x << MaskedBits) a>> MaskedBits) != %x
4704 // =>
4705 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4706 DstPred = ICmpInst::Predicate::ICMP_UGE;
4707 break;
4708 // FIXME: are more folds possible?
4709 default:
4710 return nullptr;
4711 }
4712
4713 auto *XType = X->getType();
4714 const unsigned XBitWidth = XType->getScalarSizeInBits();
4715 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4716 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4717
4718 // KeptBits = bitwidth(%x) - MaskedBits
4719 const APInt KeptBits = BitWidth - MaskedBits;
4720 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4721 // ICmpCst = (1 << KeptBits)
4722 const APInt ICmpCst = APInt(XBitWidth, 1).shl(ShiftAmt: KeptBits);
4723 assert(ICmpCst.isPowerOf2());
4724 // AddCst = (1 << (KeptBits-1))
4725 const APInt AddCst = ICmpCst.lshr(shiftAmt: 1);
4726 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4727
4728 // T0 = add %x, AddCst
4729 Value *T0 = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty: XType, V: AddCst));
4730 // T1 = T0 DstPred ICmpCst
4731 Value *T1 = Builder.CreateICmp(P: DstPred, LHS: T0, RHS: ConstantInt::get(Ty: XType, V: ICmpCst));
4732
4733 return T1;
4734}
4735
4736// Given pattern:
4737// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4738// we should move shifts to the same hand of 'and', i.e. rewrite as
4739// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4740// We are only interested in opposite logical shifts here.
4741// One of the shifts can be truncated.
4742// If we can, we want to end up creating 'lshr' shift.
4743static Value *
4744foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ,
4745 InstCombiner::BuilderTy &Builder) {
4746 if (!I.isEquality() || !match(V: I.getOperand(i_nocapture: 1), P: m_Zero()) ||
4747 !I.getOperand(i_nocapture: 0)->hasOneUse())
4748 return nullptr;
4749
4750 auto m_AnyLogicalShift = m_LogicalShift(L: m_Value(), R: m_Value());
4751
4752 // Look for an 'and' of two logical shifts, one of which may be truncated.
4753 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4754 Instruction *XShift, *MaybeTruncation, *YShift;
4755 if (!match(
4756 V: I.getOperand(i_nocapture: 0),
4757 P: m_c_And(L: m_CombineAnd(L: m_AnyLogicalShift, R: m_Instruction(I&: XShift)),
4758 R: m_CombineAnd(L: m_TruncOrSelf(Op: m_CombineAnd(
4759 L: m_AnyLogicalShift, R: m_Instruction(I&: YShift))),
4760 R: m_Instruction(I&: MaybeTruncation)))))
4761 return nullptr;
4762
4763 // We potentially looked past 'trunc', but only when matching YShift,
4764 // therefore YShift must have the widest type.
4765 Instruction *WidestShift = YShift;
4766 // Therefore XShift must have the shallowest type.
4767 // Or they both have identical types if there was no truncation.
4768 Instruction *NarrowestShift = XShift;
4769
4770 Type *WidestTy = WidestShift->getType();
4771 Type *NarrowestTy = NarrowestShift->getType();
4772 assert(NarrowestTy == I.getOperand(0)->getType() &&
4773 "We did not look past any shifts while matching XShift though.");
4774 bool HadTrunc = WidestTy != I.getOperand(i_nocapture: 0)->getType();
4775
4776 // If YShift is a 'lshr', swap the shifts around.
4777 if (match(V: YShift, P: m_LShr(L: m_Value(), R: m_Value())))
4778 std::swap(a&: XShift, b&: YShift);
4779
4780 // The shifts must be in opposite directions.
4781 auto XShiftOpcode = XShift->getOpcode();
4782 if (XShiftOpcode == YShift->getOpcode())
4783 return nullptr; // Do not care about same-direction shifts here.
4784
4785 Value *X, *XShAmt, *Y, *YShAmt;
4786 match(V: XShift, P: m_BinOp(L: m_Value(V&: X), R: m_ZExtOrSelf(Op: m_Value(V&: XShAmt))));
4787 match(V: YShift, P: m_BinOp(L: m_Value(V&: Y), R: m_ZExtOrSelf(Op: m_Value(V&: YShAmt))));
4788
4789 // If one of the values being shifted is a constant, then we will end with
4790 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4791 // however, we will need to ensure that we won't increase instruction count.
4792 if (!isa<Constant>(Val: X) && !isa<Constant>(Val: Y)) {
4793 // At least one of the hands of the 'and' should be one-use shift.
4794 if (!match(V: I.getOperand(i_nocapture: 0),
4795 P: m_c_And(L: m_OneUse(SubPattern: m_AnyLogicalShift), R: m_Value())))
4796 return nullptr;
4797 if (HadTrunc) {
4798 // Due to the 'trunc', we will need to widen X. For that either the old
4799 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4800 if (!MaybeTruncation->hasOneUse() &&
4801 !NarrowestShift->getOperand(i: 1)->hasOneUse())
4802 return nullptr;
4803 }
4804 }
4805
4806 // We have two shift amounts from two different shifts. The types of those
4807 // shift amounts may not match. If that's the case let's bailout now.
4808 if (XShAmt->getType() != YShAmt->getType())
4809 return nullptr;
4810
4811 // As input, we have the following pattern:
4812 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4813 // We want to rewrite that as:
4814 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4815 // While we know that originally (Q+K) would not overflow
4816 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
4817 // shift amounts. so it may now overflow in smaller bitwidth.
4818 // To ensure that does not happen, we need to ensure that the total maximal
4819 // shift amount is still representable in that smaller bit width.
4820 unsigned MaximalPossibleTotalShiftAmount =
4821 (WidestTy->getScalarSizeInBits() - 1) +
4822 (NarrowestTy->getScalarSizeInBits() - 1);
4823 APInt MaximalRepresentableShiftAmount =
4824 APInt::getAllOnes(numBits: XShAmt->getType()->getScalarSizeInBits());
4825 if (MaximalRepresentableShiftAmount.ult(RHS: MaximalPossibleTotalShiftAmount))
4826 return nullptr;
4827
4828 // Can we fold (XShAmt+YShAmt) ?
4829 auto *NewShAmt = dyn_cast_or_null<Constant>(
4830 Val: simplifyAddInst(LHS: XShAmt, RHS: YShAmt, /*isNSW=*/IsNSW: false,
4831 /*isNUW=*/IsNUW: false, Q: SQ.getWithInstruction(I: &I)));
4832 if (!NewShAmt)
4833 return nullptr;
4834 if (NewShAmt->getType() != WidestTy) {
4835 NewShAmt =
4836 ConstantFoldCastOperand(Opcode: Instruction::ZExt, C: NewShAmt, DestTy: WidestTy, DL: SQ.DL);
4837 if (!NewShAmt)
4838 return nullptr;
4839 }
4840 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
4841
4842 // Is the new shift amount smaller than the bit width?
4843 // FIXME: could also rely on ConstantRange.
4844 if (!match(V: NewShAmt,
4845 P: m_SpecificInt_ICMP(Predicate: ICmpInst::Predicate::ICMP_ULT,
4846 Threshold: APInt(WidestBitWidth, WidestBitWidth))))
4847 return nullptr;
4848
4849 // An extra legality check is needed if we had trunc-of-lshr.
4850 if (HadTrunc && match(V: WidestShift, P: m_LShr(L: m_Value(), R: m_Value()))) {
4851 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
4852 WidestShift]() {
4853 // It isn't obvious whether it's worth it to analyze non-constants here.
4854 // Also, let's basically give up on non-splat cases, pessimizing vectors.
4855 // If *any* of these preconditions matches we can perform the fold.
4856 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
4857 ? NewShAmt->getSplatValue()
4858 : NewShAmt;
4859 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
4860 if (NewShAmtSplat &&
4861 (NewShAmtSplat->isNullValue() ||
4862 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
4863 return true;
4864 // We consider *min* leading zeros so a single outlier
4865 // blocks the transform as opposed to allowing it.
4866 if (auto *C = dyn_cast<Constant>(Val: NarrowestShift->getOperand(i: 0))) {
4867 KnownBits Known = computeKnownBits(V: C, DL: SQ.DL);
4868 unsigned MinLeadZero = Known.countMinLeadingZeros();
4869 // If the value being shifted has at most lowest bit set we can fold.
4870 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4871 if (MaxActiveBits <= 1)
4872 return true;
4873 // Precondition: NewShAmt u<= countLeadingZeros(C)
4874 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(RHS: MinLeadZero))
4875 return true;
4876 }
4877 if (auto *C = dyn_cast<Constant>(Val: WidestShift->getOperand(i: 0))) {
4878 KnownBits Known = computeKnownBits(V: C, DL: SQ.DL);
4879 unsigned MinLeadZero = Known.countMinLeadingZeros();
4880 // If the value being shifted has at most lowest bit set we can fold.
4881 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4882 if (MaxActiveBits <= 1)
4883 return true;
4884 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
4885 if (NewShAmtSplat) {
4886 APInt AdjNewShAmt =
4887 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
4888 if (AdjNewShAmt.ule(RHS: MinLeadZero))
4889 return true;
4890 }
4891 }
4892 return false; // Can't tell if it's ok.
4893 };
4894 if (!CanFold())
4895 return nullptr;
4896 }
4897
4898 // All good, we can do this fold.
4899 X = Builder.CreateZExt(V: X, DestTy: WidestTy);
4900 Y = Builder.CreateZExt(V: Y, DestTy: WidestTy);
4901 // The shift is the same that was for X.
4902 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
4903 ? Builder.CreateLShr(LHS: X, RHS: NewShAmt)
4904 : Builder.CreateShl(LHS: X, RHS: NewShAmt);
4905 Value *T1 = Builder.CreateAnd(LHS: T0, RHS: Y);
4906 return Builder.CreateICmp(P: I.getPredicate(), LHS: T1,
4907 RHS: Constant::getNullValue(Ty: WidestTy));
4908}
4909
4910/// Fold
4911/// (-1 u/ x) u< y
4912/// ((x * y) ?/ x) != y
4913/// to
4914/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
4915/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
4916/// will mean that we are looking for the opposite answer.
4917Value *InstCombinerImpl::foldMultiplicationOverflowCheck(ICmpInst &I) {
4918 CmpPredicate Pred;
4919 Value *X, *Y;
4920 Instruction *Mul;
4921 Instruction *Div;
4922 bool NeedNegation;
4923 // Look for: (-1 u/ x) u</u>= y
4924 if (!I.isEquality() &&
4925 match(V: &I, P: m_c_ICmp(Pred,
4926 L: m_CombineAnd(L: m_OneUse(SubPattern: m_UDiv(L: m_AllOnes(), R: m_Value(V&: X))),
4927 R: m_Instruction(I&: Div)),
4928 R: m_Value(V&: Y)))) {
4929 Mul = nullptr;
4930
4931 // Are we checking that overflow does not happen, or does happen?
4932 switch (Pred) {
4933 case ICmpInst::Predicate::ICMP_ULT:
4934 NeedNegation = false;
4935 break; // OK
4936 case ICmpInst::Predicate::ICMP_UGE:
4937 NeedNegation = true;
4938 break; // OK
4939 default:
4940 return nullptr; // Wrong predicate.
4941 }
4942 } else // Look for: ((x * y) / x) !=/== y
4943 if (I.isEquality() &&
4944 match(V: &I, P: m_c_ICmp(Pred, L: m_Value(V&: Y),
4945 R: m_CombineAnd(L: m_OneUse(SubPattern: m_IDiv(
4946 L: m_CombineAnd(L: m_c_Mul(L: m_Deferred(V: Y),
4947 R: m_Value(V&: X)),
4948 R: m_Instruction(I&: Mul)),
4949 R: m_Deferred(V: X))),
4950 R: m_Instruction(I&: Div))))) {
4951 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
4952 } else
4953 return nullptr;
4954
4955 BuilderTy::InsertPointGuard Guard(Builder);
4956 // If the pattern included (x * y), we'll want to insert new instructions
4957 // right before that original multiplication so that we can replace it.
4958 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
4959 if (MulHadOtherUses)
4960 Builder.SetInsertPoint(Mul);
4961
4962 CallInst *Call = Builder.CreateIntrinsic(
4963 ID: Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
4964 : Intrinsic::smul_with_overflow,
4965 Types: X->getType(), Args: {X, Y}, /*FMFSource=*/nullptr, Name: "mul");
4966
4967 // If the multiplication was used elsewhere, to ensure that we don't leave
4968 // "duplicate" instructions, replace uses of that original multiplication
4969 // with the multiplication result from the with.overflow intrinsic.
4970 if (MulHadOtherUses)
4971 replaceInstUsesWith(I&: *Mul, V: Builder.CreateExtractValue(Agg: Call, Idxs: 0, Name: "mul.val"));
4972
4973 Value *Res = Builder.CreateExtractValue(Agg: Call, Idxs: 1, Name: "mul.ov");
4974 if (NeedNegation) // This technically increases instruction count.
4975 Res = Builder.CreateNot(V: Res, Name: "mul.not.ov");
4976
4977 // If we replaced the mul, erase it. Do this after all uses of Builder,
4978 // as the mul is used as insertion point.
4979 if (MulHadOtherUses)
4980 eraseInstFromFunction(I&: *Mul);
4981
4982 return Res;
4983}
4984
4985static Instruction *foldICmpXNegX(ICmpInst &I,
4986 InstCombiner::BuilderTy &Builder) {
4987 CmpPredicate Pred;
4988 Value *X;
4989 if (match(V: &I, P: m_c_ICmp(Pred, L: m_NSWNeg(V: m_Value(V&: X)), R: m_Deferred(V: X)))) {
4990
4991 if (ICmpInst::isSigned(predicate: Pred))
4992 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
4993 else if (ICmpInst::isUnsigned(predicate: Pred))
4994 Pred = ICmpInst::getSignedPredicate(Pred);
4995 // else for equality-comparisons just keep the predicate.
4996
4997 return ICmpInst::Create(Op: Instruction::ICmp, Pred, S1: X,
4998 S2: Constant::getNullValue(Ty: X->getType()), Name: I.getName());
4999 }
5000
5001 // A value is not equal to its negation unless that value is 0 or
5002 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
5003 if (match(V: &I, P: m_c_ICmp(Pred, L: m_OneUse(SubPattern: m_Neg(V: m_Value(V&: X))), R: m_Deferred(V: X))) &&
5004 ICmpInst::isEquality(P: Pred)) {
5005 Type *Ty = X->getType();
5006 uint32_t BitWidth = Ty->getScalarSizeInBits();
5007 Constant *MaxSignedVal =
5008 ConstantInt::get(Ty, V: APInt::getSignedMaxValue(numBits: BitWidth));
5009 Value *And = Builder.CreateAnd(LHS: X, RHS: MaxSignedVal);
5010 Constant *Zero = Constant::getNullValue(Ty);
5011 return CmpInst::Create(Op: Instruction::ICmp, Pred, S1: And, S2: Zero);
5012 }
5013
5014 return nullptr;
5015}
5016
5017static Instruction *foldICmpAndXX(ICmpInst &I, const SimplifyQuery &Q,
5018 InstCombinerImpl &IC) {
5019 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *A;
5020 // Normalize and operand as operand 0.
5021 CmpInst::Predicate Pred = I.getPredicate();
5022 if (match(V: Op1, P: m_c_And(L: m_Specific(V: Op0), R: m_Value()))) {
5023 std::swap(a&: Op0, b&: Op1);
5024 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5025 }
5026
5027 if (!match(V: Op0, P: m_c_And(L: m_Specific(V: Op1), R: m_Value(V&: A))))
5028 return nullptr;
5029
5030 // (icmp (X & Y) u< X --> (X & Y) != X
5031 if (Pred == ICmpInst::ICMP_ULT)
5032 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5033
5034 // (icmp (X & Y) u>= X --> (X & Y) == X
5035 if (Pred == ICmpInst::ICMP_UGE)
5036 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5037
5038 if (ICmpInst::isEquality(P: Pred) && Op0->hasOneUse()) {
5039 // icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and
5040 // Y is non-constant. If Y is constant the `X & C == C` form is preferable
5041 // so don't do this fold.
5042 if (!match(V: Op1, P: m_ImmConstant()))
5043 if (auto *NotOp1 =
5044 IC.getFreelyInverted(V: Op1, WillInvertAllUses: !Op1->hasNUsesOrMore(N: 3), Builder: &IC.Builder))
5045 return new ICmpInst(Pred, IC.Builder.CreateOr(LHS: A, RHS: NotOp1),
5046 Constant::getAllOnesValue(Ty: Op1->getType()));
5047 // icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.
5048 if (auto *NotA = IC.getFreelyInverted(V: A, WillInvertAllUses: A->hasOneUse(), Builder: &IC.Builder))
5049 return new ICmpInst(Pred, IC.Builder.CreateAnd(LHS: Op1, RHS: NotA),
5050 Constant::getNullValue(Ty: Op1->getType()));
5051 }
5052
5053 if (!ICmpInst::isSigned(predicate: Pred))
5054 return nullptr;
5055
5056 KnownBits KnownY = IC.computeKnownBits(V: A, CxtI: &I);
5057 // (X & NegY) spred X --> (X & NegY) upred X
5058 if (KnownY.isNegative())
5059 return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);
5060
5061 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGT)
5062 return nullptr;
5063
5064 if (KnownY.isNonNegative())
5065 // (X & PosY) s<= X --> X s>= 0
5066 // (X & PosY) s> X --> X s< 0
5067 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
5068 Constant::getNullValue(Ty: Op1->getType()));
5069
5070 if (isKnownNegative(V: Op1, SQ: IC.getSimplifyQuery().getWithInstruction(I: &I)))
5071 // (NegX & Y) s<= NegX --> Y s< 0
5072 // (NegX & Y) s> NegX --> Y s>= 0
5073 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), A,
5074 Constant::getNullValue(Ty: A->getType()));
5075
5076 return nullptr;
5077}
5078
5079static Instruction *foldICmpOrXX(ICmpInst &I, const SimplifyQuery &Q,
5080 InstCombinerImpl &IC) {
5081 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *A;
5082
5083 // Normalize or operand as operand 0.
5084 CmpInst::Predicate Pred = I.getPredicate();
5085 if (match(V: Op1, P: m_c_Or(L: m_Specific(V: Op0), R: m_Value(V&: A)))) {
5086 std::swap(a&: Op0, b&: Op1);
5087 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5088 } else if (!match(V: Op0, P: m_c_Or(L: m_Specific(V: Op1), R: m_Value(V&: A)))) {
5089 return nullptr;
5090 }
5091
5092 // icmp (X | Y) u<= X --> (X | Y) == X
5093 if (Pred == ICmpInst::ICMP_ULE)
5094 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5095
5096 // icmp (X | Y) u> X --> (X | Y) != X
5097 if (Pred == ICmpInst::ICMP_UGT)
5098 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5099
5100 if (ICmpInst::isEquality(P: Pred) && Op0->hasOneUse()) {
5101 // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
5102 if (Value *NotOp1 = IC.getFreelyInverted(
5103 V: Op1, WillInvertAllUses: !isa<Constant>(Val: Op1) && !Op1->hasNUsesOrMore(N: 3), Builder: &IC.Builder))
5104 return new ICmpInst(Pred, IC.Builder.CreateAnd(LHS: A, RHS: NotOp1),
5105 Constant::getNullValue(Ty: Op1->getType()));
5106 // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.
5107 if (Value *NotA = IC.getFreelyInverted(V: A, WillInvertAllUses: A->hasOneUse(), Builder: &IC.Builder))
5108 return new ICmpInst(Pred, IC.Builder.CreateOr(LHS: Op1, RHS: NotA),
5109 Constant::getAllOnesValue(Ty: Op1->getType()));
5110 }
5111 return nullptr;
5112}
5113
5114static Instruction *foldICmpXorXX(ICmpInst &I, const SimplifyQuery &Q,
5115 InstCombinerImpl &IC) {
5116 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *A;
5117 // Normalize xor operand as operand 0.
5118 CmpInst::Predicate Pred = I.getPredicate();
5119 if (match(V: Op1, P: m_c_Xor(L: m_Specific(V: Op0), R: m_Value()))) {
5120 std::swap(a&: Op0, b&: Op1);
5121 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5122 }
5123 if (!match(V: Op0, P: m_c_Xor(L: m_Specific(V: Op1), R: m_Value(V&: A))))
5124 return nullptr;
5125
5126 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
5127 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
5128 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
5129 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
5130 CmpInst::Predicate PredOut = CmpInst::getStrictPredicate(pred: Pred);
5131 if (PredOut != Pred && isKnownNonZero(V: A, Q))
5132 return new ICmpInst(PredOut, Op0, Op1);
5133
5134 // These transform work when A is negative.
5135 // X s< X^A, X s<= X^A, X u> X^A, X u>= X^A --> X s< 0
5136 // X s> X^A, X s>= X^A, X u< X^A, X u<= X^A --> X s>= 0
5137 if (match(V: A, P: m_Negative())) {
5138 CmpInst::Predicate NewPred;
5139 switch (ICmpInst::getStrictPredicate(pred: Pred)) {
5140 default:
5141 return nullptr;
5142 case ICmpInst::ICMP_SLT:
5143 case ICmpInst::ICMP_UGT:
5144 NewPred = ICmpInst::ICMP_SLT;
5145 break;
5146 case ICmpInst::ICMP_SGT:
5147 case ICmpInst::ICMP_ULT:
5148 NewPred = ICmpInst::ICMP_SGE;
5149 break;
5150 }
5151 Constant *Const = Constant::getNullValue(Ty: Op0->getType());
5152 return new ICmpInst(NewPred, Op0, Const);
5153 }
5154
5155 return nullptr;
5156}
5157
5158/// Return true if X is a multiple of C.
5159/// TODO: Handle non-power-of-2 factors.
5160static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q) {
5161 if (C.isOne())
5162 return true;
5163
5164 if (!C.isPowerOf2())
5165 return false;
5166
5167 return MaskedValueIsZero(V: X, Mask: C - 1, SQ: Q);
5168}
5169
5170/// Try to fold icmp (binop), X or icmp X, (binop).
5171/// TODO: A large part of this logic is duplicated in InstSimplify's
5172/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
5173/// duplication.
5174Instruction *InstCombinerImpl::foldICmpBinOp(ICmpInst &I,
5175 const SimplifyQuery &SQ) {
5176 const SimplifyQuery Q = SQ.getWithInstruction(I: &I);
5177 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
5178
5179 // Special logic for binary operators.
5180 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Val: Op0);
5181 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Val: Op1);
5182 if (!BO0 && !BO1)
5183 return nullptr;
5184
5185 if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
5186 return NewICmp;
5187
5188 const CmpInst::Predicate Pred = I.getPredicate();
5189 Value *X;
5190
5191 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
5192 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
5193 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: Op1), R: m_Value(V&: X)))) &&
5194 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5195 return new ICmpInst(Pred, Builder.CreateNot(V: Op1), X);
5196 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
5197 if (match(V: Op1, P: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: Op0), R: m_Value(V&: X)))) &&
5198 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5199 return new ICmpInst(Pred, X, Builder.CreateNot(V: Op0));
5200
5201 {
5202 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
5203 Constant *C;
5204 if (match(V: Op0, P: m_OneUse(SubPattern: m_Add(L: m_c_Add(L: m_Specific(V: Op1), R: m_Value(V&: X)),
5205 R: m_ImmConstant(C)))) &&
5206 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
5207 Constant *C2 = ConstantExpr::getNot(C);
5208 return new ICmpInst(Pred, Builder.CreateSub(LHS: C2, RHS: X), Op1);
5209 }
5210 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
5211 if (match(V: Op1, P: m_OneUse(SubPattern: m_Add(L: m_c_Add(L: m_Specific(V: Op0), R: m_Value(V&: X)),
5212 R: m_ImmConstant(C)))) &&
5213 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
5214 Constant *C2 = ConstantExpr::getNot(C);
5215 return new ICmpInst(Pred, Op0, Builder.CreateSub(LHS: C2, RHS: X));
5216 }
5217 }
5218
5219 // (icmp eq/ne (X, -P2), INT_MIN)
5220 // -> (icmp slt/sge X, INT_MIN + P2)
5221 if (ICmpInst::isEquality(P: Pred) && BO0 &&
5222 match(V: I.getOperand(i_nocapture: 1), P: m_SignMask()) &&
5223 match(V: BO0, P: m_And(L: m_Value(), R: m_NegatedPower2OrZero()))) {
5224 // Will Constant fold.
5225 Value *NewC = Builder.CreateSub(LHS: I.getOperand(i_nocapture: 1), RHS: BO0->getOperand(i_nocapture: 1));
5226 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SLT
5227 : ICmpInst::ICMP_SGE,
5228 BO0->getOperand(i_nocapture: 0), NewC);
5229 }
5230
5231 {
5232 // Similar to above: an unsigned overflow comparison may use offset + mask:
5233 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
5234 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
5235 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
5236 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
5237 BinaryOperator *BO;
5238 const APInt *C;
5239 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
5240 match(V: Op0, P: m_And(L: m_BinOp(I&: BO), R: m_LowBitMask(V&: C))) &&
5241 match(V: BO, P: m_Add(L: m_Specific(V: Op1), R: m_SpecificIntAllowPoison(V: *C)))) {
5242 CmpInst::Predicate NewPred =
5243 Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
5244 Constant *Zero = ConstantInt::getNullValue(Ty: Op1->getType());
5245 return new ICmpInst(NewPred, Op1, Zero);
5246 }
5247
5248 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5249 match(V: Op1, P: m_And(L: m_BinOp(I&: BO), R: m_LowBitMask(V&: C))) &&
5250 match(V: BO, P: m_Add(L: m_Specific(V: Op0), R: m_SpecificIntAllowPoison(V: *C)))) {
5251 CmpInst::Predicate NewPred =
5252 Pred == ICmpInst::ICMP_UGT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
5253 Constant *Zero = ConstantInt::getNullValue(Ty: Op1->getType());
5254 return new ICmpInst(NewPred, Op0, Zero);
5255 }
5256 }
5257
5258 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
5259 bool Op0HasNUW = false, Op1HasNUW = false;
5260 bool Op0HasNSW = false, Op1HasNSW = false;
5261 // Analyze the case when either Op0 or Op1 is an add instruction.
5262 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
5263 auto hasNoWrapProblem = [](const BinaryOperator &BO, CmpInst::Predicate Pred,
5264 bool &HasNSW, bool &HasNUW) -> bool {
5265 if (isa<OverflowingBinaryOperator>(Val: BO)) {
5266 HasNUW = BO.hasNoUnsignedWrap();
5267 HasNSW = BO.hasNoSignedWrap();
5268 return ICmpInst::isEquality(P: Pred) ||
5269 (CmpInst::isUnsigned(predicate: Pred) && HasNUW) ||
5270 (CmpInst::isSigned(predicate: Pred) && HasNSW);
5271 } else if (BO.getOpcode() == Instruction::Or) {
5272 HasNUW = true;
5273 HasNSW = true;
5274 return true;
5275 } else {
5276 return false;
5277 }
5278 };
5279 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5280
5281 if (BO0) {
5282 match(V: BO0, P: m_AddLike(L: m_Value(V&: A), R: m_Value(V&: B)));
5283 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5284 }
5285 if (BO1) {
5286 match(V: BO1, P: m_AddLike(L: m_Value(V&: C), R: m_Value(V&: D)));
5287 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5288 }
5289
5290 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5291 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5292 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5293 return new ICmpInst(Pred, A == Op1 ? B : A,
5294 Constant::getNullValue(Ty: Op1->getType()));
5295
5296 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5297 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5298 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5299 return new ICmpInst(Pred, Constant::getNullValue(Ty: Op0->getType()),
5300 C == Op0 ? D : C);
5301
5302 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
5303 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
5304 NoOp1WrapProblem) {
5305 // Determine Y and Z in the form icmp (X+Y), (X+Z).
5306 Value *Y, *Z;
5307 if (A == C) {
5308 // C + B == C + D -> B == D
5309 Y = B;
5310 Z = D;
5311 } else if (A == D) {
5312 // D + B == C + D -> B == C
5313 Y = B;
5314 Z = C;
5315 } else if (B == C) {
5316 // A + C == C + D -> A == D
5317 Y = A;
5318 Z = D;
5319 } else {
5320 assert(B == D);
5321 // A + D == C + D -> A == C
5322 Y = A;
5323 Z = C;
5324 }
5325 return new ICmpInst(Pred, Y, Z);
5326 }
5327
5328 if (ICmpInst::isRelational(P: Pred)) {
5329 // Return if both X and Y is divisible by Z/-Z.
5330 // TODO: Generalize to check if (X - Y) is divisible by Z/-Z.
5331 auto ShareCommonDivisor = [&Q](Value *X, Value *Y, Value *Z,
5332 bool IsNegative) -> bool {
5333 const APInt *OffsetC;
5334 if (!match(V: Z, P: m_APInt(Res&: OffsetC)))
5335 return false;
5336
5337 // Fast path for Z == 1/-1.
5338 if (IsNegative ? OffsetC->isAllOnes() : OffsetC->isOne())
5339 return true;
5340
5341 APInt C = *OffsetC;
5342 if (IsNegative)
5343 C.negate();
5344 // Note: -INT_MIN is also negative.
5345 if (!C.isStrictlyPositive())
5346 return false;
5347
5348 return isMultipleOf(X, C, Q) && isMultipleOf(X: Y, C, Q);
5349 };
5350
5351 // TODO: The subtraction-related identities shown below also hold, but
5352 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
5353 // wouldn't happen even if they were implemented.
5354 //
5355 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5356 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5357 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5358 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5359
5360 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5361 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5362 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5363 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5364 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5365 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5366 if (A && NoOp0WrapProblem &&
5367 ShareCommonDivisor(A, Op1, B,
5368 ICmpInst::isLT(P: Pred) || ICmpInst::isGE(P: Pred)))
5369 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), A,
5370 Op1);
5371
5372 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5373 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5374 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5375 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5376 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5377 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5378 if (C && NoOp1WrapProblem &&
5379 ShareCommonDivisor(Op0, C, D,
5380 ICmpInst::isGT(P: Pred) || ICmpInst::isLE(P: Pred)))
5381 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), Op0,
5382 C);
5383 }
5384
5385 // if C1 has greater magnitude than C2:
5386 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5387 // s.t. C3 = C1 - C2
5388 //
5389 // if C2 has greater magnitude than C1:
5390 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5391 // s.t. C3 = C2 - C1
5392 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5393 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5394 const APInt *AP1, *AP2;
5395 // TODO: Support non-uniform vectors.
5396 // TODO: Allow poison passthrough if B or D's element is poison.
5397 if (match(V: B, P: m_APIntAllowPoison(Res&: AP1)) &&
5398 match(V: D, P: m_APIntAllowPoison(Res&: AP2)) &&
5399 AP1->isNegative() == AP2->isNegative()) {
5400 APInt AP1Abs = AP1->abs();
5401 APInt AP2Abs = AP2->abs();
5402 if (AP1Abs.uge(RHS: AP2Abs)) {
5403 APInt Diff = *AP1 - *AP2;
5404 Constant *C3 = Constant::getIntegerValue(Ty: BO0->getType(), V: Diff);
5405 Value *NewAdd = Builder.CreateAdd(
5406 LHS: A, RHS: C3, Name: "", HasNUW: Op0HasNUW && Diff.ule(RHS: *AP1), HasNSW: Op0HasNSW);
5407 return new ICmpInst(Pred, NewAdd, C);
5408 } else {
5409 APInt Diff = *AP2 - *AP1;
5410 Constant *C3 = Constant::getIntegerValue(Ty: BO0->getType(), V: Diff);
5411 Value *NewAdd = Builder.CreateAdd(
5412 LHS: C, RHS: C3, Name: "", HasNUW: Op1HasNUW && Diff.ule(RHS: *AP2), HasNSW: Op1HasNSW);
5413 return new ICmpInst(Pred, A, NewAdd);
5414 }
5415 }
5416 Constant *Cst1, *Cst2;
5417 if (match(V: B, P: m_ImmConstant(C&: Cst1)) && match(V: D, P: m_ImmConstant(C&: Cst2)) &&
5418 ICmpInst::isEquality(P: Pred)) {
5419 Constant *Diff = ConstantExpr::getSub(C1: Cst2, C2: Cst1);
5420 Value *NewAdd = Builder.CreateAdd(LHS: C, RHS: Diff);
5421 return new ICmpInst(Pred, A, NewAdd);
5422 }
5423 }
5424
5425 // Analyze the case when either Op0 or Op1 is a sub instruction.
5426 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5427 A = nullptr;
5428 B = nullptr;
5429 C = nullptr;
5430 D = nullptr;
5431 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5432 A = BO0->getOperand(i_nocapture: 0);
5433 B = BO0->getOperand(i_nocapture: 1);
5434 }
5435 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5436 C = BO1->getOperand(i_nocapture: 0);
5437 D = BO1->getOperand(i_nocapture: 1);
5438 }
5439
5440 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5441 if (A == Op1 && NoOp0WrapProblem)
5442 return new ICmpInst(Pred, Constant::getNullValue(Ty: Op1->getType()), B);
5443 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5444 if (C == Op0 && NoOp1WrapProblem)
5445 return new ICmpInst(Pred, D, Constant::getNullValue(Ty: Op0->getType()));
5446
5447 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5448 // (A - B) u>/u<= A --> B u>/u<= A
5449 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5450 return new ICmpInst(Pred, B, A);
5451 // C u</u>= (C - D) --> C u</u>= D
5452 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5453 return new ICmpInst(Pred, C, D);
5454 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5455 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5456 isKnownNonZero(V: B, Q))
5457 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(pred: Pred), B, A);
5458 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5459 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5460 isKnownNonZero(V: D, Q))
5461 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(pred: Pred), C, D);
5462
5463 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
5464 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
5465 return new ICmpInst(Pred, A, C);
5466
5467 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
5468 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
5469 return new ICmpInst(Pred, D, B);
5470
5471 // icmp (0-X) < cst --> x > -cst
5472 if (NoOp0WrapProblem && ICmpInst::isSigned(predicate: Pred)) {
5473 Value *X;
5474 if (match(V: BO0, P: m_Neg(V: m_Value(V&: X))))
5475 if (Constant *RHSC = dyn_cast<Constant>(Val: Op1))
5476 if (RHSC->isNotMinSignedValue())
5477 return new ICmpInst(I.getSwappedPredicate(), X,
5478 ConstantExpr::getNeg(C: RHSC));
5479 }
5480
5481 if (Instruction *R = foldICmpXorXX(I, Q, IC&: *this))
5482 return R;
5483 if (Instruction *R = foldICmpOrXX(I, Q, IC&: *this))
5484 return R;
5485
5486 {
5487 // Try to remove shared multiplier from comparison:
5488 // X * Z pred Y * Z
5489 Value *X, *Y, *Z;
5490 if ((match(V: Op0, P: m_Mul(L: m_Value(V&: X), R: m_Value(V&: Z))) &&
5491 match(V: Op1, P: m_c_Mul(L: m_Specific(V: Z), R: m_Value(V&: Y)))) ||
5492 (match(V: Op0, P: m_Mul(L: m_Value(V&: Z), R: m_Value(V&: X))) &&
5493 match(V: Op1, P: m_c_Mul(L: m_Specific(V: Z), R: m_Value(V&: Y))))) {
5494 if (ICmpInst::isSigned(predicate: Pred)) {
5495 if (Op0HasNSW && Op1HasNSW) {
5496 KnownBits ZKnown = computeKnownBits(V: Z, CxtI: &I);
5497 if (ZKnown.isStrictlyPositive())
5498 return new ICmpInst(Pred, X, Y);
5499 if (ZKnown.isNegative())
5500 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), X, Y);
5501 Value *LessThan = simplifyICmpInst(Pred: ICmpInst::ICMP_SLT, LHS: X, RHS: Y,
5502 Q: SQ.getWithInstruction(I: &I));
5503 if (LessThan && match(V: LessThan, P: m_One()))
5504 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Z,
5505 Constant::getNullValue(Ty: Z->getType()));
5506 Value *GreaterThan = simplifyICmpInst(Pred: ICmpInst::ICMP_SGT, LHS: X, RHS: Y,
5507 Q: SQ.getWithInstruction(I: &I));
5508 if (GreaterThan && match(V: GreaterThan, P: m_One()))
5509 return new ICmpInst(Pred, Z, Constant::getNullValue(Ty: Z->getType()));
5510 }
5511 } else {
5512 bool NonZero;
5513 if (ICmpInst::isEquality(P: Pred)) {
5514 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5515 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5516 isKnownNonEqual(V1: X, V2: Y, SQ))
5517 return new ICmpInst(Pred, Z, Constant::getNullValue(Ty: Z->getType()));
5518
5519 KnownBits ZKnown = computeKnownBits(V: Z, CxtI: &I);
5520 // if Z % 2 != 0
5521 // X * Z eq/ne Y * Z -> X eq/ne Y
5522 if (ZKnown.countMaxTrailingZeros() == 0)
5523 return new ICmpInst(Pred, X, Y);
5524 NonZero = !ZKnown.One.isZero() || isKnownNonZero(V: Z, Q);
5525 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5526 // X * Z eq/ne Y * Z -> X eq/ne Y
5527 if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)
5528 return new ICmpInst(Pred, X, Y);
5529 } else
5530 NonZero = isKnownNonZero(V: Z, Q);
5531
5532 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5533 // X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
5534 if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)
5535 return new ICmpInst(Pred, X, Y);
5536 }
5537 }
5538 }
5539
5540 BinaryOperator *SRem = nullptr;
5541 // icmp (srem X, Y), Y
5542 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(i_nocapture: 1))
5543 SRem = BO0;
5544 // icmp Y, (srem X, Y)
5545 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5546 Op0 == BO1->getOperand(i_nocapture: 1))
5547 SRem = BO1;
5548 if (SRem) {
5549 // We don't check hasOneUse to avoid increasing register pressure because
5550 // the value we use is the same value this instruction was already using.
5551 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(pred: Pred) : Pred) {
5552 default:
5553 break;
5554 case ICmpInst::ICMP_EQ:
5555 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
5556 case ICmpInst::ICMP_NE:
5557 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
5558 case ICmpInst::ICMP_SGT:
5559 case ICmpInst::ICMP_SGE:
5560 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(i_nocapture: 1),
5561 Constant::getAllOnesValue(Ty: SRem->getType()));
5562 case ICmpInst::ICMP_SLT:
5563 case ICmpInst::ICMP_SLE:
5564 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(i_nocapture: 1),
5565 Constant::getNullValue(Ty: SRem->getType()));
5566 }
5567 }
5568
5569 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5570 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5571 BO0->getOperand(i_nocapture: 1) == BO1->getOperand(i_nocapture: 1)) {
5572 switch (BO0->getOpcode()) {
5573 default:
5574 break;
5575 case Instruction::Add:
5576 case Instruction::Sub:
5577 case Instruction::Xor: {
5578 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5579 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5580
5581 const APInt *C;
5582 if (match(V: BO0->getOperand(i_nocapture: 1), P: m_APInt(Res&: C))) {
5583 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5584 if (C->isSignMask()) {
5585 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5586 return new ICmpInst(NewPred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5587 }
5588
5589 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5590 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5591 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5592 NewPred = I.getSwappedPredicate(pred: NewPred);
5593 return new ICmpInst(NewPred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5594 }
5595 }
5596 break;
5597 }
5598 case Instruction::Mul: {
5599 if (!I.isEquality())
5600 break;
5601
5602 const APInt *C;
5603 if (match(V: BO0->getOperand(i_nocapture: 1), P: m_APInt(Res&: C)) && !C->isZero() &&
5604 !C->isOne()) {
5605 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5606 // Mask = -1 >> count-trailing-zeros(C).
5607 if (unsigned TZs = C->countr_zero()) {
5608 Constant *Mask = ConstantInt::get(
5609 Ty: BO0->getType(),
5610 V: APInt::getLowBitsSet(numBits: C->getBitWidth(), loBitsSet: C->getBitWidth() - TZs));
5611 Value *And1 = Builder.CreateAnd(LHS: BO0->getOperand(i_nocapture: 0), RHS: Mask);
5612 Value *And2 = Builder.CreateAnd(LHS: BO1->getOperand(i_nocapture: 0), RHS: Mask);
5613 return new ICmpInst(Pred, And1, And2);
5614 }
5615 }
5616 break;
5617 }
5618 case Instruction::UDiv:
5619 case Instruction::LShr:
5620 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
5621 break;
5622 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5623
5624 case Instruction::SDiv:
5625 if (!(I.isEquality() || match(V: BO0->getOperand(i_nocapture: 1), P: m_NonNegative())) ||
5626 !BO0->isExact() || !BO1->isExact())
5627 break;
5628 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5629
5630 case Instruction::AShr:
5631 if (!BO0->isExact() || !BO1->isExact())
5632 break;
5633 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5634
5635 case Instruction::Shl: {
5636 bool NUW = Op0HasNUW && Op1HasNUW;
5637 bool NSW = Op0HasNSW && Op1HasNSW;
5638 if (!NUW && !NSW)
5639 break;
5640 if (!NSW && I.isSigned())
5641 break;
5642 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5643 }
5644 }
5645 }
5646
5647 if (BO0) {
5648 // Transform A & (L - 1) `ult` L --> L != 0
5649 auto LSubOne = m_Add(L: m_Specific(V: Op1), R: m_AllOnes());
5650 auto BitwiseAnd = m_c_And(L: m_Value(), R: LSubOne);
5651
5652 if (match(V: BO0, P: BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5653 auto *Zero = Constant::getNullValue(Ty: BO0->getType());
5654 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5655 }
5656 }
5657
5658 // For unsigned predicates / eq / ne:
5659 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5660 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5661 if (!ICmpInst::isSigned(predicate: Pred)) {
5662 if (match(V: Op0, P: m_Shl(L: m_Specific(V: Op1), R: m_One())))
5663 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5664 Constant::getNullValue(Ty: Op1->getType()));
5665 else if (match(V: Op1, P: m_Shl(L: m_Specific(V: Op0), R: m_One())))
5666 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5667 Constant::getNullValue(Ty: Op0->getType()), Op0);
5668 }
5669
5670 if (Value *V = foldMultiplicationOverflowCheck(I))
5671 return replaceInstUsesWith(I, V);
5672
5673 if (Instruction *R = foldICmpAndXX(I, Q, IC&: *this))
5674 return R;
5675
5676 if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder))
5677 return replaceInstUsesWith(I, V);
5678
5679 if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder))
5680 return replaceInstUsesWith(I, V);
5681
5682 return nullptr;
5683}
5684
5685/// Fold icmp Pred min|max(X, Y), Z.
5686Instruction *InstCombinerImpl::foldICmpWithMinMax(Instruction &I,
5687 MinMaxIntrinsic *MinMax,
5688 Value *Z, CmpPredicate Pred) {
5689 Value *X = MinMax->getLHS();
5690 Value *Y = MinMax->getRHS();
5691 if (ICmpInst::isSigned(predicate: Pred) && !MinMax->isSigned())
5692 return nullptr;
5693 if (ICmpInst::isUnsigned(predicate: Pred) && MinMax->isSigned()) {
5694 // Revert the transform signed pred -> unsigned pred
5695 // TODO: We can flip the signedness of predicate if both operands of icmp
5696 // are negative.
5697 if (isKnownNonNegative(V: Z, SQ: SQ.getWithInstruction(I: &I)) &&
5698 isKnownNonNegative(V: MinMax, SQ: SQ.getWithInstruction(I: &I))) {
5699 Pred = ICmpInst::getFlippedSignednessPredicate(Pred);
5700 } else
5701 return nullptr;
5702 }
5703 SimplifyQuery Q = SQ.getWithInstruction(I: &I);
5704 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5705 if (!Val)
5706 return std::nullopt;
5707 if (match(V: Val, P: m_One()))
5708 return true;
5709 if (match(V: Val, P: m_Zero()))
5710 return false;
5711 return std::nullopt;
5712 };
5713 // Remove samesign here since it is illegal to keep it when we speculatively
5714 // execute comparisons. For example, `icmp samesign ult umax(X, -46), -32`
5715 // cannot be decomposed into `(icmp samesign ult X, -46) or (icmp samesign ult
5716 // -46, -32)`. `X` is allowed to be non-negative here.
5717 Pred = Pred.dropSameSign();
5718 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, LHS: X, RHS: Z, Q));
5719 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, LHS: Y, RHS: Z, Q));
5720 if (!CmpXZ.has_value() && !CmpYZ.has_value())
5721 return nullptr;
5722 if (!CmpXZ.has_value()) {
5723 std::swap(a&: X, b&: Y);
5724 std::swap(lhs&: CmpXZ, rhs&: CmpYZ);
5725 }
5726
5727 auto FoldIntoCmpYZ = [&]() -> Instruction * {
5728 if (CmpYZ.has_value())
5729 return replaceInstUsesWith(I, V: ConstantInt::getBool(Ty: I.getType(), V: *CmpYZ));
5730 return ICmpInst::Create(Op: Instruction::ICmp, Pred, S1: Y, S2: Z);
5731 };
5732
5733 switch (Pred) {
5734 case ICmpInst::ICMP_EQ:
5735 case ICmpInst::ICMP_NE: {
5736 // If X == Z:
5737 // Expr Result
5738 // min(X, Y) == Z X <= Y
5739 // max(X, Y) == Z X >= Y
5740 // min(X, Y) != Z X > Y
5741 // max(X, Y) != Z X < Y
5742 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5743 ICmpInst::Predicate NewPred =
5744 ICmpInst::getNonStrictPredicate(pred: MinMax->getPredicate());
5745 if (Pred == ICmpInst::ICMP_NE)
5746 NewPred = ICmpInst::getInversePredicate(pred: NewPred);
5747 return ICmpInst::Create(Op: Instruction::ICmp, Pred: NewPred, S1: X, S2: Y);
5748 }
5749 // Otherwise (X != Z):
5750 ICmpInst::Predicate NewPred = MinMax->getPredicate();
5751 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred: NewPred, LHS: X, RHS: Z, Q));
5752 if (!MinMaxCmpXZ.has_value()) {
5753 std::swap(a&: X, b&: Y);
5754 std::swap(lhs&: CmpXZ, rhs&: CmpYZ);
5755 // Re-check pre-condition X != Z
5756 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5757 break;
5758 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred: NewPred, LHS: X, RHS: Z, Q));
5759 }
5760 if (!MinMaxCmpXZ.has_value())
5761 break;
5762 if (*MinMaxCmpXZ) {
5763 // Expr Fact Result
5764 // min(X, Y) == Z X < Z false
5765 // max(X, Y) == Z X > Z false
5766 // min(X, Y) != Z X < Z true
5767 // max(X, Y) != Z X > Z true
5768 return replaceInstUsesWith(
5769 I, V: ConstantInt::getBool(Ty: I.getType(), V: Pred == ICmpInst::ICMP_NE));
5770 } else {
5771 // Expr Fact Result
5772 // min(X, Y) == Z X > Z Y == Z
5773 // max(X, Y) == Z X < Z Y == Z
5774 // min(X, Y) != Z X > Z Y != Z
5775 // max(X, Y) != Z X < Z Y != Z
5776 return FoldIntoCmpYZ();
5777 }
5778 break;
5779 }
5780 case ICmpInst::ICMP_SLT:
5781 case ICmpInst::ICMP_ULT:
5782 case ICmpInst::ICMP_SLE:
5783 case ICmpInst::ICMP_ULE:
5784 case ICmpInst::ICMP_SGT:
5785 case ICmpInst::ICMP_UGT:
5786 case ICmpInst::ICMP_SGE:
5787 case ICmpInst::ICMP_UGE: {
5788 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(pred: Pred);
5789 if (*CmpXZ) {
5790 if (IsSame) {
5791 // Expr Fact Result
5792 // min(X, Y) < Z X < Z true
5793 // min(X, Y) <= Z X <= Z true
5794 // max(X, Y) > Z X > Z true
5795 // max(X, Y) >= Z X >= Z true
5796 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
5797 } else {
5798 // Expr Fact Result
5799 // max(X, Y) < Z X < Z Y < Z
5800 // max(X, Y) <= Z X <= Z Y <= Z
5801 // min(X, Y) > Z X > Z Y > Z
5802 // min(X, Y) >= Z X >= Z Y >= Z
5803 return FoldIntoCmpYZ();
5804 }
5805 } else {
5806 if (IsSame) {
5807 // Expr Fact Result
5808 // min(X, Y) < Z X >= Z Y < Z
5809 // min(X, Y) <= Z X > Z Y <= Z
5810 // max(X, Y) > Z X <= Z Y > Z
5811 // max(X, Y) >= Z X < Z Y >= Z
5812 return FoldIntoCmpYZ();
5813 } else {
5814 // Expr Fact Result
5815 // max(X, Y) < Z X >= Z false
5816 // max(X, Y) <= Z X > Z false
5817 // min(X, Y) > Z X <= Z false
5818 // min(X, Y) >= Z X < Z false
5819 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
5820 }
5821 }
5822 break;
5823 }
5824 default:
5825 break;
5826 }
5827
5828 return nullptr;
5829}
5830
5831/// Match and fold patterns like:
5832/// icmp eq/ne X, min(max(X, Lo), Hi)
5833/// which represents a range check and can be repsented as a ConstantRange.
5834///
5835/// For icmp eq, build ConstantRange [Lo, Hi + 1) and convert to:
5836/// (X - Lo) u< (Hi + 1 - Lo)
5837/// For icmp ne, build ConstantRange [Hi + 1, Lo) and convert to:
5838/// (X - (Hi + 1)) u< (Lo - (Hi + 1))
5839Instruction *InstCombinerImpl::foldICmpWithClamp(ICmpInst &I, Value *X,
5840 MinMaxIntrinsic *Min) {
5841 if (!I.isEquality() || !Min->hasOneUse() || !Min->isMin())
5842 return nullptr;
5843
5844 const APInt *Lo = nullptr, *Hi = nullptr;
5845 if (Min->isSigned()) {
5846 if (!match(V: Min->getLHS(), P: m_OneUse(SubPattern: m_SMax(L: m_Specific(V: X), R: m_APInt(Res&: Lo)))) ||
5847 !match(V: Min->getRHS(), P: m_APInt(Res&: Hi)) || !Lo->slt(RHS: *Hi))
5848 return nullptr;
5849 } else {
5850 if (!match(V: Min->getLHS(), P: m_OneUse(SubPattern: m_UMax(L: m_Specific(V: X), R: m_APInt(Res&: Lo)))) ||
5851 !match(V: Min->getRHS(), P: m_APInt(Res&: Hi)) || !Lo->ult(RHS: *Hi))
5852 return nullptr;
5853 }
5854
5855 ConstantRange CR = ConstantRange::getNonEmpty(Lower: *Lo, Upper: *Hi + 1);
5856 ICmpInst::Predicate Pred;
5857 APInt C, Offset;
5858 if (I.getPredicate() == ICmpInst::ICMP_EQ)
5859 CR.getEquivalentICmp(Pred, RHS&: C, Offset);
5860 else
5861 CR.inverse().getEquivalentICmp(Pred, RHS&: C, Offset);
5862
5863 if (!Offset.isZero())
5864 X = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: Offset));
5865
5866 return replaceInstUsesWith(
5867 I, V: Builder.CreateICmp(P: Pred, LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: C)));
5868}
5869
5870// Canonicalize checking for a power-of-2-or-zero value:
5871static Instruction *foldICmpPow2Test(ICmpInst &I,
5872 InstCombiner::BuilderTy &Builder) {
5873 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
5874 const CmpInst::Predicate Pred = I.getPredicate();
5875 Value *A = nullptr;
5876 bool CheckIs;
5877 if (I.isEquality()) {
5878 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
5879 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
5880 if (!match(V: Op0, P: m_OneUse(SubPattern: m_c_And(L: m_Add(L: m_Value(V&: A), R: m_AllOnes()),
5881 R: m_Deferred(V: A)))) ||
5882 !match(V: Op1, P: m_ZeroInt()))
5883 A = nullptr;
5884
5885 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
5886 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
5887 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_And(L: m_Neg(V: m_Specific(V: Op1)), R: m_Specific(V: Op1)))))
5888 A = Op1;
5889 else if (match(V: Op1,
5890 P: m_OneUse(SubPattern: m_c_And(L: m_Neg(V: m_Specific(V: Op0)), R: m_Specific(V: Op0)))))
5891 A = Op0;
5892
5893 CheckIs = Pred == ICmpInst::ICMP_EQ;
5894 } else if (ICmpInst::isUnsigned(predicate: Pred)) {
5895 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
5896 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
5897
5898 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5899 match(V: Op0, P: m_OneUse(SubPattern: m_c_Xor(L: m_Add(L: m_Specific(V: Op1), R: m_AllOnes()),
5900 R: m_Specific(V: Op1))))) {
5901 A = Op1;
5902 CheckIs = Pred == ICmpInst::ICMP_UGE;
5903 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5904 match(V: Op1, P: m_OneUse(SubPattern: m_c_Xor(L: m_Add(L: m_Specific(V: Op0), R: m_AllOnes()),
5905 R: m_Specific(V: Op0))))) {
5906 A = Op0;
5907 CheckIs = Pred == ICmpInst::ICMP_ULE;
5908 }
5909 }
5910
5911 if (A) {
5912 Type *Ty = A->getType();
5913 CallInst *CtPop = Builder.CreateUnaryIntrinsic(ID: Intrinsic::ctpop, V: A);
5914 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
5915 ConstantInt::get(Ty, V: 2))
5916 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
5917 ConstantInt::get(Ty, V: 1));
5918 }
5919
5920 return nullptr;
5921}
5922
5923/// Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
5924using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
5925static void collectOffsetOp(Value *V, SmallVectorImpl<OffsetOp> &Offsets,
5926 bool AllowRecursion) {
5927 Instruction *Inst = dyn_cast<Instruction>(Val: V);
5928 if (!Inst || !Inst->hasOneUse())
5929 return;
5930
5931 switch (Inst->getOpcode()) {
5932 case Instruction::Add:
5933 Offsets.emplace_back(Args: Instruction::Sub, Args: Inst->getOperand(i: 1));
5934 Offsets.emplace_back(Args: Instruction::Sub, Args: Inst->getOperand(i: 0));
5935 break;
5936 case Instruction::Sub:
5937 Offsets.emplace_back(Args: Instruction::Add, Args: Inst->getOperand(i: 1));
5938 break;
5939 case Instruction::Xor:
5940 Offsets.emplace_back(Args: Instruction::Xor, Args: Inst->getOperand(i: 1));
5941 Offsets.emplace_back(Args: Instruction::Xor, Args: Inst->getOperand(i: 0));
5942 break;
5943 case Instruction::Shl:
5944 if (Inst->hasNoSignedWrap())
5945 Offsets.emplace_back(Args: Instruction::AShr, Args: Inst->getOperand(i: 1));
5946 if (Inst->hasNoUnsignedWrap())
5947 Offsets.emplace_back(Args: Instruction::LShr, Args: Inst->getOperand(i: 1));
5948 break;
5949 case Instruction::Select:
5950 if (AllowRecursion) {
5951 collectOffsetOp(V: Inst->getOperand(i: 1), Offsets, /*AllowRecursion=*/false);
5952 collectOffsetOp(V: Inst->getOperand(i: 2), Offsets, /*AllowRecursion=*/false);
5953 }
5954 break;
5955 default:
5956 break;
5957 }
5958}
5959
5960enum class OffsetKind { Invalid, Value, Select };
5961
5962struct OffsetResult {
5963 OffsetKind Kind;
5964 Value *V0, *V1, *V2;
5965 Instruction *MDFrom;
5966
5967 static OffsetResult invalid() {
5968 return {.Kind: OffsetKind::Invalid, .V0: nullptr, .V1: nullptr, .V2: nullptr, .MDFrom: nullptr};
5969 }
5970 static OffsetResult value(Value *V) {
5971 return {.Kind: OffsetKind::Value, .V0: V, .V1: nullptr, .V2: nullptr, .MDFrom: nullptr};
5972 }
5973 static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV,
5974 Instruction *MDFrom) {
5975 return {.Kind: OffsetKind::Select, .V0: Cond, .V1: TrueV, .V2: FalseV, .MDFrom: MDFrom};
5976 }
5977 bool isValid() const { return Kind != OffsetKind::Invalid; }
5978 Value *materialize(InstCombiner::BuilderTy &Builder) const {
5979 switch (Kind) {
5980 case OffsetKind::Invalid:
5981 llvm_unreachable("Invalid offset result");
5982 case OffsetKind::Value:
5983 return V0;
5984 case OffsetKind::Select:
5985 return Builder.CreateSelect(
5986 C: V0, True: V1, False: V2, Name: "", MDFrom: ProfcheckDisableMetadataFixes ? nullptr : MDFrom);
5987 }
5988 llvm_unreachable("Unknown OffsetKind enum");
5989 }
5990};
5991
5992/// Offset both sides of an equality icmp to see if we can save some
5993/// instructions: icmp eq/ne X, Y -> icmp eq/ne X op Z, Y op Z.
5994/// Note: This operation should not introduce poison.
5995static Instruction *foldICmpEqualityWithOffset(ICmpInst &I,
5996 InstCombiner::BuilderTy &Builder,
5997 const SimplifyQuery &SQ) {
5998 assert(I.isEquality() && "Expected an equality icmp");
5999 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
6000 if (!Op0->getType()->isIntOrIntVectorTy())
6001 return nullptr;
6002
6003 SmallVector<OffsetOp, 4> OffsetOps;
6004 collectOffsetOp(V: Op0, Offsets&: OffsetOps, /*AllowRecursion=*/true);
6005 collectOffsetOp(V: Op1, Offsets&: OffsetOps, /*AllowRecursion=*/true);
6006
6007 auto ApplyOffsetImpl = [&](Value *V, unsigned BinOpc, Value *RHS) -> Value * {
6008 switch (BinOpc) {
6009 // V = shl nsw X, RHS => X = ashr V, RHS
6010 case Instruction::AShr: {
6011 const APInt *CV, *CRHS;
6012 if (!(match(V, P: m_APInt(Res&: CV)) && match(V: RHS, P: m_APInt(Res&: CRHS)) &&
6013 CV->ashr(ShiftAmt: *CRHS).shl(ShiftAmt: *CRHS) == *CV) &&
6014 !match(V, P: m_NSWShl(L: m_Value(), R: m_Specific(V: RHS))))
6015 return nullptr;
6016 break;
6017 }
6018 // V = shl nuw X, RHS => X = lshr V, RHS
6019 case Instruction::LShr: {
6020 const APInt *CV, *CRHS;
6021 if (!(match(V, P: m_APInt(Res&: CV)) && match(V: RHS, P: m_APInt(Res&: CRHS)) &&
6022 CV->lshr(ShiftAmt: *CRHS).shl(ShiftAmt: *CRHS) == *CV) &&
6023 !match(V, P: m_NUWShl(L: m_Value(), R: m_Specific(V: RHS))))
6024 return nullptr;
6025 break;
6026 }
6027 default:
6028 break;
6029 }
6030
6031 Value *Simplified = simplifyBinOp(Opcode: BinOpc, LHS: V, RHS, Q: SQ);
6032 if (!Simplified)
6033 return nullptr;
6034 // Reject constant expressions as they don't simplify things.
6035 if (isa<Constant>(Val: Simplified) && !match(V: Simplified, P: m_ImmConstant()))
6036 return nullptr;
6037 // Check if the transformation introduces poison.
6038 return impliesPoison(ValAssumedPoison: RHS, V) ? Simplified : nullptr;
6039 };
6040
6041 auto ApplyOffset = [&](Value *V, unsigned BinOpc,
6042 Value *RHS) -> OffsetResult {
6043 if (auto *Sel = dyn_cast<SelectInst>(Val: V)) {
6044 if (!Sel->hasOneUse())
6045 return OffsetResult::invalid();
6046 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc, RHS);
6047 if (!TrueVal)
6048 return OffsetResult::invalid();
6049 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc, RHS);
6050 if (!FalseVal)
6051 return OffsetResult::invalid();
6052 return OffsetResult::select(Cond: Sel->getCondition(), TrueV: TrueVal, FalseV: FalseVal, MDFrom: Sel);
6053 }
6054 if (Value *Simplified = ApplyOffsetImpl(V, BinOpc, RHS))
6055 return OffsetResult::value(V: Simplified);
6056 return OffsetResult::invalid();
6057 };
6058
6059 for (auto [BinOp, RHS] : OffsetOps) {
6060 auto BinOpc = static_cast<unsigned>(BinOp);
6061
6062 auto Op0Result = ApplyOffset(Op0, BinOpc, RHS);
6063 if (!Op0Result.isValid())
6064 continue;
6065 auto Op1Result = ApplyOffset(Op1, BinOpc, RHS);
6066 if (!Op1Result.isValid())
6067 continue;
6068
6069 Value *NewLHS = Op0Result.materialize(Builder);
6070 Value *NewRHS = Op1Result.materialize(Builder);
6071 return new ICmpInst(I.getPredicate(), NewLHS, NewRHS);
6072 }
6073
6074 return nullptr;
6075}
6076
6077Instruction *InstCombinerImpl::foldICmpEquality(ICmpInst &I) {
6078 if (!I.isEquality())
6079 return nullptr;
6080
6081 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
6082 const CmpInst::Predicate Pred = I.getPredicate();
6083 Value *A, *B, *C, *D;
6084 if (match(V: Op0, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B)))) {
6085 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6086 Value *OtherVal = A == Op1 ? B : A;
6087 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(Ty: A->getType()));
6088 }
6089
6090 if (match(V: Op1, P: m_Xor(L: m_Value(V&: C), R: m_Value(V&: D)))) {
6091 // A^c1 == C^c2 --> A == C^(c1^c2)
6092 ConstantInt *C1, *C2;
6093 if (match(V: B, P: m_ConstantInt(CI&: C1)) && match(V: D, P: m_ConstantInt(CI&: C2)) &&
6094 Op1->hasOneUse()) {
6095 Constant *NC = Builder.getInt(AI: C1->getValue() ^ C2->getValue());
6096 Value *Xor = Builder.CreateXor(LHS: C, RHS: NC);
6097 return new ICmpInst(Pred, A, Xor);
6098 }
6099
6100 // A^B == A^D -> B == D
6101 if (A == C)
6102 return new ICmpInst(Pred, B, D);
6103 if (A == D)
6104 return new ICmpInst(Pred, B, C);
6105 if (B == C)
6106 return new ICmpInst(Pred, A, D);
6107 if (B == D)
6108 return new ICmpInst(Pred, A, C);
6109 }
6110 }
6111
6112 if (match(V: Op1, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))) && (A == Op0 || B == Op0)) {
6113 // A == (A^B) -> B == 0
6114 Value *OtherVal = A == Op0 ? B : A;
6115 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(Ty: A->getType()));
6116 }
6117
6118 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6119 if (match(V: Op0, P: m_And(L: m_Value(V&: A), R: m_Value(V&: B))) &&
6120 match(V: Op1, P: m_And(L: m_Value(V&: C), R: m_Value(V&: D)))) {
6121 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
6122
6123 if (A == C) {
6124 X = B;
6125 Y = D;
6126 Z = A;
6127 } else if (A == D) {
6128 X = B;
6129 Y = C;
6130 Z = A;
6131 } else if (B == C) {
6132 X = A;
6133 Y = D;
6134 Z = B;
6135 } else if (B == D) {
6136 X = A;
6137 Y = C;
6138 Z = B;
6139 }
6140
6141 if (X) {
6142 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
6143 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
6144 // instructions.
6145 const APInt *C0, *C1;
6146 bool XorIsNegP2 = match(V: X, P: m_APInt(Res&: C0)) && match(V: Y, P: m_APInt(Res&: C1)) &&
6147 (*C0 ^ *C1).isNegatedPowerOf2();
6148
6149 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
6150 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
6151 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
6152 int UseCnt =
6153 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
6154 (int(match(V: X, P: m_ImmConstant()) && match(V: Y, P: m_ImmConstant())));
6155 if (XorIsNegP2 || UseCnt >= 2) {
6156 // Build (X^Y) & Z
6157 Op1 = Builder.CreateXor(LHS: X, RHS: Y);
6158 Op1 = Builder.CreateAnd(LHS: Op1, RHS: Z);
6159 return new ICmpInst(Pred, Op1, Constant::getNullValue(Ty: Op1->getType()));
6160 }
6161 }
6162 }
6163
6164 {
6165 // Similar to above, but specialized for constant because invert is needed:
6166 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
6167 Value *X, *Y;
6168 Constant *C;
6169 if (match(V: Op0, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: X), R: m_Constant(C)))) &&
6170 match(V: Op1, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: Y), R: m_Specific(V: C))))) {
6171 Value *Xor = Builder.CreateXor(LHS: X, RHS: Y);
6172 Value *And = Builder.CreateAnd(LHS: Xor, RHS: ConstantExpr::getNot(C));
6173 return new ICmpInst(Pred, And, Constant::getNullValue(Ty: And->getType()));
6174 }
6175 }
6176
6177 if (match(V: Op1, P: m_ZExt(Op: m_Value(V&: A))) &&
6178 (Op0->hasOneUse() || Op1->hasOneUse())) {
6179 // (B & (Pow2C-1)) == zext A --> A == trunc B
6180 // (B & (Pow2C-1)) != zext A --> A != trunc B
6181 const APInt *MaskC;
6182 if (match(V: Op0, P: m_And(L: m_Value(V&: B), R: m_LowBitMask(V&: MaskC))) &&
6183 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
6184 return new ICmpInst(Pred, A, Builder.CreateTrunc(V: B, DestTy: A->getType()));
6185 }
6186
6187 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
6188 // For lshr and ashr pairs.
6189 const APInt *AP1, *AP2;
6190 if ((match(V: Op0, P: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: A), R: m_APIntAllowPoison(Res&: AP1)))) &&
6191 match(V: Op1, P: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: B), R: m_APIntAllowPoison(Res&: AP2))))) ||
6192 (match(V: Op0, P: m_OneUse(SubPattern: m_AShr(L: m_Value(V&: A), R: m_APIntAllowPoison(Res&: AP1)))) &&
6193 match(V: Op1, P: m_OneUse(SubPattern: m_AShr(L: m_Value(V&: B), R: m_APIntAllowPoison(Res&: AP2)))))) {
6194 if (*AP1 != *AP2)
6195 return nullptr;
6196 unsigned TypeBits = AP1->getBitWidth();
6197 unsigned ShAmt = AP1->getLimitedValue(Limit: TypeBits);
6198 if (ShAmt < TypeBits && ShAmt != 0) {
6199 ICmpInst::Predicate NewPred =
6200 Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6201 Value *Xor = Builder.CreateXor(LHS: A, RHS: B, Name: I.getName() + ".unshifted");
6202 APInt CmpVal = APInt::getOneBitSet(numBits: TypeBits, BitNo: ShAmt);
6203 return new ICmpInst(NewPred, Xor, ConstantInt::get(Ty: A->getType(), V: CmpVal));
6204 }
6205 }
6206
6207 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
6208 ConstantInt *Cst1;
6209 if (match(V: Op0, P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: A), R: m_ConstantInt(CI&: Cst1)))) &&
6210 match(V: Op1, P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: B), R: m_Specific(V: Cst1))))) {
6211 unsigned TypeBits = Cst1->getBitWidth();
6212 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(Limit: TypeBits);
6213 if (ShAmt < TypeBits && ShAmt != 0) {
6214 Value *Xor = Builder.CreateXor(LHS: A, RHS: B, Name: I.getName() + ".unshifted");
6215 APInt AndVal = APInt::getLowBitsSet(numBits: TypeBits, loBitsSet: TypeBits - ShAmt);
6216 Value *And =
6217 Builder.CreateAnd(LHS: Xor, RHS: Builder.getInt(AI: AndVal), Name: I.getName() + ".mask");
6218 return new ICmpInst(Pred, And, Constant::getNullValue(Ty: Cst1->getType()));
6219 }
6220 }
6221
6222 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
6223 // "icmp (and X, mask), cst"
6224 uint64_t ShAmt = 0;
6225 if (Op0->hasOneUse() &&
6226 match(V: Op0, P: m_Trunc(Op: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: A), R: m_ConstantInt(V&: ShAmt))))) &&
6227 match(V: Op1, P: m_ConstantInt(CI&: Cst1)) &&
6228 // Only do this when A has multiple uses. This is most important to do
6229 // when it exposes other optimizations.
6230 !A->hasOneUse()) {
6231 unsigned ASize = cast<IntegerType>(Val: A->getType())->getPrimitiveSizeInBits();
6232
6233 if (ShAmt < ASize) {
6234 APInt MaskV =
6235 APInt::getLowBitsSet(numBits: ASize, loBitsSet: Op0->getType()->getPrimitiveSizeInBits());
6236 MaskV <<= ShAmt;
6237
6238 APInt CmpV = Cst1->getValue().zext(width: ASize);
6239 CmpV <<= ShAmt;
6240
6241 Value *Mask = Builder.CreateAnd(LHS: A, RHS: Builder.getInt(AI: MaskV));
6242 return new ICmpInst(Pred, Mask, Builder.getInt(AI: CmpV));
6243 }
6244 }
6245
6246 if (Instruction *ICmp = foldICmpIntrinsicWithIntrinsic(Cmp&: I, Builder))
6247 return ICmp;
6248
6249 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
6250 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
6251 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
6252 // few steps of instcombine.
6253 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6254 if (match(V: Op0, P: m_AShr(L: m_Trunc(Op: m_Value(V&: A)), R: m_SpecificInt(V: BitWidth - 1))) &&
6255 match(V: Op1, P: m_Trunc(Op: m_LShr(L: m_Specific(V: A), R: m_SpecificInt(V: BitWidth)))) &&
6256 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
6257 (I.getOperand(i_nocapture: 0)->hasOneUse() || I.getOperand(i_nocapture: 1)->hasOneUse())) {
6258 APInt C = APInt::getOneBitSet(numBits: BitWidth * 2, BitNo: BitWidth - 1);
6259 Value *Add = Builder.CreateAdd(LHS: A, RHS: ConstantInt::get(Ty: A->getType(), V: C));
6260 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
6261 : ICmpInst::ICMP_UGE,
6262 Add, ConstantInt::get(Ty: A->getType(), V: C.shl(shiftAmt: 1)));
6263 }
6264
6265 // Canonicalize:
6266 // Assume B_Pow2 != 0
6267 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
6268 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
6269 if (match(V: Op0, P: m_c_And(L: m_Specific(V: Op1), R: m_Value())) &&
6270 isKnownToBeAPowerOfTwo(V: Op1, /* OrZero */ false, CxtI: &I))
6271 return new ICmpInst(CmpInst::getInversePredicate(pred: Pred), Op0,
6272 ConstantInt::getNullValue(Ty: Op0->getType()));
6273
6274 if (match(V: Op1, P: m_c_And(L: m_Specific(V: Op0), R: m_Value())) &&
6275 isKnownToBeAPowerOfTwo(V: Op0, /* OrZero */ false, CxtI: &I))
6276 return new ICmpInst(CmpInst::getInversePredicate(pred: Pred), Op1,
6277 ConstantInt::getNullValue(Ty: Op1->getType()));
6278
6279 // Canonicalize:
6280 // icmp eq/ne X, OneUse(rotate-right(X))
6281 // -> icmp eq/ne X, rotate-left(X)
6282 // We generally try to convert rotate-right -> rotate-left, this just
6283 // canonicalizes another case.
6284 if (match(V: &I, P: m_c_ICmp(L: m_Value(V&: A),
6285 R: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::fshr>(
6286 Op0: m_Deferred(V: A), Op1: m_Deferred(V: A), Op2: m_Value(V&: B))))))
6287 return new ICmpInst(
6288 Pred, A,
6289 Builder.CreateIntrinsic(RetTy: Op0->getType(), ID: Intrinsic::fshl, Args: {A, A, B}));
6290
6291 // Canonicalize:
6292 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
6293 Constant *Cst;
6294 if (match(V: &I, P: m_c_ICmp(L: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: A), R: m_ImmConstant(C&: Cst))),
6295 R: m_CombineAnd(L: m_Value(V&: B), R: m_Unless(M: m_ImmConstant())))))
6296 return new ICmpInst(Pred, Builder.CreateXor(LHS: A, RHS: B), Cst);
6297
6298 {
6299 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6300 auto m_Matcher =
6301 m_CombineOr(L: m_CombineOr(L: m_c_Add(L: m_Value(V&: B), R: m_Deferred(V: A)),
6302 R: m_c_Xor(L: m_Value(V&: B), R: m_Deferred(V: A))),
6303 R: m_Sub(L: m_Value(V&: B), R: m_Deferred(V: A)));
6304 std::optional<bool> IsZero = std::nullopt;
6305 if (match(V: &I, P: m_c_ICmp(L: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: A), R: m_Matcher)),
6306 R: m_Deferred(V: A))))
6307 IsZero = false;
6308 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6309 else if (match(V: &I,
6310 P: m_ICmp(L: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: A), R: m_Matcher)), R: m_Zero())))
6311 IsZero = true;
6312
6313 if (IsZero && isKnownToBeAPowerOfTwo(V: A, /* OrZero */ true, CxtI: &I))
6314 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6315 // -> (icmp eq/ne (and X, P2), 0)
6316 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6317 // -> (icmp eq/ne (and X, P2), P2)
6318 return new ICmpInst(Pred, Builder.CreateAnd(LHS: B, RHS: A),
6319 *IsZero ? A
6320 : ConstantInt::getNullValue(Ty: A->getType()));
6321 }
6322
6323 if (auto *Res = foldICmpEqualityWithOffset(
6324 I, Builder, SQ: getSimplifyQuery().getWithInstruction(I: &I)))
6325 return Res;
6326
6327 return nullptr;
6328}
6329
6330Instruction *InstCombinerImpl::foldICmpWithTrunc(ICmpInst &ICmp) {
6331 ICmpInst::Predicate Pred = ICmp.getPredicate();
6332 Value *Op0 = ICmp.getOperand(i_nocapture: 0), *Op1 = ICmp.getOperand(i_nocapture: 1);
6333
6334 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6335 // The trunc masks high bits while the compare may effectively mask low bits.
6336 Value *X;
6337 const APInt *C;
6338 if (!match(V: Op0, P: m_OneUse(SubPattern: m_Trunc(Op: m_Value(V&: X)))) || !match(V: Op1, P: m_APInt(Res&: C)))
6339 return nullptr;
6340
6341 // This matches patterns corresponding to tests of the signbit as well as:
6342 // (trunc X) pred C2 --> (X & Mask) == C
6343 if (auto Res = decomposeBitTestICmp(LHS: Op0, RHS: Op1, Pred, /*LookThroughTrunc=*/true,
6344 /*AllowNonZeroC=*/true)) {
6345 Value *And = Builder.CreateAnd(LHS: Res->X, RHS: Res->Mask);
6346 Constant *C = ConstantInt::get(Ty: Res->X->getType(), V: Res->C);
6347 return new ICmpInst(Res->Pred, And, C);
6348 }
6349
6350 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6351 if (auto *II = dyn_cast<IntrinsicInst>(Val: X)) {
6352 if (II->getIntrinsicID() == Intrinsic::cttz ||
6353 II->getIntrinsicID() == Intrinsic::ctlz) {
6354 unsigned MaxRet = SrcBits;
6355 // If the "is_zero_poison" argument is set, then we know at least
6356 // one bit is set in the input, so the result is always at least one
6357 // less than the full bitwidth of that input.
6358 if (match(V: II->getArgOperand(i: 1), P: m_One()))
6359 MaxRet--;
6360
6361 // Make sure the destination is wide enough to hold the largest output of
6362 // the intrinsic.
6363 if (llvm::Log2_32(Value: MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6364 if (Instruction *I =
6365 foldICmpIntrinsicWithConstant(Cmp&: ICmp, II, C: C->zext(width: SrcBits)))
6366 return I;
6367 }
6368 }
6369
6370 return nullptr;
6371}
6372
6373Instruction *InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst &ICmp) {
6374 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6375 auto *CastOp0 = cast<CastInst>(Val: ICmp.getOperand(i_nocapture: 0));
6376 Value *X;
6377 if (!match(V: CastOp0, P: m_ZExtOrSExt(Op: m_Value(V&: X))))
6378 return nullptr;
6379
6380 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6381 bool IsSignedCmp = ICmp.isSigned();
6382
6383 // icmp Pred (ext X), (ext Y)
6384 Value *Y;
6385 if (match(V: ICmp.getOperand(i_nocapture: 1), P: m_ZExtOrSExt(Op: m_Value(V&: Y)))) {
6386 bool IsZext0 = isa<ZExtInst>(Val: ICmp.getOperand(i_nocapture: 0));
6387 bool IsZext1 = isa<ZExtInst>(Val: ICmp.getOperand(i_nocapture: 1));
6388
6389 if (IsZext0 != IsZext1) {
6390 // If X and Y and both i1
6391 // (icmp eq/ne (zext X) (sext Y))
6392 // eq -> (icmp eq (or X, Y), 0)
6393 // ne -> (icmp ne (or X, Y), 0)
6394 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(BitWidth: 1) &&
6395 Y->getType()->isIntOrIntVectorTy(BitWidth: 1))
6396 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(LHS: X, RHS: Y),
6397 Constant::getNullValue(Ty: X->getType()));
6398
6399 // If we have mismatched casts and zext has the nneg flag, we can
6400 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6401
6402 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(Val: ICmp.getOperand(i_nocapture: 0));
6403 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(Val: ICmp.getOperand(i_nocapture: 1));
6404
6405 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6406 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6407
6408 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6409 IsSignedExt = true;
6410 else
6411 return nullptr;
6412 }
6413
6414 // Not an extension from the same type?
6415 Type *XTy = X->getType(), *YTy = Y->getType();
6416 if (XTy != YTy) {
6417 // One of the casts must have one use because we are creating a new cast.
6418 if (!ICmp.getOperand(i_nocapture: 0)->hasOneUse() && !ICmp.getOperand(i_nocapture: 1)->hasOneUse())
6419 return nullptr;
6420 // Extend the narrower operand to the type of the wider operand.
6421 CastInst::CastOps CastOpcode =
6422 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6423 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6424 X = Builder.CreateCast(Op: CastOpcode, V: X, DestTy: YTy);
6425 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6426 Y = Builder.CreateCast(Op: CastOpcode, V: Y, DestTy: XTy);
6427 else
6428 return nullptr;
6429 }
6430
6431 // (zext X) == (zext Y) --> X == Y
6432 // (sext X) == (sext Y) --> X == Y
6433 if (ICmp.isEquality())
6434 return new ICmpInst(ICmp.getPredicate(), X, Y);
6435
6436 // A signed comparison of sign extended values simplifies into a
6437 // signed comparison.
6438 if (IsSignedCmp && IsSignedExt)
6439 return new ICmpInst(ICmp.getPredicate(), X, Y);
6440
6441 // The other three cases all fold into an unsigned comparison.
6442 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6443 }
6444
6445 // Below here, we are only folding a compare with constant.
6446 auto *C = dyn_cast<Constant>(Val: ICmp.getOperand(i_nocapture: 1));
6447 if (!C)
6448 return nullptr;
6449
6450 // If a lossless truncate is possible...
6451 Type *SrcTy = CastOp0->getSrcTy();
6452 Constant *Res = getLosslessInvCast(C, InvCastTo: SrcTy, CastOp: CastOp0->getOpcode(), DL);
6453 if (Res) {
6454 if (ICmp.isEquality())
6455 return new ICmpInst(ICmp.getPredicate(), X, Res);
6456
6457 // A signed comparison of sign extended values simplifies into a
6458 // signed comparison.
6459 if (IsSignedExt && IsSignedCmp)
6460 return new ICmpInst(ICmp.getPredicate(), X, Res);
6461
6462 // The other three cases all fold into an unsigned comparison.
6463 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6464 }
6465
6466 // The re-extended constant changed, partly changed (in the case of a vector),
6467 // or could not be determined to be equal (in the case of a constant
6468 // expression), so the constant cannot be represented in the shorter type.
6469 // All the cases that fold to true or false will have already been handled
6470 // by simplifyICmpInst, so only deal with the tricky case.
6471 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(Val: C))
6472 return nullptr;
6473
6474 // Is source op positive?
6475 // icmp ult (sext X), C --> icmp sgt X, -1
6476 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6477 return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(Ty: SrcTy));
6478
6479 // Is source op negative?
6480 // icmp ugt (sext X), C --> icmp slt X, 0
6481 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6482 return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(Ty: SrcTy));
6483}
6484
6485/// Handle icmp (cast x), (cast or constant).
6486Instruction *InstCombinerImpl::foldICmpWithCastOp(ICmpInst &ICmp) {
6487 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6488 // icmp compares only pointer's value.
6489 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6490 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(Val: ICmp.getOperand(i_nocapture: 0));
6491 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(Val: ICmp.getOperand(i_nocapture: 1));
6492 if (SimplifiedOp0 || SimplifiedOp1)
6493 return new ICmpInst(ICmp.getPredicate(),
6494 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(i_nocapture: 0),
6495 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(i_nocapture: 1));
6496
6497 auto *CastOp0 = dyn_cast<CastInst>(Val: ICmp.getOperand(i_nocapture: 0));
6498 if (!CastOp0)
6499 return nullptr;
6500 if (!isa<Constant>(Val: ICmp.getOperand(i_nocapture: 1)) && !isa<CastInst>(Val: ICmp.getOperand(i_nocapture: 1)))
6501 return nullptr;
6502
6503 Value *Op0Src = CastOp0->getOperand(i_nocapture: 0);
6504 Type *SrcTy = CastOp0->getSrcTy();
6505 Type *DestTy = CastOp0->getDestTy();
6506
6507 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6508 // integer type is the same size as the pointer type.
6509 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6510 if (isa<VectorType>(Val: PtrTy)) {
6511 PtrTy = cast<VectorType>(Val: PtrTy)->getElementType();
6512 IntTy = cast<VectorType>(Val: IntTy)->getElementType();
6513 }
6514 return DL.getPointerTypeSizeInBits(PtrTy) == IntTy->getIntegerBitWidth();
6515 };
6516 if (CastOp0->getOpcode() == Instruction::PtrToInt &&
6517 CompatibleSizes(SrcTy, DestTy)) {
6518 Value *NewOp1 = nullptr;
6519 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(Val: ICmp.getOperand(i_nocapture: 1))) {
6520 Value *PtrSrc = PtrToIntOp1->getOperand(i_nocapture: 0);
6521 if (PtrSrc->getType() == Op0Src->getType())
6522 NewOp1 = PtrToIntOp1->getOperand(i_nocapture: 0);
6523 } else if (auto *RHSC = dyn_cast<Constant>(Val: ICmp.getOperand(i_nocapture: 1))) {
6524 NewOp1 = ConstantExpr::getIntToPtr(C: RHSC, Ty: SrcTy);
6525 }
6526
6527 if (NewOp1)
6528 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6529 }
6530
6531 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6532 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6533 CompatibleSizes(DestTy, SrcTy)) {
6534 Value *NewOp1 = nullptr;
6535 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(Val: ICmp.getOperand(i_nocapture: 1))) {
6536 Value *IntSrc = IntToPtrOp1->getOperand(i_nocapture: 0);
6537 if (IntSrc->getType() == Op0Src->getType())
6538 NewOp1 = IntToPtrOp1->getOperand(i_nocapture: 0);
6539 } else if (auto *RHSC = dyn_cast<Constant>(Val: ICmp.getOperand(i_nocapture: 1))) {
6540 NewOp1 = ConstantFoldConstant(C: ConstantExpr::getPtrToInt(C: RHSC, Ty: SrcTy), DL);
6541 }
6542
6543 if (NewOp1)
6544 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6545 }
6546
6547 if (Instruction *R = foldICmpWithTrunc(ICmp))
6548 return R;
6549
6550 return foldICmpWithZextOrSext(ICmp);
6551}
6552
6553static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS,
6554 bool IsSigned) {
6555 switch (BinaryOp) {
6556 default:
6557 llvm_unreachable("Unsupported binary op");
6558 case Instruction::Add:
6559 case Instruction::Sub:
6560 return match(V: RHS, P: m_Zero());
6561 case Instruction::Mul:
6562 return !(RHS->getType()->isIntOrIntVectorTy(BitWidth: 1) && IsSigned) &&
6563 match(V: RHS, P: m_One());
6564 }
6565}
6566
6567OverflowResult
6568InstCombinerImpl::computeOverflow(Instruction::BinaryOps BinaryOp,
6569 bool IsSigned, Value *LHS, Value *RHS,
6570 Instruction *CxtI) const {
6571 switch (BinaryOp) {
6572 default:
6573 llvm_unreachable("Unsupported binary op");
6574 case Instruction::Add:
6575 if (IsSigned)
6576 return computeOverflowForSignedAdd(LHS, RHS, CxtI);
6577 else
6578 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
6579 case Instruction::Sub:
6580 if (IsSigned)
6581 return computeOverflowForSignedSub(LHS, RHS, CxtI);
6582 else
6583 return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
6584 case Instruction::Mul:
6585 if (IsSigned)
6586 return computeOverflowForSignedMul(LHS, RHS, CxtI);
6587 else
6588 return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
6589 }
6590}
6591
6592bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6593 bool IsSigned, Value *LHS,
6594 Value *RHS, Instruction &OrigI,
6595 Value *&Result,
6596 Constant *&Overflow) {
6597 if (OrigI.isCommutative() && isa<Constant>(Val: LHS) && !isa<Constant>(Val: RHS))
6598 std::swap(a&: LHS, b&: RHS);
6599
6600 // If the overflow check was an add followed by a compare, the insertion point
6601 // may be pointing to the compare. We want to insert the new instructions
6602 // before the add in case there are uses of the add between the add and the
6603 // compare.
6604 Builder.SetInsertPoint(&OrigI);
6605
6606 Type *OverflowTy = Type::getInt1Ty(C&: LHS->getContext());
6607 if (auto *LHSTy = dyn_cast<VectorType>(Val: LHS->getType()))
6608 OverflowTy = VectorType::get(ElementType: OverflowTy, EC: LHSTy->getElementCount());
6609
6610 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6611 Result = LHS;
6612 Overflow = ConstantInt::getFalse(Ty: OverflowTy);
6613 return true;
6614 }
6615
6616 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, CxtI: &OrigI)) {
6617 case OverflowResult::MayOverflow:
6618 return false;
6619 case OverflowResult::AlwaysOverflowsLow:
6620 case OverflowResult::AlwaysOverflowsHigh:
6621 Result = Builder.CreateBinOp(Opc: BinaryOp, LHS, RHS);
6622 Result->takeName(V: &OrigI);
6623 Overflow = ConstantInt::getTrue(Ty: OverflowTy);
6624 return true;
6625 case OverflowResult::NeverOverflows:
6626 Result = Builder.CreateBinOp(Opc: BinaryOp, LHS, RHS);
6627 Result->takeName(V: &OrigI);
6628 Overflow = ConstantInt::getFalse(Ty: OverflowTy);
6629 if (auto *Inst = dyn_cast<Instruction>(Val: Result)) {
6630 if (IsSigned)
6631 Inst->setHasNoSignedWrap();
6632 else
6633 Inst->setHasNoUnsignedWrap();
6634 }
6635 return true;
6636 }
6637
6638 llvm_unreachable("Unexpected overflow result");
6639}
6640
6641/// Recognize and process idiom involving test for multiplication
6642/// overflow.
6643///
6644/// The caller has matched a pattern of the form:
6645/// I = cmp u (mul(zext A, zext B), V
6646/// The function checks if this is a test for overflow and if so replaces
6647/// multiplication with call to 'mul.with.overflow' intrinsic.
6648///
6649/// \param I Compare instruction.
6650/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
6651/// the compare instruction. Must be of integer type.
6652/// \param OtherVal The other argument of compare instruction.
6653/// \returns Instruction which must replace the compare instruction, NULL if no
6654/// replacement required.
6655static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,
6656 const APInt *OtherVal,
6657 InstCombinerImpl &IC) {
6658 // Don't bother doing this transformation for pointers, don't do it for
6659 // vectors.
6660 if (!isa<IntegerType>(Val: MulVal->getType()))
6661 return nullptr;
6662
6663 auto *MulInstr = dyn_cast<Instruction>(Val: MulVal);
6664 if (!MulInstr)
6665 return nullptr;
6666 assert(MulInstr->getOpcode() == Instruction::Mul);
6667
6668 auto *LHS = cast<ZExtInst>(Val: MulInstr->getOperand(i: 0)),
6669 *RHS = cast<ZExtInst>(Val: MulInstr->getOperand(i: 1));
6670 assert(LHS->getOpcode() == Instruction::ZExt);
6671 assert(RHS->getOpcode() == Instruction::ZExt);
6672 Value *A = LHS->getOperand(i_nocapture: 0), *B = RHS->getOperand(i_nocapture: 0);
6673
6674 // Calculate type and width of the result produced by mul.with.overflow.
6675 Type *TyA = A->getType(), *TyB = B->getType();
6676 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6677 WidthB = TyB->getPrimitiveSizeInBits();
6678 unsigned MulWidth;
6679 Type *MulType;
6680 if (WidthB > WidthA) {
6681 MulWidth = WidthB;
6682 MulType = TyB;
6683 } else {
6684 MulWidth = WidthA;
6685 MulType = TyA;
6686 }
6687
6688 // In order to replace the original mul with a narrower mul.with.overflow,
6689 // all uses must ignore upper bits of the product. The number of used low
6690 // bits must be not greater than the width of mul.with.overflow.
6691 if (MulVal->hasNUsesOrMore(N: 2))
6692 for (User *U : MulVal->users()) {
6693 if (U == &I)
6694 continue;
6695 if (TruncInst *TI = dyn_cast<TruncInst>(Val: U)) {
6696 // Check if truncation ignores bits above MulWidth.
6697 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
6698 if (TruncWidth > MulWidth)
6699 return nullptr;
6700 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: U)) {
6701 // Check if AND ignores bits above MulWidth.
6702 if (BO->getOpcode() != Instruction::And)
6703 return nullptr;
6704 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: BO->getOperand(i_nocapture: 1))) {
6705 const APInt &CVal = CI->getValue();
6706 if (CVal.getBitWidth() - CVal.countl_zero() > MulWidth)
6707 return nullptr;
6708 } else {
6709 // In this case we could have the operand of the binary operation
6710 // being defined in another block, and performing the replacement
6711 // could break the dominance relation.
6712 return nullptr;
6713 }
6714 } else {
6715 // Other uses prohibit this transformation.
6716 return nullptr;
6717 }
6718 }
6719
6720 // Recognize patterns
6721 switch (I.getPredicate()) {
6722 case ICmpInst::ICMP_UGT: {
6723 // Recognize pattern:
6724 // mulval = mul(zext A, zext B)
6725 // cmp ugt mulval, max
6726 APInt MaxVal = APInt::getMaxValue(numBits: MulWidth);
6727 MaxVal = MaxVal.zext(width: OtherVal->getBitWidth());
6728 if (MaxVal.eq(RHS: *OtherVal))
6729 break; // Recognized
6730 return nullptr;
6731 }
6732
6733 case ICmpInst::ICMP_ULT: {
6734 // Recognize pattern:
6735 // mulval = mul(zext A, zext B)
6736 // cmp ule mulval, max + 1
6737 APInt MaxVal = APInt::getOneBitSet(numBits: OtherVal->getBitWidth(), BitNo: MulWidth);
6738 if (MaxVal.eq(RHS: *OtherVal))
6739 break; // Recognized
6740 return nullptr;
6741 }
6742
6743 default:
6744 return nullptr;
6745 }
6746
6747 InstCombiner::BuilderTy &Builder = IC.Builder;
6748 Builder.SetInsertPoint(MulInstr);
6749
6750 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
6751 Value *MulA = A, *MulB = B;
6752 if (WidthA < MulWidth)
6753 MulA = Builder.CreateZExt(V: A, DestTy: MulType);
6754 if (WidthB < MulWidth)
6755 MulB = Builder.CreateZExt(V: B, DestTy: MulType);
6756 CallInst *Call =
6757 Builder.CreateIntrinsic(ID: Intrinsic::umul_with_overflow, Types: MulType,
6758 Args: {MulA, MulB}, /*FMFSource=*/nullptr, Name: "umul");
6759 IC.addToWorklist(I: MulInstr);
6760
6761 // If there are uses of mul result other than the comparison, we know that
6762 // they are truncation or binary AND. Change them to use result of
6763 // mul.with.overflow and adjust properly mask/size.
6764 if (MulVal->hasNUsesOrMore(N: 2)) {
6765 Value *Mul = Builder.CreateExtractValue(Agg: Call, Idxs: 0, Name: "umul.value");
6766 for (User *U : make_early_inc_range(Range: MulVal->users())) {
6767 if (U == &I)
6768 continue;
6769 if (TruncInst *TI = dyn_cast<TruncInst>(Val: U)) {
6770 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
6771 IC.replaceInstUsesWith(I&: *TI, V: Mul);
6772 else
6773 TI->setOperand(i_nocapture: 0, Val_nocapture: Mul);
6774 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: U)) {
6775 assert(BO->getOpcode() == Instruction::And);
6776 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
6777 ConstantInt *CI = cast<ConstantInt>(Val: BO->getOperand(i_nocapture: 1));
6778 APInt ShortMask = CI->getValue().trunc(width: MulWidth);
6779 Value *ShortAnd = Builder.CreateAnd(LHS: Mul, RHS: ShortMask);
6780 Value *Zext = Builder.CreateZExt(V: ShortAnd, DestTy: BO->getType());
6781 IC.replaceInstUsesWith(I&: *BO, V: Zext);
6782 } else {
6783 llvm_unreachable("Unexpected Binary operation");
6784 }
6785 IC.addToWorklist(I: cast<Instruction>(Val: U));
6786 }
6787 }
6788
6789 // The original icmp gets replaced with the overflow value, maybe inverted
6790 // depending on predicate.
6791 if (I.getPredicate() == ICmpInst::ICMP_ULT) {
6792 Value *Res = Builder.CreateExtractValue(Agg: Call, Idxs: 1);
6793 return BinaryOperator::CreateNot(Op: Res);
6794 }
6795
6796 return ExtractValueInst::Create(Agg: Call, Idxs: 1);
6797}
6798
6799/// When performing a comparison against a constant, it is possible that not all
6800/// the bits in the LHS are demanded. This helper method computes the mask that
6801/// IS demanded.
6802static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) {
6803 const APInt *RHS;
6804 if (!match(V: I.getOperand(i_nocapture: 1), P: m_APInt(Res&: RHS)))
6805 return APInt::getAllOnes(numBits: BitWidth);
6806
6807 // If this is a normal comparison, it demands all bits. If it is a sign bit
6808 // comparison, it only demands the sign bit.
6809 bool UnusedBit;
6810 if (isSignBitCheck(Pred: I.getPredicate(), RHS: *RHS, TrueIfSigned&: UnusedBit))
6811 return APInt::getSignMask(BitWidth);
6812
6813 switch (I.getPredicate()) {
6814 // For a UGT comparison, we don't care about any bits that
6815 // correspond to the trailing ones of the comparand. The value of these
6816 // bits doesn't impact the outcome of the comparison, because any value
6817 // greater than the RHS must differ in a bit higher than these due to carry.
6818 case ICmpInst::ICMP_UGT:
6819 return APInt::getBitsSetFrom(numBits: BitWidth, loBit: RHS->countr_one());
6820
6821 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
6822 // Any value less than the RHS must differ in a higher bit because of carries.
6823 case ICmpInst::ICMP_ULT:
6824 return APInt::getBitsSetFrom(numBits: BitWidth, loBit: RHS->countr_zero());
6825
6826 default:
6827 return APInt::getAllOnes(numBits: BitWidth);
6828 }
6829}
6830
6831/// Check that one use is in the same block as the definition and all
6832/// other uses are in blocks dominated by a given block.
6833///
6834/// \param DI Definition
6835/// \param UI Use
6836/// \param DB Block that must dominate all uses of \p DI outside
6837/// the parent block
6838/// \return true when \p UI is the only use of \p DI in the parent block
6839/// and all other uses of \p DI are in blocks dominated by \p DB.
6840///
6841bool InstCombinerImpl::dominatesAllUses(const Instruction *DI,
6842 const Instruction *UI,
6843 const BasicBlock *DB) const {
6844 assert(DI && UI && "Instruction not defined\n");
6845 // Ignore incomplete definitions.
6846 if (!DI->getParent())
6847 return false;
6848 // DI and UI must be in the same block.
6849 if (DI->getParent() != UI->getParent())
6850 return false;
6851 // Protect from self-referencing blocks.
6852 if (DI->getParent() == DB)
6853 return false;
6854 for (const User *U : DI->users()) {
6855 auto *Usr = cast<Instruction>(Val: U);
6856 if (Usr != UI && !DT.dominates(A: DB, B: Usr->getParent()))
6857 return false;
6858 }
6859 return true;
6860}
6861
6862/// Return true when the instruction sequence within a block is select-cmp-br.
6863static bool isChainSelectCmpBranch(const SelectInst *SI) {
6864 const BasicBlock *BB = SI->getParent();
6865 if (!BB)
6866 return false;
6867 auto *BI = dyn_cast_or_null<BranchInst>(Val: BB->getTerminator());
6868 if (!BI || BI->getNumSuccessors() != 2)
6869 return false;
6870 auto *IC = dyn_cast<ICmpInst>(Val: BI->getCondition());
6871 if (!IC || (IC->getOperand(i_nocapture: 0) != SI && IC->getOperand(i_nocapture: 1) != SI))
6872 return false;
6873 return true;
6874}
6875
6876/// True when a select result is replaced by one of its operands
6877/// in select-icmp sequence. This will eventually result in the elimination
6878/// of the select.
6879///
6880/// \param SI Select instruction
6881/// \param Icmp Compare instruction
6882/// \param SIOpd Operand that replaces the select
6883///
6884/// Notes:
6885/// - The replacement is global and requires dominator information
6886/// - The caller is responsible for the actual replacement
6887///
6888/// Example:
6889///
6890/// entry:
6891/// %4 = select i1 %3, %C* %0, %C* null
6892/// %5 = icmp eq %C* %4, null
6893/// br i1 %5, label %9, label %7
6894/// ...
6895/// ; <label>:7 ; preds = %entry
6896/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
6897/// ...
6898///
6899/// can be transformed to
6900///
6901/// %5 = icmp eq %C* %0, null
6902/// %6 = select i1 %3, i1 %5, i1 true
6903/// br i1 %6, label %9, label %7
6904/// ...
6905/// ; <label>:7 ; preds = %entry
6906/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
6907///
6908/// Similar when the first operand of the select is a constant or/and
6909/// the compare is for not equal rather than equal.
6910///
6911/// NOTE: The function is only called when the select and compare constants
6912/// are equal, the optimization can work only for EQ predicates. This is not a
6913/// major restriction since a NE compare should be 'normalized' to an equal
6914/// compare, which usually happens in the combiner and test case
6915/// select-cmp-br.ll checks for it.
6916bool InstCombinerImpl::replacedSelectWithOperand(SelectInst *SI,
6917 const ICmpInst *Icmp,
6918 const unsigned SIOpd) {
6919 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
6920 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
6921 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(Idx: 1);
6922 // The check for the single predecessor is not the best that can be
6923 // done. But it protects efficiently against cases like when SI's
6924 // home block has two successors, Succ and Succ1, and Succ1 predecessor
6925 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
6926 // replaced can be reached on either path. So the uniqueness check
6927 // guarantees that the path all uses of SI (outside SI's parent) are on
6928 // is disjoint from all other paths out of SI. But that information
6929 // is more expensive to compute, and the trade-off here is in favor
6930 // of compile-time. It should also be noticed that we check for a single
6931 // predecessor and not only uniqueness. This to handle the situation when
6932 // Succ and Succ1 points to the same basic block.
6933 if (Succ->getSinglePredecessor() && dominatesAllUses(DI: SI, UI: Icmp, DB: Succ)) {
6934 NumSel++;
6935 SI->replaceUsesOutsideBlock(V: SI->getOperand(i_nocapture: SIOpd), BB: SI->getParent());
6936 return true;
6937 }
6938 }
6939 return false;
6940}
6941
6942/// Try to fold the comparison based on range information we can get by checking
6943/// whether bits are known to be zero or one in the inputs.
6944Instruction *InstCombinerImpl::foldICmpUsingKnownBits(ICmpInst &I) {
6945 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
6946 Type *Ty = Op0->getType();
6947 ICmpInst::Predicate Pred = I.getPredicate();
6948
6949 // Get scalar or pointer size.
6950 unsigned BitWidth = Ty->isIntOrIntVectorTy()
6951 ? Ty->getScalarSizeInBits()
6952 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
6953
6954 if (!BitWidth)
6955 return nullptr;
6956
6957 KnownBits Op0Known(BitWidth);
6958 KnownBits Op1Known(BitWidth);
6959
6960 {
6961 // Don't use dominating conditions when folding icmp using known bits. This
6962 // may convert signed into unsigned predicates in ways that other passes
6963 // (especially IndVarSimplify) may not be able to reliably undo.
6964 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(I: &I);
6965 if (SimplifyDemandedBits(I: &I, Op: 0, DemandedMask: getDemandedBitsLHSMask(I, BitWidth),
6966 Known&: Op0Known, Q))
6967 return &I;
6968
6969 if (SimplifyDemandedBits(I: &I, Op: 1, DemandedMask: APInt::getAllOnes(numBits: BitWidth), Known&: Op1Known, Q))
6970 return &I;
6971 }
6972
6973 if (!isa<Constant>(Val: Op0) && Op0Known.isConstant())
6974 return new ICmpInst(
6975 Pred, ConstantExpr::getIntegerValue(Ty, V: Op0Known.getConstant()), Op1);
6976 if (!isa<Constant>(Val: Op1) && Op1Known.isConstant())
6977 return new ICmpInst(
6978 Pred, Op0, ConstantExpr::getIntegerValue(Ty, V: Op1Known.getConstant()));
6979
6980 if (std::optional<bool> Res = ICmpInst::compare(LHS: Op0Known, RHS: Op1Known, Pred))
6981 return replaceInstUsesWith(I, V: ConstantInt::getBool(Ty: I.getType(), V: *Res));
6982
6983 // Given the known and unknown bits, compute a range that the LHS could be
6984 // in. Compute the Min, Max and RHS values based on the known bits. For the
6985 // EQ and NE we use unsigned values.
6986 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6987 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6988 if (I.isSigned()) {
6989 Op0Min = Op0Known.getSignedMinValue();
6990 Op0Max = Op0Known.getSignedMaxValue();
6991 Op1Min = Op1Known.getSignedMinValue();
6992 Op1Max = Op1Known.getSignedMaxValue();
6993 } else {
6994 Op0Min = Op0Known.getMinValue();
6995 Op0Max = Op0Known.getMaxValue();
6996 Op1Min = Op1Known.getMinValue();
6997 Op1Max = Op1Known.getMaxValue();
6998 }
6999
7000 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
7001 // min/max canonical compare with some other compare. That could lead to
7002 // conflict with select canonicalization and infinite looping.
7003 // FIXME: This constraint may go away if min/max intrinsics are canonical.
7004 auto isMinMaxCmp = [&](Instruction &Cmp) {
7005 if (!Cmp.hasOneUse())
7006 return false;
7007 Value *A, *B;
7008 SelectPatternFlavor SPF = matchSelectPattern(V: Cmp.user_back(), LHS&: A, RHS&: B).Flavor;
7009 if (!SelectPatternResult::isMinOrMax(SPF))
7010 return false;
7011 return match(V: Op0, P: m_MaxOrMin(L: m_Value(), R: m_Value())) ||
7012 match(V: Op1, P: m_MaxOrMin(L: m_Value(), R: m_Value()));
7013 };
7014 if (!isMinMaxCmp(I)) {
7015 switch (Pred) {
7016 default:
7017 break;
7018 case ICmpInst::ICMP_ULT: {
7019 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
7020 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7021 const APInt *CmpC;
7022 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7023 // A <u C -> A == C-1 if min(A)+1 == C
7024 if (*CmpC == Op0Min + 1)
7025 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7026 ConstantInt::get(Ty: Op1->getType(), V: *CmpC - 1));
7027 // X <u C --> X == 0, if the number of zero bits in the bottom of X
7028 // exceeds the log2 of C.
7029 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
7030 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7031 Constant::getNullValue(Ty: Op1->getType()));
7032 }
7033 break;
7034 }
7035 case ICmpInst::ICMP_UGT: {
7036 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
7037 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7038 const APInt *CmpC;
7039 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7040 // A >u C -> A == C+1 if max(a)-1 == C
7041 if (*CmpC == Op0Max - 1)
7042 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7043 ConstantInt::get(Ty: Op1->getType(), V: *CmpC + 1));
7044 // X >u C --> X != 0, if the number of zero bits in the bottom of X
7045 // exceeds the log2 of C.
7046 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
7047 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
7048 Constant::getNullValue(Ty: Op1->getType()));
7049 }
7050 break;
7051 }
7052 case ICmpInst::ICMP_SLT: {
7053 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
7054 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7055 const APInt *CmpC;
7056 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7057 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
7058 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7059 ConstantInt::get(Ty: Op1->getType(), V: *CmpC - 1));
7060 }
7061 break;
7062 }
7063 case ICmpInst::ICMP_SGT: {
7064 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
7065 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7066 const APInt *CmpC;
7067 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7068 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
7069 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7070 ConstantInt::get(Ty: Op1->getType(), V: *CmpC + 1));
7071 }
7072 break;
7073 }
7074 }
7075 }
7076
7077 // Based on the range information we know about the LHS, see if we can
7078 // simplify this comparison. For example, (x&4) < 8 is always true.
7079 switch (Pred) {
7080 default:
7081 break;
7082 case ICmpInst::ICMP_EQ:
7083 case ICmpInst::ICMP_NE: {
7084 // If all bits are known zero except for one, then we know at most one bit
7085 // is set. If the comparison is against zero, then this is a check to see if
7086 // *that* bit is set.
7087 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
7088 if (Op1Known.isZero()) {
7089 // If the LHS is an AND with the same constant, look through it.
7090 Value *LHS = nullptr;
7091 const APInt *LHSC;
7092 if (!match(V: Op0, P: m_And(L: m_Value(V&: LHS), R: m_APInt(Res&: LHSC))) ||
7093 *LHSC != Op0KnownZeroInverted)
7094 LHS = Op0;
7095
7096 Value *X;
7097 const APInt *C1;
7098 if (match(V: LHS, P: m_Shl(L: m_Power2(V&: C1), R: m_Value(V&: X)))) {
7099 Type *XTy = X->getType();
7100 unsigned Log2C1 = C1->countr_zero();
7101 APInt C2 = Op0KnownZeroInverted;
7102 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
7103 if (C2Pow2.isPowerOf2()) {
7104 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
7105 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
7106 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
7107 unsigned Log2C2 = C2Pow2.countr_zero();
7108 auto *CmpC = ConstantInt::get(Ty: XTy, V: Log2C2 - Log2C1);
7109 auto NewPred =
7110 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
7111 return new ICmpInst(NewPred, X, CmpC);
7112 }
7113 }
7114 }
7115
7116 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
7117 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
7118 (Op0Known & Op1Known) == Op0Known)
7119 return new ICmpInst(CmpInst::getInversePredicate(pred: Pred), Op0,
7120 ConstantInt::getNullValue(Ty: Op1->getType()));
7121 break;
7122 }
7123 case ICmpInst::ICMP_SGE:
7124 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
7125 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7126 break;
7127 case ICmpInst::ICMP_SLE:
7128 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
7129 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7130 break;
7131 case ICmpInst::ICMP_UGE:
7132 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
7133 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7134 break;
7135 case ICmpInst::ICMP_ULE:
7136 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
7137 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7138 break;
7139 }
7140
7141 // Turn a signed comparison into an unsigned one if both operands are known to
7142 // have the same sign. Set samesign if possible (except for equality
7143 // predicates).
7144 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
7145 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
7146 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
7147 I.setPredicate(I.getUnsignedPredicate());
7148 I.setSameSign();
7149 return &I;
7150 }
7151
7152 return nullptr;
7153}
7154
7155/// If one operand of an icmp is effectively a bool (value range of {0,1}),
7156/// then try to reduce patterns based on that limit.
7157Instruction *InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst &I) {
7158 Value *X, *Y;
7159 CmpPredicate Pred;
7160
7161 // X must be 0 and bool must be true for "ULT":
7162 // X <u (zext i1 Y) --> (X == 0) & Y
7163 if (match(V: &I, P: m_c_ICmp(Pred, L: m_Value(V&: X), R: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: Y))))) &&
7164 Y->getType()->isIntOrIntVectorTy(BitWidth: 1) && Pred == ICmpInst::ICMP_ULT)
7165 return BinaryOperator::CreateAnd(V1: Builder.CreateIsNull(Arg: X), V2: Y);
7166
7167 // X must be 0 or bool must be true for "ULE":
7168 // X <=u (sext i1 Y) --> (X == 0) | Y
7169 if (match(V: &I, P: m_c_ICmp(Pred, L: m_Value(V&: X), R: m_OneUse(SubPattern: m_SExt(Op: m_Value(V&: Y))))) &&
7170 Y->getType()->isIntOrIntVectorTy(BitWidth: 1) && Pred == ICmpInst::ICMP_ULE)
7171 return BinaryOperator::CreateOr(V1: Builder.CreateIsNull(Arg: X), V2: Y);
7172
7173 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
7174 CmpPredicate Pred1, Pred2;
7175 const APInt *C;
7176 Instruction *ExtI;
7177 if (match(V: &I, P: m_c_ICmp(Pred&: Pred1, L: m_Value(V&: X),
7178 R: m_CombineAnd(L: m_Instruction(I&: ExtI),
7179 R: m_ZExtOrSExt(Op: m_ICmp(Pred&: Pred2, L: m_Deferred(V: X),
7180 R: m_APInt(Res&: C)))))) &&
7181 ICmpInst::isEquality(P: Pred1) && ICmpInst::isEquality(P: Pred2)) {
7182 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
7183 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(i: 0)->hasOneUse();
7184 auto CreateRangeCheck = [&] {
7185 Value *CmpV1 =
7186 Builder.CreateICmp(P: Pred1, LHS: X, RHS: Constant::getNullValue(Ty: X->getType()));
7187 Value *CmpV2 = Builder.CreateICmp(
7188 P: Pred1, LHS: X, RHS: ConstantInt::getSigned(Ty: X->getType(), V: IsSExt ? -1 : 1));
7189 return BinaryOperator::Create(
7190 Op: Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
7191 S1: CmpV1, S2: CmpV2);
7192 };
7193 if (C->isZero()) {
7194 if (Pred2 == ICmpInst::ICMP_EQ) {
7195 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
7196 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
7197 return replaceInstUsesWith(
7198 I, V: ConstantInt::getBool(Ty: I.getType(), V: Pred1 == ICmpInst::ICMP_NE));
7199 } else if (!IsSExt || HasOneUse) {
7200 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
7201 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
7202 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
7203 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X != -1
7204 return CreateRangeCheck();
7205 }
7206 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
7207 if (Pred2 == ICmpInst::ICMP_NE) {
7208 // icmp eq X, (zext (icmp ne X, 1)) --> false
7209 // icmp ne X, (zext (icmp ne X, 1)) --> true
7210 // icmp eq X, (sext (icmp ne X, -1)) --> false
7211 // icmp ne X, (sext (icmp ne X, -1)) --> true
7212 return replaceInstUsesWith(
7213 I, V: ConstantInt::getBool(Ty: I.getType(), V: Pred1 == ICmpInst::ICMP_NE));
7214 } else if (!IsSExt || HasOneUse) {
7215 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
7216 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
7217 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
7218 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
7219 return CreateRangeCheck();
7220 }
7221 } else {
7222 // when C != 0 && C != 1:
7223 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
7224 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
7225 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
7226 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
7227 // when C != 0 && C != -1:
7228 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
7229 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
7230 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
7231 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
7232 return ICmpInst::Create(
7233 Op: Instruction::ICmp, Pred: Pred1, S1: X,
7234 S2: ConstantInt::getSigned(Ty: X->getType(), V: Pred2 == ICmpInst::ICMP_NE
7235 ? (IsSExt ? -1 : 1)
7236 : 0));
7237 }
7238 }
7239
7240 return nullptr;
7241}
7242
7243/// If we have an icmp le or icmp ge instruction with a constant operand, turn
7244/// it into the appropriate icmp lt or icmp gt instruction. This transform
7245/// allows them to be folded in visitICmpInst.
7246static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
7247 ICmpInst::Predicate Pred = I.getPredicate();
7248 if (ICmpInst::isEquality(P: Pred) || !ICmpInst::isIntPredicate(P: Pred) ||
7249 InstCombiner::isCanonicalPredicate(Pred))
7250 return nullptr;
7251
7252 Value *Op0 = I.getOperand(i_nocapture: 0);
7253 Value *Op1 = I.getOperand(i_nocapture: 1);
7254 auto *Op1C = dyn_cast<Constant>(Val: Op1);
7255 if (!Op1C)
7256 return nullptr;
7257
7258 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, C: Op1C);
7259 if (!FlippedStrictness)
7260 return nullptr;
7261
7262 return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7263}
7264
7265/// If we have a comparison with a non-canonical predicate, if we can update
7266/// all the users, invert the predicate and adjust all the users.
7267CmpInst *InstCombinerImpl::canonicalizeICmpPredicate(CmpInst &I) {
7268 // Is the predicate already canonical?
7269 CmpInst::Predicate Pred = I.getPredicate();
7270 if (InstCombiner::isCanonicalPredicate(Pred))
7271 return nullptr;
7272
7273 // Can all users be adjusted to predicate inversion?
7274 if (!InstCombiner::canFreelyInvertAllUsersOf(V: &I, /*IgnoredUser=*/nullptr))
7275 return nullptr;
7276
7277 // Ok, we can canonicalize comparison!
7278 // Let's first invert the comparison's predicate.
7279 I.setPredicate(CmpInst::getInversePredicate(pred: Pred));
7280 I.setName(I.getName() + ".not");
7281
7282 // And, adapt users.
7283 freelyInvertAllUsersOf(V: &I);
7284
7285 return &I;
7286}
7287
7288/// Integer compare with boolean values can always be turned into bitwise ops.
7289static Instruction *canonicalizeICmpBool(ICmpInst &I,
7290 InstCombiner::BuilderTy &Builder) {
7291 Value *A = I.getOperand(i_nocapture: 0), *B = I.getOperand(i_nocapture: 1);
7292 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
7293
7294 // A boolean compared to true/false can be simplified to Op0/true/false in
7295 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
7296 // Cases not handled by InstSimplify are always 'not' of Op0.
7297 if (match(V: B, P: m_Zero())) {
7298 switch (I.getPredicate()) {
7299 case CmpInst::ICMP_EQ: // A == 0 -> !A
7300 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
7301 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7302 return BinaryOperator::CreateNot(Op: A);
7303 default:
7304 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7305 }
7306 } else if (match(V: B, P: m_One())) {
7307 switch (I.getPredicate()) {
7308 case CmpInst::ICMP_NE: // A != 1 -> !A
7309 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7310 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7311 return BinaryOperator::CreateNot(Op: A);
7312 default:
7313 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7314 }
7315 }
7316
7317 switch (I.getPredicate()) {
7318 default:
7319 llvm_unreachable("Invalid icmp instruction!");
7320 case ICmpInst::ICMP_EQ:
7321 // icmp eq i1 A, B -> ~(A ^ B)
7322 return BinaryOperator::CreateNot(Op: Builder.CreateXor(LHS: A, RHS: B));
7323
7324 case ICmpInst::ICMP_NE:
7325 // icmp ne i1 A, B -> A ^ B
7326 return BinaryOperator::CreateXor(V1: A, V2: B);
7327
7328 case ICmpInst::ICMP_UGT:
7329 // icmp ugt -> icmp ult
7330 std::swap(a&: A, b&: B);
7331 [[fallthrough]];
7332 case ICmpInst::ICMP_ULT:
7333 // icmp ult i1 A, B -> ~A & B
7334 return BinaryOperator::CreateAnd(V1: Builder.CreateNot(V: A), V2: B);
7335
7336 case ICmpInst::ICMP_SGT:
7337 // icmp sgt -> icmp slt
7338 std::swap(a&: A, b&: B);
7339 [[fallthrough]];
7340 case ICmpInst::ICMP_SLT:
7341 // icmp slt i1 A, B -> A & ~B
7342 return BinaryOperator::CreateAnd(V1: Builder.CreateNot(V: B), V2: A);
7343
7344 case ICmpInst::ICMP_UGE:
7345 // icmp uge -> icmp ule
7346 std::swap(a&: A, b&: B);
7347 [[fallthrough]];
7348 case ICmpInst::ICMP_ULE:
7349 // icmp ule i1 A, B -> ~A | B
7350 return BinaryOperator::CreateOr(V1: Builder.CreateNot(V: A), V2: B);
7351
7352 case ICmpInst::ICMP_SGE:
7353 // icmp sge -> icmp sle
7354 std::swap(a&: A, b&: B);
7355 [[fallthrough]];
7356 case ICmpInst::ICMP_SLE:
7357 // icmp sle i1 A, B -> A | ~B
7358 return BinaryOperator::CreateOr(V1: Builder.CreateNot(V: B), V2: A);
7359 }
7360}
7361
7362// Transform pattern like:
7363// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7364// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7365// Into:
7366// (X l>> Y) != 0
7367// (X l>> Y) == 0
7368static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp,
7369 InstCombiner::BuilderTy &Builder) {
7370 CmpPredicate Pred, NewPred;
7371 Value *X, *Y;
7372 if (match(V: &Cmp,
7373 P: m_c_ICmp(Pred, L: m_OneUse(SubPattern: m_Shl(L: m_One(), R: m_Value(V&: Y))), R: m_Value(V&: X)))) {
7374 switch (Pred) {
7375 case ICmpInst::ICMP_ULE:
7376 NewPred = ICmpInst::ICMP_NE;
7377 break;
7378 case ICmpInst::ICMP_UGT:
7379 NewPred = ICmpInst::ICMP_EQ;
7380 break;
7381 default:
7382 return nullptr;
7383 }
7384 } else if (match(V: &Cmp, P: m_c_ICmp(Pred,
7385 L: m_OneUse(SubPattern: m_CombineOr(
7386 L: m_Not(V: m_Shl(L: m_AllOnes(), R: m_Value(V&: Y))),
7387 R: m_Add(L: m_Shl(L: m_One(), R: m_Value(V&: Y)),
7388 R: m_AllOnes()))),
7389 R: m_Value(V&: X)))) {
7390 // The variant with 'add' is not canonical, (the variant with 'not' is)
7391 // we only get it because it has extra uses, and can't be canonicalized,
7392
7393 switch (Pred) {
7394 case ICmpInst::ICMP_ULT:
7395 NewPred = ICmpInst::ICMP_NE;
7396 break;
7397 case ICmpInst::ICMP_UGE:
7398 NewPred = ICmpInst::ICMP_EQ;
7399 break;
7400 default:
7401 return nullptr;
7402 }
7403 } else
7404 return nullptr;
7405
7406 Value *NewX = Builder.CreateLShr(LHS: X, RHS: Y, Name: X->getName() + ".highbits");
7407 Constant *Zero = Constant::getNullValue(Ty: NewX->getType());
7408 return CmpInst::Create(Op: Instruction::ICmp, Pred: NewPred, S1: NewX, S2: Zero);
7409}
7410
7411static Instruction *foldVectorCmp(CmpInst &Cmp,
7412 InstCombiner::BuilderTy &Builder) {
7413 const CmpInst::Predicate Pred = Cmp.getPredicate();
7414 Value *LHS = Cmp.getOperand(i_nocapture: 0), *RHS = Cmp.getOperand(i_nocapture: 1);
7415 Value *V1, *V2;
7416
7417 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7418 Value *V = Builder.CreateCmp(Pred, LHS: X, RHS: Y, Name: Cmp.getName());
7419 if (auto *I = dyn_cast<Instruction>(Val: V))
7420 I->copyIRFlags(V: &Cmp);
7421 Module *M = Cmp.getModule();
7422 Function *F = Intrinsic::getOrInsertDeclaration(
7423 M, id: Intrinsic::vector_reverse, Tys: V->getType());
7424 return CallInst::Create(Func: F, Args: V);
7425 };
7426
7427 if (match(V: LHS, P: m_VecReverse(Op0: m_Value(V&: V1)))) {
7428 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7429 if (match(V: RHS, P: m_VecReverse(Op0: m_Value(V&: V2))) &&
7430 (LHS->hasOneUse() || RHS->hasOneUse()))
7431 return createCmpReverse(Pred, V1, V2);
7432
7433 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7434 if (LHS->hasOneUse() && isSplatValue(V: RHS))
7435 return createCmpReverse(Pred, V1, RHS);
7436 }
7437 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7438 else if (isSplatValue(V: LHS) && match(V: RHS, P: m_OneUse(SubPattern: m_VecReverse(Op0: m_Value(V&: V2)))))
7439 return createCmpReverse(Pred, LHS, V2);
7440
7441 ArrayRef<int> M;
7442 if (!match(V: LHS, P: m_Shuffle(v1: m_Value(V&: V1), v2: m_Undef(), mask: m_Mask(M))))
7443 return nullptr;
7444
7445 // If both arguments of the cmp are shuffles that use the same mask and
7446 // shuffle within a single vector, move the shuffle after the cmp:
7447 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7448 Type *V1Ty = V1->getType();
7449 if (match(V: RHS, P: m_Shuffle(v1: m_Value(V&: V2), v2: m_Undef(), mask: m_SpecificMask(M))) &&
7450 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7451 Value *NewCmp = Builder.CreateCmp(Pred, LHS: V1, RHS: V2);
7452 return new ShuffleVectorInst(NewCmp, M);
7453 }
7454
7455 // Try to canonicalize compare with splatted operand and splat constant.
7456 // TODO: We could generalize this for more than splats. See/use the code in
7457 // InstCombiner::foldVectorBinop().
7458 Constant *C;
7459 if (!LHS->hasOneUse() || !match(V: RHS, P: m_Constant(C)))
7460 return nullptr;
7461
7462 // Length-changing splats are ok, so adjust the constants as needed:
7463 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7464 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7465 int MaskSplatIndex;
7466 if (ScalarC && match(Mask: M, P: m_SplatOrPoisonMask(MaskSplatIndex))) {
7467 // We allow poison in matching, but this transform removes it for safety.
7468 // Demanded elements analysis should be able to recover some/all of that.
7469 C = ConstantVector::getSplat(EC: cast<VectorType>(Val: V1Ty)->getElementCount(),
7470 Elt: ScalarC);
7471 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7472 Value *NewCmp = Builder.CreateCmp(Pred, LHS: V1, RHS: C);
7473 return new ShuffleVectorInst(NewCmp, NewM);
7474 }
7475
7476 return nullptr;
7477}
7478
7479// extract(uadd.with.overflow(A, B), 0) ult A
7480// -> extract(uadd.with.overflow(A, B), 1)
7481static Instruction *foldICmpOfUAddOv(ICmpInst &I) {
7482 CmpInst::Predicate Pred = I.getPredicate();
7483 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
7484
7485 Value *UAddOv;
7486 Value *A, *B;
7487 auto UAddOvResultPat = m_ExtractValue<0>(
7488 V: m_Intrinsic<Intrinsic::uadd_with_overflow>(Op0: m_Value(V&: A), Op1: m_Value(V&: B)));
7489 if (match(V: Op0, P: UAddOvResultPat) &&
7490 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7491 (Pred == ICmpInst::ICMP_EQ && match(V: Op1, P: m_ZeroInt()) &&
7492 (match(V: A, P: m_One()) || match(V: B, P: m_One()))) ||
7493 (Pred == ICmpInst::ICMP_NE && match(V: Op1, P: m_AllOnes()) &&
7494 (match(V: A, P: m_AllOnes()) || match(V: B, P: m_AllOnes())))))
7495 // extract(uadd.with.overflow(A, B), 0) < A
7496 // extract(uadd.with.overflow(A, 1), 0) == 0
7497 // extract(uadd.with.overflow(A, -1), 0) != -1
7498 UAddOv = cast<ExtractValueInst>(Val: Op0)->getAggregateOperand();
7499 else if (match(V: Op1, P: UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7500 (Op0 == A || Op0 == B))
7501 // A > extract(uadd.with.overflow(A, B), 0)
7502 UAddOv = cast<ExtractValueInst>(Val: Op1)->getAggregateOperand();
7503 else
7504 return nullptr;
7505
7506 return ExtractValueInst::Create(Agg: UAddOv, Idxs: 1);
7507}
7508
7509static Instruction *foldICmpInvariantGroup(ICmpInst &I) {
7510 if (!I.getOperand(i_nocapture: 0)->getType()->isPointerTy() ||
7511 NullPointerIsDefined(
7512 F: I.getParent()->getParent(),
7513 AS: I.getOperand(i_nocapture: 0)->getType()->getPointerAddressSpace())) {
7514 return nullptr;
7515 }
7516 Instruction *Op;
7517 if (match(V: I.getOperand(i_nocapture: 0), P: m_Instruction(I&: Op)) &&
7518 match(V: I.getOperand(i_nocapture: 1), P: m_Zero()) &&
7519 Op->isLaunderOrStripInvariantGroup()) {
7520 return ICmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(),
7521 S1: Op->getOperand(i: 0), S2: I.getOperand(i_nocapture: 1));
7522 }
7523 return nullptr;
7524}
7525
7526static Instruction *foldICmpOfVectorReduce(ICmpInst &I, const DataLayout &DL,
7527 IRBuilderBase &Builder) {
7528 if (!ICmpInst::isEquality(P: I.getPredicate()))
7529 return nullptr;
7530
7531 // The caller puts constants after non-constants.
7532 Value *Op = I.getOperand(i_nocapture: 0);
7533 Value *Const = I.getOperand(i_nocapture: 1);
7534
7535 // For Cond an equality condition, fold
7536 //
7537 // icmp (eq|ne) (vreduce_(or|and) Op), (Zero|AllOnes) ->
7538 // icmp (eq|ne) Op, (Zero|AllOnes)
7539 //
7540 // with a bitcast.
7541 Value *Vec;
7542 if ((match(V: Const, P: m_ZeroInt()) &&
7543 match(V: Op, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_or>(
7544 Op0: m_Value(V&: Vec))))) ||
7545 (match(V: Const, P: m_AllOnes()) &&
7546 match(V: Op, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_and>(
7547 Op0: m_Value(V&: Vec)))))) {
7548 auto *VecTy = dyn_cast<FixedVectorType>(Val: Vec->getType());
7549 if (!VecTy)
7550 return nullptr;
7551 Type *VecEltTy = VecTy->getElementType();
7552 unsigned ScalarBW =
7553 DL.getTypeSizeInBits(Ty: VecEltTy) * VecTy->getNumElements();
7554 if (!DL.fitsInLegalInteger(Width: ScalarBW))
7555 return nullptr;
7556 Type *ScalarTy = IntegerType::get(C&: I.getContext(), NumBits: ScalarBW);
7557 Value *NewConst = match(V: Const, P: m_ZeroInt())
7558 ? ConstantInt::get(Ty: ScalarTy, V: 0)
7559 : ConstantInt::getAllOnesValue(Ty: ScalarTy);
7560 return CmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(),
7561 S1: Builder.CreateBitCast(V: Vec, DestTy: ScalarTy), S2: NewConst);
7562 }
7563 return nullptr;
7564}
7565
7566/// This function folds patterns produced by lowering of reduce idioms, such as
7567/// llvm.vector.reduce.and which are lowered into instruction chains. This code
7568/// attempts to generate fewer number of scalar comparisons instead of vector
7569/// comparisons when possible.
7570static Instruction *foldReductionIdiom(ICmpInst &I,
7571 InstCombiner::BuilderTy &Builder,
7572 const DataLayout &DL) {
7573 if (I.getType()->isVectorTy())
7574 return nullptr;
7575 CmpPredicate OuterPred, InnerPred;
7576 Value *LHS, *RHS;
7577
7578 // Match lowering of @llvm.vector.reduce.and. Turn
7579 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7580 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7581 /// %res = icmp <pred> i8 %scalar_ne, 0
7582 ///
7583 /// into
7584 ///
7585 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7586 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7587 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7588 ///
7589 /// for <pred> in {ne, eq}.
7590 if (!match(V: &I, P: m_ICmp(Pred&: OuterPred,
7591 L: m_OneUse(SubPattern: m_BitCast(Op: m_OneUse(
7592 SubPattern: m_ICmp(Pred&: InnerPred, L: m_Value(V&: LHS), R: m_Value(V&: RHS))))),
7593 R: m_Zero())))
7594 return nullptr;
7595 auto *LHSTy = dyn_cast<FixedVectorType>(Val: LHS->getType());
7596 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7597 return nullptr;
7598 unsigned NumBits =
7599 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7600 // TODO: Relax this to "not wider than max legal integer type"?
7601 if (!DL.isLegalInteger(Width: NumBits))
7602 return nullptr;
7603
7604 if (ICmpInst::isEquality(P: OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7605 auto *ScalarTy = Builder.getIntNTy(N: NumBits);
7606 LHS = Builder.CreateBitCast(V: LHS, DestTy: ScalarTy, Name: LHS->getName() + ".scalar");
7607 RHS = Builder.CreateBitCast(V: RHS, DestTy: ScalarTy, Name: RHS->getName() + ".scalar");
7608 return ICmpInst::Create(Op: Instruction::ICmp, Pred: OuterPred, S1: LHS, S2: RHS,
7609 Name: I.getName());
7610 }
7611
7612 return nullptr;
7613}
7614
7615// This helper will be called with icmp operands in both orders.
7616Instruction *InstCombinerImpl::foldICmpCommutative(CmpPredicate Pred,
7617 Value *Op0, Value *Op1,
7618 ICmpInst &CxtI) {
7619 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7620 if (auto *GEP = dyn_cast<GEPOperator>(Val: Op0))
7621 if (Instruction *NI = foldGEPICmp(GEPLHS: GEP, RHS: Op1, Cond: Pred, I&: CxtI))
7622 return NI;
7623
7624 if (auto *SI = dyn_cast<SelectInst>(Val: Op0))
7625 if (Instruction *NI = foldSelectICmp(Pred, SI, RHS: Op1, I: CxtI))
7626 return NI;
7627
7628 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Val: Op0)) {
7629 if (Instruction *Res = foldICmpWithMinMax(I&: CxtI, MinMax, Z: Op1, Pred))
7630 return Res;
7631
7632 if (Instruction *Res = foldICmpWithClamp(I&: CxtI, X: Op1, Min: MinMax))
7633 return Res;
7634 }
7635
7636 {
7637 Value *X;
7638 const APInt *C;
7639 // icmp X+Cst, X
7640 if (match(V: Op0, P: m_Add(L: m_Value(V&: X), R: m_APInt(Res&: C))) && Op1 == X)
7641 return foldICmpAddOpConst(X, C: *C, Pred);
7642 }
7643
7644 // abs(X) >= X --> true
7645 // abs(X) u<= X --> true
7646 // abs(X) < X --> false
7647 // abs(X) u> X --> false
7648 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7649 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7650 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7651 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7652 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7653 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7654 {
7655 Value *X;
7656 Constant *C;
7657 if (match(V: Op0, P: m_Intrinsic<Intrinsic::abs>(Op0: m_Value(V&: X), Op1: m_Constant(C))) &&
7658 match(V: Op1, P: m_Specific(V: X))) {
7659 Value *NullValue = Constant::getNullValue(Ty: X->getType());
7660 Value *AllOnesValue = Constant::getAllOnesValue(Ty: X->getType());
7661 const APInt SMin =
7662 APInt::getSignedMinValue(numBits: X->getType()->getScalarSizeInBits());
7663 bool IsIntMinPosion = C->isAllOnesValue();
7664 switch (Pred) {
7665 case CmpInst::ICMP_ULE:
7666 case CmpInst::ICMP_SGE:
7667 return replaceInstUsesWith(I&: CxtI, V: ConstantInt::getTrue(Ty: CxtI.getType()));
7668 case CmpInst::ICMP_UGT:
7669 case CmpInst::ICMP_SLT:
7670 return replaceInstUsesWith(I&: CxtI, V: ConstantInt::getFalse(Ty: CxtI.getType()));
7671 case CmpInst::ICMP_UGE:
7672 case CmpInst::ICMP_SLE:
7673 case CmpInst::ICMP_EQ: {
7674 return replaceInstUsesWith(
7675 I&: CxtI, V: IsIntMinPosion
7676 ? Builder.CreateICmpSGT(LHS: X, RHS: AllOnesValue)
7677 : Builder.CreateICmpULT(
7678 LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: SMin + 1)));
7679 }
7680 case CmpInst::ICMP_ULT:
7681 case CmpInst::ICMP_SGT:
7682 case CmpInst::ICMP_NE: {
7683 return replaceInstUsesWith(
7684 I&: CxtI, V: IsIntMinPosion
7685 ? Builder.CreateICmpSLT(LHS: X, RHS: NullValue)
7686 : Builder.CreateICmpUGT(
7687 LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: SMin)));
7688 }
7689 default:
7690 llvm_unreachable("Invalid predicate!");
7691 }
7692 }
7693 }
7694
7695 const SimplifyQuery Q = SQ.getWithInstruction(I: &CxtI);
7696 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, IC&: *this))
7697 return replaceInstUsesWith(I&: CxtI, V);
7698
7699 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
7700 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(RHS: 1); };
7701 {
7702 if (match(V: Op0, P: m_UDiv(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckUGT1)))) {
7703 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7704 Constant::getNullValue(Ty: Op1->getType()));
7705 }
7706
7707 if (!ICmpInst::isUnsigned(predicate: Pred) &&
7708 match(V: Op0, P: m_SDiv(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckUGT1)))) {
7709 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7710 Constant::getNullValue(Ty: Op1->getType()));
7711 }
7712 }
7713
7714 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
7715 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
7716 {
7717 if (match(V: Op0, P: m_LShr(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckNE0)))) {
7718 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7719 Constant::getNullValue(Ty: Op1->getType()));
7720 }
7721
7722 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
7723 match(V: Op0, P: m_AShr(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckNE0)))) {
7724 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7725 Constant::getNullValue(Ty: Op1->getType()));
7726 }
7727 }
7728
7729 return nullptr;
7730}
7731
7732Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {
7733 bool Changed = false;
7734 const SimplifyQuery Q = SQ.getWithInstruction(I: &I);
7735 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
7736 unsigned Op0Cplxity = getComplexity(V: Op0);
7737 unsigned Op1Cplxity = getComplexity(V: Op1);
7738
7739 /// Orders the operands of the compare so that they are listed from most
7740 /// complex to least complex. This puts constants before unary operators,
7741 /// before binary operators.
7742 if (Op0Cplxity < Op1Cplxity) {
7743 I.swapOperands();
7744 std::swap(a&: Op0, b&: Op1);
7745 Changed = true;
7746 }
7747
7748 if (Value *V = simplifyICmpInst(Pred: I.getCmpPredicate(), LHS: Op0, RHS: Op1, Q))
7749 return replaceInstUsesWith(I, V);
7750
7751 // Comparing -val or val with non-zero is the same as just comparing val
7752 // ie, abs(val) != 0 -> val != 0
7753 if (I.getPredicate() == ICmpInst::ICMP_NE && match(V: Op1, P: m_Zero())) {
7754 Value *Cond, *SelectTrue, *SelectFalse;
7755 if (match(V: Op0, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: SelectTrue),
7756 R: m_Value(V&: SelectFalse)))) {
7757 if (Value *V = dyn_castNegVal(V: SelectTrue)) {
7758 if (V == SelectFalse)
7759 return CmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(), S1: V, S2: Op1);
7760 } else if (Value *V = dyn_castNegVal(V: SelectFalse)) {
7761 if (V == SelectTrue)
7762 return CmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(), S1: V, S2: Op1);
7763 }
7764 }
7765 }
7766
7767 if (Instruction *Res = foldICmpTruncWithTruncOrExt(Cmp&: I, Q))
7768 return Res;
7769
7770 if (Op0->getType()->isIntOrIntVectorTy(BitWidth: 1))
7771 if (Instruction *Res = canonicalizeICmpBool(I, Builder))
7772 return Res;
7773
7774 if (Instruction *Res = canonicalizeCmpWithConstant(I))
7775 return Res;
7776
7777 if (Instruction *Res = canonicalizeICmpPredicate(I))
7778 return Res;
7779
7780 if (Instruction *Res = foldICmpWithConstant(Cmp&: I))
7781 return Res;
7782
7783 if (Instruction *Res = foldICmpWithDominatingICmp(Cmp&: I))
7784 return Res;
7785
7786 if (Instruction *Res = foldICmpUsingBoolRange(I))
7787 return Res;
7788
7789 if (Instruction *Res = foldICmpUsingKnownBits(I))
7790 return Res;
7791
7792 if (Instruction *Res = foldIsMultipleOfAPowerOfTwo(Cmp&: I))
7793 return Res;
7794
7795 // Test if the ICmpInst instruction is used exclusively by a select as
7796 // part of a minimum or maximum operation. If so, refrain from doing
7797 // any other folding. This helps out other analyses which understand
7798 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
7799 // and CodeGen. And in this case, at least one of the comparison
7800 // operands has at least one user besides the compare (the select),
7801 // which would often largely negate the benefit of folding anyway.
7802 //
7803 // Do the same for the other patterns recognized by matchSelectPattern.
7804 if (I.hasOneUse())
7805 if (SelectInst *SI = dyn_cast<SelectInst>(Val: I.user_back())) {
7806 Value *A, *B;
7807 SelectPatternResult SPR = matchSelectPattern(V: SI, LHS&: A, RHS&: B);
7808 if (SPR.Flavor != SPF_UNKNOWN)
7809 return nullptr;
7810 }
7811
7812 // Do this after checking for min/max to prevent infinite looping.
7813 if (Instruction *Res = foldICmpWithZero(Cmp&: I))
7814 return Res;
7815
7816 // FIXME: We only do this after checking for min/max to prevent infinite
7817 // looping caused by a reverse canonicalization of these patterns for min/max.
7818 // FIXME: The organization of folds is a mess. These would naturally go into
7819 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
7820 // down here after the min/max restriction.
7821 ICmpInst::Predicate Pred = I.getPredicate();
7822 const APInt *C;
7823 if (match(V: Op1, P: m_APInt(Res&: C))) {
7824 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
7825 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
7826 Constant *Zero = Constant::getNullValue(Ty: Op0->getType());
7827 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
7828 }
7829
7830 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
7831 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
7832 Constant *AllOnes = Constant::getAllOnesValue(Ty: Op0->getType());
7833 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
7834 }
7835 }
7836
7837 // The folds in here may rely on wrapping flags and special constants, so
7838 // they can break up min/max idioms in some cases but not seemingly similar
7839 // patterns.
7840 // FIXME: It may be possible to enhance select folding to make this
7841 // unnecessary. It may also be moot if we canonicalize to min/max
7842 // intrinsics.
7843 if (Instruction *Res = foldICmpBinOp(I, SQ: Q))
7844 return Res;
7845
7846 if (Instruction *Res = foldICmpInstWithConstant(Cmp&: I))
7847 return Res;
7848
7849 // Try to match comparison as a sign bit test. Intentionally do this after
7850 // foldICmpInstWithConstant() to potentially let other folds to happen first.
7851 if (Instruction *New = foldSignBitTest(I))
7852 return New;
7853
7854 if (auto *PN = dyn_cast<PHINode>(Val: Op0))
7855 if (Instruction *NV = foldOpIntoPhi(I, PN))
7856 return NV;
7857 if (auto *PN = dyn_cast<PHINode>(Val: Op1))
7858 if (Instruction *NV = foldOpIntoPhi(I, PN))
7859 return NV;
7860
7861 if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
7862 return Res;
7863
7864 if (Instruction *Res = foldICmpCommutative(Pred: I.getCmpPredicate(), Op0, Op1, CxtI&: I))
7865 return Res;
7866 if (Instruction *Res =
7867 foldICmpCommutative(Pred: I.getSwappedCmpPredicate(), Op0: Op1, Op1: Op0, CxtI&: I))
7868 return Res;
7869
7870 if (I.isCommutative()) {
7871 if (auto Pair = matchSymmetricPair(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1))) {
7872 replaceOperand(I, OpNum: 0, V: Pair->first);
7873 replaceOperand(I, OpNum: 1, V: Pair->second);
7874 return &I;
7875 }
7876 }
7877
7878 // In case of a comparison with two select instructions having the same
7879 // condition, check whether one of the resulting branches can be simplified.
7880 // If so, just compare the other branch and select the appropriate result.
7881 // For example:
7882 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
7883 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
7884 // %cmp2 = icmp slt i32 %tmp2, %tmp1
7885 // The icmp will result false for the false value of selects and the result
7886 // will depend upon the comparison of true values of selects if %cmp is
7887 // true. Thus, transform this into:
7888 // %cmp = icmp slt i32 %y, %z
7889 // %sel = select i1 %cond, i1 %cmp, i1 false
7890 // This handles similar cases to transform.
7891 {
7892 Value *Cond, *A, *B, *C, *D;
7893 if (match(V: Op0, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: A), R: m_Value(V&: B))) &&
7894 match(V: Op1, P: m_Select(C: m_Specific(V: Cond), L: m_Value(V&: C), R: m_Value(V&: D))) &&
7895 (Op0->hasOneUse() || Op1->hasOneUse())) {
7896 // Check whether comparison of TrueValues can be simplified
7897 if (Value *Res = simplifyICmpInst(Pred, LHS: A, RHS: C, Q: SQ)) {
7898 Value *NewICMP = Builder.CreateICmp(P: Pred, LHS: B, RHS: D);
7899 return SelectInst::Create(
7900 C: Cond, S1: Res, S2: NewICMP, /*NameStr=*/"", /*InsertBefore=*/nullptr,
7901 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : cast<Instruction>(Val: Op0));
7902 }
7903 // Check whether comparison of FalseValues can be simplified
7904 if (Value *Res = simplifyICmpInst(Pred, LHS: B, RHS: D, Q: SQ)) {
7905 Value *NewICMP = Builder.CreateICmp(P: Pred, LHS: A, RHS: C);
7906 return SelectInst::Create(
7907 C: Cond, S1: NewICMP, S2: Res, /*NameStr=*/"", /*InsertBefore=*/nullptr,
7908 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : cast<Instruction>(Val: Op0));
7909 }
7910 }
7911 }
7912
7913 // icmp slt (sub nsw x, y), (add nsw x, y) --> icmp sgt y, 0
7914 // icmp ult (sub nuw x, y), (add nuw x, y) --> icmp ugt y, 0
7915 // icmp eq (sub nsw/nuw x, y), (add nsw/nuw x, y) --> icmp eq y, 0
7916 {
7917 Value *A, *B;
7918 CmpPredicate CmpPred;
7919 if (match(V: &I, P: m_c_ICmp(Pred&: CmpPred, L: m_Sub(L: m_Value(V&: A), R: m_Value(V&: B)),
7920 R: m_c_Add(L: m_Deferred(V: A), R: m_Deferred(V: B))))) {
7921 auto *I0 = cast<OverflowingBinaryOperator>(Val: Op0);
7922 auto *I1 = cast<OverflowingBinaryOperator>(Val: Op1);
7923 bool I0NUW = I0->hasNoUnsignedWrap();
7924 bool I1NUW = I1->hasNoUnsignedWrap();
7925 bool I0NSW = I0->hasNoSignedWrap();
7926 bool I1NSW = I1->hasNoSignedWrap();
7927 if ((ICmpInst::isUnsigned(predicate: Pred) && I0NUW && I1NUW) ||
7928 (ICmpInst::isSigned(predicate: Pred) && I0NSW && I1NSW) ||
7929 (ICmpInst::isEquality(P: Pred) &&
7930 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
7931 return new ICmpInst(CmpPredicate::getSwapped(P: CmpPred), B,
7932 ConstantInt::get(Ty: Op0->getType(), V: 0));
7933 }
7934 }
7935 }
7936
7937 // Try to optimize equality comparisons against alloca-based pointers.
7938 if (Op0->getType()->isPointerTy() && I.isEquality()) {
7939 assert(Op1->getType()->isPointerTy() &&
7940 "Comparing pointer with non-pointer?");
7941 if (auto *Alloca = dyn_cast<AllocaInst>(Val: getUnderlyingObject(V: Op0)))
7942 if (foldAllocaCmp(Alloca))
7943 return nullptr;
7944 if (auto *Alloca = dyn_cast<AllocaInst>(Val: getUnderlyingObject(V: Op1)))
7945 if (foldAllocaCmp(Alloca))
7946 return nullptr;
7947 }
7948
7949 if (Instruction *Res = foldICmpBitCast(Cmp&: I))
7950 return Res;
7951
7952 // TODO: Hoist this above the min/max bailout.
7953 if (Instruction *R = foldICmpWithCastOp(ICmp&: I))
7954 return R;
7955
7956 {
7957 Value *X, *Y;
7958 // Transform (X & ~Y) == 0 --> (X & Y) != 0
7959 // and (X & ~Y) != 0 --> (X & Y) == 0
7960 // if A is a power of 2.
7961 if (match(V: Op0, P: m_And(L: m_Value(V&: X), R: m_Not(V: m_Value(V&: Y)))) &&
7962 match(V: Op1, P: m_Zero()) && isKnownToBeAPowerOfTwo(V: X, OrZero: false, CxtI: &I) &&
7963 I.isEquality())
7964 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(LHS: X, RHS: Y),
7965 Op1);
7966
7967 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
7968 if (Op0->getType()->isIntOrIntVectorTy()) {
7969 bool ConsumesOp0, ConsumesOp1;
7970 if (isFreeToInvert(V: Op0, WillInvertAllUses: Op0->hasOneUse(), DoesConsume&: ConsumesOp0) &&
7971 isFreeToInvert(V: Op1, WillInvertAllUses: Op1->hasOneUse(), DoesConsume&: ConsumesOp1) &&
7972 (ConsumesOp0 || ConsumesOp1)) {
7973 Value *InvOp0 = getFreelyInverted(V: Op0, WillInvertAllUses: Op0->hasOneUse(), Builder: &Builder);
7974 Value *InvOp1 = getFreelyInverted(V: Op1, WillInvertAllUses: Op1->hasOneUse(), Builder: &Builder);
7975 assert(InvOp0 && InvOp1 &&
7976 "Mismatch between isFreeToInvert and getFreelyInverted");
7977 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
7978 }
7979 }
7980
7981 Instruction *AddI = nullptr;
7982 if (match(V: &I, P: m_UAddWithOverflow(L: m_Value(V&: X), R: m_Value(V&: Y),
7983 S: m_Instruction(I&: AddI))) &&
7984 isa<IntegerType>(Val: X->getType())) {
7985 Value *Result;
7986 Constant *Overflow;
7987 // m_UAddWithOverflow can match patterns that do not include an explicit
7988 // "add" instruction, so check the opcode of the matched op.
7989 if (AddI->getOpcode() == Instruction::Add &&
7990 OptimizeOverflowCheck(BinaryOp: Instruction::Add, /*Signed*/ IsSigned: false, LHS: X, RHS: Y, OrigI&: *AddI,
7991 Result, Overflow)) {
7992 replaceInstUsesWith(I&: *AddI, V: Result);
7993 eraseInstFromFunction(I&: *AddI);
7994 return replaceInstUsesWith(I, V: Overflow);
7995 }
7996 }
7997
7998 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
7999 if (match(V: Op0, P: m_NUWMul(L: m_ZExt(Op: m_Value(V&: X)), R: m_ZExt(Op: m_Value(V&: Y)))) &&
8000 match(V: Op1, P: m_APInt(Res&: C))) {
8001 if (Instruction *R = processUMulZExtIdiom(I, MulVal: Op0, OtherVal: C, IC&: *this))
8002 return R;
8003 }
8004
8005 // Signbit test folds
8006 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
8007 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
8008 Instruction *ExtI;
8009 if ((I.isUnsigned() || I.isEquality()) &&
8010 match(V: Op1,
8011 P: m_CombineAnd(L: m_Instruction(I&: ExtI), R: m_ZExtOrSExt(Op: m_Value(V&: Y)))) &&
8012 Y->getType()->getScalarSizeInBits() == 1 &&
8013 (Op0->hasOneUse() || Op1->hasOneUse())) {
8014 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
8015 Instruction *ShiftI;
8016 if (match(V: Op0, P: m_CombineAnd(L: m_Instruction(I&: ShiftI),
8017 R: m_Shr(L: m_Value(V&: X), R: m_SpecificIntAllowPoison(
8018 V: OpWidth - 1))))) {
8019 unsigned ExtOpc = ExtI->getOpcode();
8020 unsigned ShiftOpc = ShiftI->getOpcode();
8021 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
8022 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
8023 Value *SLTZero =
8024 Builder.CreateICmpSLT(LHS: X, RHS: Constant::getNullValue(Ty: X->getType()));
8025 Value *Cmp = Builder.CreateICmp(P: Pred, LHS: SLTZero, RHS: Y, Name: I.getName());
8026 return replaceInstUsesWith(I, V: Cmp);
8027 }
8028 }
8029 }
8030 }
8031
8032 if (Instruction *Res = foldICmpEquality(I))
8033 return Res;
8034
8035 if (Instruction *Res = foldICmpPow2Test(I, Builder))
8036 return Res;
8037
8038 if (Instruction *Res = foldICmpOfUAddOv(I))
8039 return Res;
8040
8041 if (Instruction *Res = foldICmpOfVectorReduce(I, DL, Builder))
8042 return Res;
8043
8044 // The 'cmpxchg' instruction returns an aggregate containing the old value and
8045 // an i1 which indicates whether or not we successfully did the swap.
8046 //
8047 // Replace comparisons between the old value and the expected value with the
8048 // indicator that 'cmpxchg' returns.
8049 //
8050 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
8051 // spuriously fail. In those cases, the old value may equal the expected
8052 // value but it is possible for the swap to not occur.
8053 if (I.getPredicate() == ICmpInst::ICMP_EQ)
8054 if (auto *EVI = dyn_cast<ExtractValueInst>(Val: Op0))
8055 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(Val: EVI->getAggregateOperand()))
8056 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
8057 !ACXI->isWeak())
8058 return ExtractValueInst::Create(Agg: ACXI, Idxs: 1);
8059
8060 if (Instruction *Res = foldICmpWithHighBitMask(Cmp&: I, Builder))
8061 return Res;
8062
8063 if (I.getType()->isVectorTy())
8064 if (Instruction *Res = foldVectorCmp(Cmp&: I, Builder))
8065 return Res;
8066
8067 if (Instruction *Res = foldICmpInvariantGroup(I))
8068 return Res;
8069
8070 if (Instruction *Res = foldReductionIdiom(I, Builder, DL))
8071 return Res;
8072
8073 {
8074 Value *A;
8075 const APInt *C1, *C2;
8076 ICmpInst::Predicate Pred = I.getPredicate();
8077 if (ICmpInst::isEquality(P: Pred)) {
8078 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
8079 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
8080 if (match(V: Op0, P: m_And(L: m_SExt(Op: m_Value(V&: A)), R: m_APInt(Res&: C1))) &&
8081 match(V: Op1, P: m_APInt(Res&: C2))) {
8082 Type *InputTy = A->getType();
8083 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
8084 // c2 must be non-negative at the bitwidth of a.
8085 if (C2->getActiveBits() < InputBitWidth) {
8086 APInt TruncC1 = C1->trunc(width: InputBitWidth);
8087 // Check if there are 1s in C1 high bits of size InputBitWidth.
8088 if (C1->uge(RHS: APInt::getOneBitSet(numBits: C1->getBitWidth(), BitNo: InputBitWidth)))
8089 TruncC1.setBit(InputBitWidth - 1);
8090 Value *AndInst = Builder.CreateAnd(LHS: A, RHS: TruncC1);
8091 return new ICmpInst(
8092 Pred, AndInst,
8093 ConstantInt::get(Ty: InputTy, V: C2->trunc(width: InputBitWidth)));
8094 }
8095 }
8096 }
8097 }
8098
8099 return Changed ? &I : nullptr;
8100}
8101
8102/// Fold fcmp ([us]itofp x, cst) if possible.
8103Instruction *InstCombinerImpl::foldFCmpIntToFPConst(FCmpInst &I,
8104 Instruction *LHSI,
8105 Constant *RHSC) {
8106 const APFloat *RHS;
8107 if (!match(V: RHSC, P: m_APFloat(Res&: RHS)))
8108 return nullptr;
8109
8110 // Get the width of the mantissa. We don't want to hack on conversions that
8111 // might lose information from the integer, e.g. "i64 -> float"
8112 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8113 if (MantissaWidth == -1)
8114 return nullptr; // Unknown.
8115
8116 Type *IntTy = LHSI->getOperand(i: 0)->getType();
8117 unsigned IntWidth = IntTy->getScalarSizeInBits();
8118 bool LHSUnsigned = isa<UIToFPInst>(Val: LHSI);
8119
8120 if (I.isEquality()) {
8121 FCmpInst::Predicate P = I.getPredicate();
8122 bool IsExact = false;
8123 APSInt RHSCvt(IntWidth, LHSUnsigned);
8124 RHS->convertToInteger(Result&: RHSCvt, RM: APFloat::rmNearestTiesToEven, IsExact: &IsExact);
8125
8126 // If the floating point constant isn't an integer value, we know if we will
8127 // ever compare equal / not equal to it.
8128 if (!IsExact) {
8129 // TODO: Can never be -0.0 and other non-representable values
8130 APFloat RHSRoundInt(*RHS);
8131 RHSRoundInt.roundToIntegral(RM: APFloat::rmNearestTiesToEven);
8132 if (*RHS != RHSRoundInt) {
8133 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
8134 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8135
8136 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
8137 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8138 }
8139 }
8140
8141 // TODO: If the constant is exactly representable, is it always OK to do
8142 // equality compares as integer?
8143 }
8144
8145 // Check to see that the input is converted from an integer type that is small
8146 // enough that preserves all bits. TODO: check here for "known" sign bits.
8147 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
8148
8149 // Following test does NOT adjust IntWidth downwards for signed inputs,
8150 // because the most negative value still requires all the mantissa bits
8151 // to distinguish it from one less than that value.
8152 if ((int)IntWidth > MantissaWidth) {
8153 // Conversion would lose accuracy. Check if loss can impact comparison.
8154 int Exp = ilogb(Arg: *RHS);
8155 if (Exp == APFloat::IEK_Inf) {
8156 int MaxExponent = ilogb(Arg: APFloat::getLargest(Sem: RHS->getSemantics()));
8157 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
8158 // Conversion could create infinity.
8159 return nullptr;
8160 } else {
8161 // Note that if RHS is zero or NaN, then Exp is negative
8162 // and first condition is trivially false.
8163 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
8164 // Conversion could affect comparison.
8165 return nullptr;
8166 }
8167 }
8168
8169 // Otherwise, we can potentially simplify the comparison. We know that it
8170 // will always come through as an integer value and we know the constant is
8171 // not a NAN (it would have been previously simplified).
8172 assert(!RHS->isNaN() && "NaN comparison not already folded!");
8173
8174 ICmpInst::Predicate Pred;
8175 switch (I.getPredicate()) {
8176 default:
8177 llvm_unreachable("Unexpected predicate!");
8178 case FCmpInst::FCMP_UEQ:
8179 case FCmpInst::FCMP_OEQ:
8180 Pred = ICmpInst::ICMP_EQ;
8181 break;
8182 case FCmpInst::FCMP_UGT:
8183 case FCmpInst::FCMP_OGT:
8184 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
8185 break;
8186 case FCmpInst::FCMP_UGE:
8187 case FCmpInst::FCMP_OGE:
8188 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
8189 break;
8190 case FCmpInst::FCMP_ULT:
8191 case FCmpInst::FCMP_OLT:
8192 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
8193 break;
8194 case FCmpInst::FCMP_ULE:
8195 case FCmpInst::FCMP_OLE:
8196 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
8197 break;
8198 case FCmpInst::FCMP_UNE:
8199 case FCmpInst::FCMP_ONE:
8200 Pred = ICmpInst::ICMP_NE;
8201 break;
8202 case FCmpInst::FCMP_ORD:
8203 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8204 case FCmpInst::FCMP_UNO:
8205 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8206 }
8207
8208 // Now we know that the APFloat is a normal number, zero or inf.
8209
8210 // See if the FP constant is too large for the integer. For example,
8211 // comparing an i8 to 300.0.
8212 if (!LHSUnsigned) {
8213 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
8214 // and large values.
8215 APFloat SMax(RHS->getSemantics());
8216 SMax.convertFromAPInt(Input: APInt::getSignedMaxValue(numBits: IntWidth), IsSigned: true,
8217 RM: APFloat::rmNearestTiesToEven);
8218 if (SMax < *RHS) { // smax < 13123.0
8219 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
8220 Pred == ICmpInst::ICMP_SLE)
8221 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8222 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8223 }
8224 } else {
8225 // If the RHS value is > UnsignedMax, fold the comparison. This handles
8226 // +INF and large values.
8227 APFloat UMax(RHS->getSemantics());
8228 UMax.convertFromAPInt(Input: APInt::getMaxValue(numBits: IntWidth), IsSigned: false,
8229 RM: APFloat::rmNearestTiesToEven);
8230 if (UMax < *RHS) { // umax < 13123.0
8231 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
8232 Pred == ICmpInst::ICMP_ULE)
8233 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8234 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8235 }
8236 }
8237
8238 if (!LHSUnsigned) {
8239 // See if the RHS value is < SignedMin.
8240 APFloat SMin(RHS->getSemantics());
8241 SMin.convertFromAPInt(Input: APInt::getSignedMinValue(numBits: IntWidth), IsSigned: true,
8242 RM: APFloat::rmNearestTiesToEven);
8243 if (SMin > *RHS) { // smin > 12312.0
8244 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
8245 Pred == ICmpInst::ICMP_SGE)
8246 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8247 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8248 }
8249 } else {
8250 // See if the RHS value is < UnsignedMin.
8251 APFloat UMin(RHS->getSemantics());
8252 UMin.convertFromAPInt(Input: APInt::getMinValue(numBits: IntWidth), IsSigned: false,
8253 RM: APFloat::rmNearestTiesToEven);
8254 if (UMin > *RHS) { // umin > 12312.0
8255 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
8256 Pred == ICmpInst::ICMP_UGE)
8257 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8258 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8259 }
8260 }
8261
8262 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
8263 // [0, UMAX], but it may still be fractional. Check whether this is the case
8264 // using the IsExact flag.
8265 // Don't do this for zero, because -0.0 is not fractional.
8266 APSInt RHSInt(IntWidth, LHSUnsigned);
8267 bool IsExact;
8268 RHS->convertToInteger(Result&: RHSInt, RM: APFloat::rmTowardZero, IsExact: &IsExact);
8269 if (!RHS->isZero()) {
8270 if (!IsExact) {
8271 // If we had a comparison against a fractional value, we have to adjust
8272 // the compare predicate and sometimes the value. RHSC is rounded towards
8273 // zero at this point.
8274 switch (Pred) {
8275 default:
8276 llvm_unreachable("Unexpected integer comparison!");
8277 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
8278 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8279 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
8280 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8281 case ICmpInst::ICMP_ULE:
8282 // (float)int <= 4.4 --> int <= 4
8283 // (float)int <= -4.4 --> false
8284 if (RHS->isNegative())
8285 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8286 break;
8287 case ICmpInst::ICMP_SLE:
8288 // (float)int <= 4.4 --> int <= 4
8289 // (float)int <= -4.4 --> int < -4
8290 if (RHS->isNegative())
8291 Pred = ICmpInst::ICMP_SLT;
8292 break;
8293 case ICmpInst::ICMP_ULT:
8294 // (float)int < -4.4 --> false
8295 // (float)int < 4.4 --> int <= 4
8296 if (RHS->isNegative())
8297 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8298 Pred = ICmpInst::ICMP_ULE;
8299 break;
8300 case ICmpInst::ICMP_SLT:
8301 // (float)int < -4.4 --> int < -4
8302 // (float)int < 4.4 --> int <= 4
8303 if (!RHS->isNegative())
8304 Pred = ICmpInst::ICMP_SLE;
8305 break;
8306 case ICmpInst::ICMP_UGT:
8307 // (float)int > 4.4 --> int > 4
8308 // (float)int > -4.4 --> true
8309 if (RHS->isNegative())
8310 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8311 break;
8312 case ICmpInst::ICMP_SGT:
8313 // (float)int > 4.4 --> int > 4
8314 // (float)int > -4.4 --> int >= -4
8315 if (RHS->isNegative())
8316 Pred = ICmpInst::ICMP_SGE;
8317 break;
8318 case ICmpInst::ICMP_UGE:
8319 // (float)int >= -4.4 --> true
8320 // (float)int >= 4.4 --> int > 4
8321 if (RHS->isNegative())
8322 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8323 Pred = ICmpInst::ICMP_UGT;
8324 break;
8325 case ICmpInst::ICMP_SGE:
8326 // (float)int >= -4.4 --> int >= -4
8327 // (float)int >= 4.4 --> int > 4
8328 if (!RHS->isNegative())
8329 Pred = ICmpInst::ICMP_SGT;
8330 break;
8331 }
8332 }
8333 }
8334
8335 // Lower this FP comparison into an appropriate integer version of the
8336 // comparison.
8337 return new ICmpInst(Pred, LHSI->getOperand(i: 0),
8338 ConstantInt::get(Ty: LHSI->getOperand(i: 0)->getType(), V: RHSInt));
8339}
8340
8341/// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
8342static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI,
8343 Constant *RHSC) {
8344 // When C is not 0.0 and infinities are not allowed:
8345 // (C / X) < 0.0 is a sign-bit test of X
8346 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
8347 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
8348 //
8349 // Proof:
8350 // Multiply (C / X) < 0.0 by X * X / C.
8351 // - X is non zero, if it is the flag 'ninf' is violated.
8352 // - C defines the sign of X * X * C. Thus it also defines whether to swap
8353 // the predicate. C is also non zero by definition.
8354 //
8355 // Thus X * X / C is non zero and the transformation is valid. [qed]
8356
8357 FCmpInst::Predicate Pred = I.getPredicate();
8358
8359 // Check that predicates are valid.
8360 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
8361 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
8362 return nullptr;
8363
8364 // Check that RHS operand is zero.
8365 if (!match(V: RHSC, P: m_AnyZeroFP()))
8366 return nullptr;
8367
8368 // Check fastmath flags ('ninf').
8369 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
8370 return nullptr;
8371
8372 // Check the properties of the dividend. It must not be zero to avoid a
8373 // division by zero (see Proof).
8374 const APFloat *C;
8375 if (!match(V: LHSI->getOperand(i: 0), P: m_APFloat(Res&: C)))
8376 return nullptr;
8377
8378 if (C->isZero())
8379 return nullptr;
8380
8381 // Get swapped predicate if necessary.
8382 if (C->isNegative())
8383 Pred = I.getSwappedPredicate();
8384
8385 return new FCmpInst(Pred, LHSI->getOperand(i: 1), RHSC, "", &I);
8386}
8387
8388// Transform 'fptrunc(x) cmp C' to 'x cmp ext(C)' if possible.
8389// Patterns include:
8390// fptrunc(x) < C --> x < ext(C)
8391// fptrunc(x) <= C --> x <= ext(C)
8392// fptrunc(x) > C --> x > ext(C)
8393// fptrunc(x) >= C --> x >= ext(C)
8394// where 'ext(C)' is the extension of 'C' to the type of 'x' with a small bias
8395// due to precision loss.
8396static Instruction *foldFCmpFpTrunc(FCmpInst &I, const Instruction &FPTrunc,
8397 const Constant &C) {
8398 FCmpInst::Predicate Pred = I.getPredicate();
8399 bool RoundDown = false;
8400
8401 if (Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE ||
8402 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT)
8403 RoundDown = true;
8404 else if (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT ||
8405 Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)
8406 RoundDown = false;
8407 else
8408 return nullptr;
8409
8410 const APFloat *CValue;
8411 if (!match(V: &C, P: m_APFloat(Res&: CValue)))
8412 return nullptr;
8413
8414 if (CValue->isNaN() || CValue->isInfinity())
8415 return nullptr;
8416
8417 auto ConvertFltSema = [](const APFloat &Src, const fltSemantics &Sema) {
8418 bool LosesInfo;
8419 APFloat Dest = Src;
8420 Dest.convert(ToSemantics: Sema, RM: APFloat::rmNearestTiesToEven, losesInfo: &LosesInfo);
8421 return Dest;
8422 };
8423
8424 auto NextValue = [](const APFloat &Value, bool RoundDown) {
8425 APFloat NextValue = Value;
8426 NextValue.next(nextDown: RoundDown);
8427 return NextValue;
8428 };
8429
8430 APFloat NextCValue = NextValue(*CValue, RoundDown);
8431
8432 Type *DestType = FPTrunc.getOperand(i: 0)->getType();
8433 const fltSemantics &DestFltSema =
8434 DestType->getScalarType()->getFltSemantics();
8435
8436 APFloat ExtCValue = ConvertFltSema(*CValue, DestFltSema);
8437 APFloat ExtNextCValue = ConvertFltSema(NextCValue, DestFltSema);
8438
8439 // When 'NextCValue' is infinity, use an imaged 'NextCValue' that equals
8440 // 'CValue + bias' to avoid the infinity after conversion. The bias is
8441 // estimated as 'CValue - PrevCValue', where 'PrevCValue' is the previous
8442 // value of 'CValue'.
8443 if (NextCValue.isInfinity()) {
8444 APFloat PrevCValue = NextValue(*CValue, !RoundDown);
8445 APFloat Bias = ConvertFltSema(*CValue - PrevCValue, DestFltSema);
8446
8447 ExtNextCValue = ExtCValue + Bias;
8448 }
8449
8450 APFloat ExtMidValue =
8451 scalbn(X: ExtCValue + ExtNextCValue, Exp: -1, RM: APFloat::rmNearestTiesToEven);
8452
8453 const fltSemantics &SrcFltSema =
8454 C.getType()->getScalarType()->getFltSemantics();
8455
8456 // 'MidValue' might be rounded to 'NextCValue'. Correct it here.
8457 APFloat MidValue = ConvertFltSema(ExtMidValue, SrcFltSema);
8458 if (MidValue != *CValue)
8459 ExtMidValue.next(nextDown: !RoundDown);
8460
8461 // Check whether 'ExtMidValue' is a valid result since the assumption on
8462 // imaged 'NextCValue' might not hold for new float types.
8463 // ppc_fp128 can't pass here when converting from max float because of
8464 // APFloat implementation.
8465 if (NextCValue.isInfinity()) {
8466 // ExtMidValue --- narrowed ---> Finite
8467 if (ConvertFltSema(ExtMidValue, SrcFltSema).isInfinity())
8468 return nullptr;
8469
8470 // NextExtMidValue --- narrowed ---> Infinity
8471 APFloat NextExtMidValue = NextValue(ExtMidValue, RoundDown);
8472 if (ConvertFltSema(NextExtMidValue, SrcFltSema).isFinite())
8473 return nullptr;
8474 }
8475
8476 return new FCmpInst(Pred, FPTrunc.getOperand(i: 0),
8477 ConstantFP::get(Ty: DestType, V: ExtMidValue), "", &I);
8478}
8479
8480/// Optimize fabs(X) compared with zero.
8481static Instruction *foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
8482 Value *X;
8483 if (!match(V: I.getOperand(i_nocapture: 0), P: m_FAbs(Op0: m_Value(V&: X))))
8484 return nullptr;
8485
8486 const APFloat *C;
8487 if (!match(V: I.getOperand(i_nocapture: 1), P: m_APFloat(Res&: C)))
8488 return nullptr;
8489
8490 if (!C->isPosZero()) {
8491 if (!C->isSmallestNormalized())
8492 return nullptr;
8493
8494 const Function *F = I.getFunction();
8495 DenormalMode Mode = F->getDenormalMode(FPType: C->getSemantics());
8496 if (Mode.Input == DenormalMode::PreserveSign ||
8497 Mode.Input == DenormalMode::PositiveZero) {
8498
8499 auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8500 Constant *Zero = ConstantFP::getZero(Ty: X->getType());
8501 return new FCmpInst(P, X, Zero, "", I);
8502 };
8503
8504 switch (I.getPredicate()) {
8505 case FCmpInst::FCMP_OLT:
8506 // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
8507 return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
8508 case FCmpInst::FCMP_UGE:
8509 // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
8510 return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
8511 case FCmpInst::FCMP_OGE:
8512 // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
8513 return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
8514 case FCmpInst::FCMP_ULT:
8515 // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
8516 return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
8517 default:
8518 break;
8519 }
8520 }
8521
8522 return nullptr;
8523 }
8524
8525 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8526 I->setPredicate(P);
8527 return IC.replaceOperand(I&: *I, OpNum: 0, V: X);
8528 };
8529
8530 switch (I.getPredicate()) {
8531 case FCmpInst::FCMP_UGE:
8532 case FCmpInst::FCMP_OLT:
8533 // fabs(X) >= 0.0 --> true
8534 // fabs(X) < 0.0 --> false
8535 llvm_unreachable("fcmp should have simplified");
8536
8537 case FCmpInst::FCMP_OGT:
8538 // fabs(X) > 0.0 --> X != 0.0
8539 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
8540
8541 case FCmpInst::FCMP_UGT:
8542 // fabs(X) u> 0.0 --> X u!= 0.0
8543 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
8544
8545 case FCmpInst::FCMP_OLE:
8546 // fabs(X) <= 0.0 --> X == 0.0
8547 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
8548
8549 case FCmpInst::FCMP_ULE:
8550 // fabs(X) u<= 0.0 --> X u== 0.0
8551 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
8552
8553 case FCmpInst::FCMP_OGE:
8554 // fabs(X) >= 0.0 --> !isnan(X)
8555 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8556 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
8557
8558 case FCmpInst::FCMP_ULT:
8559 // fabs(X) u< 0.0 --> isnan(X)
8560 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8561 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
8562
8563 case FCmpInst::FCMP_OEQ:
8564 case FCmpInst::FCMP_UEQ:
8565 case FCmpInst::FCMP_ONE:
8566 case FCmpInst::FCMP_UNE:
8567 case FCmpInst::FCMP_ORD:
8568 case FCmpInst::FCMP_UNO:
8569 // Look through the fabs() because it doesn't change anything but the sign.
8570 // fabs(X) == 0.0 --> X == 0.0,
8571 // fabs(X) != 0.0 --> X != 0.0
8572 // isnan(fabs(X)) --> isnan(X)
8573 // !isnan(fabs(X) --> !isnan(X)
8574 return replacePredAndOp0(&I, I.getPredicate(), X);
8575
8576 default:
8577 return nullptr;
8578 }
8579}
8580
8581/// Optimize sqrt(X) compared with zero.
8582static Instruction *foldSqrtWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
8583 Value *X;
8584 if (!match(V: I.getOperand(i_nocapture: 0), P: m_Sqrt(Op0: m_Value(V&: X))))
8585 return nullptr;
8586
8587 if (!match(V: I.getOperand(i_nocapture: 1), P: m_PosZeroFP()))
8588 return nullptr;
8589
8590 auto ReplacePredAndOp0 = [&](FCmpInst::Predicate P) {
8591 I.setPredicate(P);
8592 return IC.replaceOperand(I, OpNum: 0, V: X);
8593 };
8594
8595 // Clear ninf flag if sqrt doesn't have it.
8596 if (!cast<Instruction>(Val: I.getOperand(i_nocapture: 0))->hasNoInfs())
8597 I.setHasNoInfs(false);
8598
8599 switch (I.getPredicate()) {
8600 case FCmpInst::FCMP_OLT:
8601 case FCmpInst::FCMP_UGE:
8602 // sqrt(X) < 0.0 --> false
8603 // sqrt(X) u>= 0.0 --> true
8604 llvm_unreachable("fcmp should have simplified");
8605 case FCmpInst::FCMP_ULT:
8606 case FCmpInst::FCMP_ULE:
8607 case FCmpInst::FCMP_OGT:
8608 case FCmpInst::FCMP_OGE:
8609 case FCmpInst::FCMP_OEQ:
8610 case FCmpInst::FCMP_UNE:
8611 // sqrt(X) u< 0.0 --> X u< 0.0
8612 // sqrt(X) u<= 0.0 --> X u<= 0.0
8613 // sqrt(X) > 0.0 --> X > 0.0
8614 // sqrt(X) >= 0.0 --> X >= 0.0
8615 // sqrt(X) == 0.0 --> X == 0.0
8616 // sqrt(X) u!= 0.0 --> X u!= 0.0
8617 return IC.replaceOperand(I, OpNum: 0, V: X);
8618
8619 case FCmpInst::FCMP_OLE:
8620 // sqrt(X) <= 0.0 --> X == 0.0
8621 return ReplacePredAndOp0(FCmpInst::FCMP_OEQ);
8622 case FCmpInst::FCMP_UGT:
8623 // sqrt(X) u> 0.0 --> X u!= 0.0
8624 return ReplacePredAndOp0(FCmpInst::FCMP_UNE);
8625 case FCmpInst::FCMP_UEQ:
8626 // sqrt(X) u== 0.0 --> X u<= 0.0
8627 return ReplacePredAndOp0(FCmpInst::FCMP_ULE);
8628 case FCmpInst::FCMP_ONE:
8629 // sqrt(X) != 0.0 --> X > 0.0
8630 return ReplacePredAndOp0(FCmpInst::FCMP_OGT);
8631 case FCmpInst::FCMP_ORD:
8632 // !isnan(sqrt(X)) --> X >= 0.0
8633 return ReplacePredAndOp0(FCmpInst::FCMP_OGE);
8634 case FCmpInst::FCMP_UNO:
8635 // isnan(sqrt(X)) --> X u< 0.0
8636 return ReplacePredAndOp0(FCmpInst::FCMP_ULT);
8637 default:
8638 llvm_unreachable("Unexpected predicate!");
8639 }
8640}
8641
8642static Instruction *foldFCmpFNegCommonOp(FCmpInst &I) {
8643 CmpInst::Predicate Pred = I.getPredicate();
8644 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
8645
8646 // Canonicalize fneg as Op1.
8647 if (match(V: Op0, P: m_FNeg(X: m_Value())) && !match(V: Op1, P: m_FNeg(X: m_Value()))) {
8648 std::swap(a&: Op0, b&: Op1);
8649 Pred = I.getSwappedPredicate();
8650 }
8651
8652 if (!match(V: Op1, P: m_FNeg(X: m_Specific(V: Op0))))
8653 return nullptr;
8654
8655 // Replace the negated operand with 0.0:
8656 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
8657 Constant *Zero = ConstantFP::getZero(Ty: Op0->getType());
8658 return new FCmpInst(Pred, Op0, Zero, "", &I);
8659}
8660
8661static Instruction *foldFCmpFSubIntoFCmp(FCmpInst &I, Instruction *LHSI,
8662 Constant *RHSC, InstCombinerImpl &CI) {
8663 const CmpInst::Predicate Pred = I.getPredicate();
8664 Value *X = LHSI->getOperand(i: 0);
8665 Value *Y = LHSI->getOperand(i: 1);
8666 switch (Pred) {
8667 default:
8668 break;
8669 case FCmpInst::FCMP_UGT:
8670 case FCmpInst::FCMP_ULT:
8671 case FCmpInst::FCMP_UNE:
8672 case FCmpInst::FCMP_OEQ:
8673 case FCmpInst::FCMP_OGE:
8674 case FCmpInst::FCMP_OLE:
8675 // The optimization is not valid if X and Y are infinities of the same
8676 // sign, i.e. the inf - inf = nan case. If the fsub has the ninf or nnan
8677 // flag then we can assume we do not have that case. Otherwise we might be
8678 // able to prove that either X or Y is not infinity.
8679 if (!LHSI->hasNoNaNs() && !LHSI->hasNoInfs() &&
8680 !isKnownNeverInfinity(V: Y,
8681 SQ: CI.getSimplifyQuery().getWithInstruction(I: &I)) &&
8682 !isKnownNeverInfinity(V: X, SQ: CI.getSimplifyQuery().getWithInstruction(I: &I)))
8683 break;
8684
8685 [[fallthrough]];
8686 case FCmpInst::FCMP_OGT:
8687 case FCmpInst::FCMP_OLT:
8688 case FCmpInst::FCMP_ONE:
8689 case FCmpInst::FCMP_UEQ:
8690 case FCmpInst::FCMP_UGE:
8691 case FCmpInst::FCMP_ULE:
8692 // fcmp pred (x - y), 0 --> fcmp pred x, y
8693 if (match(V: RHSC, P: m_AnyZeroFP()) &&
8694 I.getFunction()->getDenormalMode(
8695 FPType: LHSI->getType()->getScalarType()->getFltSemantics()) ==
8696 DenormalMode::getIEEE()) {
8697 CI.replaceOperand(I, OpNum: 0, V: X);
8698 CI.replaceOperand(I, OpNum: 1, V: Y);
8699 I.setHasNoInfs(LHSI->hasNoInfs());
8700 if (LHSI->hasNoNaNs())
8701 I.setHasNoNaNs(true);
8702 return &I;
8703 }
8704 break;
8705 }
8706
8707 return nullptr;
8708}
8709
8710static Instruction *foldFCmpWithFloorAndCeil(FCmpInst &I,
8711 InstCombinerImpl &IC) {
8712 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
8713 Type *OpType = LHS->getType();
8714 CmpInst::Predicate Pred = I.getPredicate();
8715
8716 bool FloorX = match(V: LHS, P: m_Intrinsic<Intrinsic::floor>(Op0: m_Specific(V: RHS)));
8717 bool CeilX = match(V: LHS, P: m_Intrinsic<Intrinsic::ceil>(Op0: m_Specific(V: RHS)));
8718
8719 if (!FloorX && !CeilX) {
8720 if ((FloorX = match(V: RHS, P: m_Intrinsic<Intrinsic::floor>(Op0: m_Specific(V: LHS)))) ||
8721 (CeilX = match(V: RHS, P: m_Intrinsic<Intrinsic::ceil>(Op0: m_Specific(V: LHS))))) {
8722 std::swap(a&: LHS, b&: RHS);
8723 Pred = I.getSwappedPredicate();
8724 }
8725 }
8726
8727 switch (Pred) {
8728 case FCmpInst::FCMP_OLE:
8729 // fcmp ole floor(x), x => fcmp ord x, 0
8730 if (FloorX)
8731 return new FCmpInst(FCmpInst::FCMP_ORD, RHS, ConstantFP::getZero(Ty: OpType),
8732 "", &I);
8733 break;
8734 case FCmpInst::FCMP_OGT:
8735 // fcmp ogt floor(x), x => false
8736 if (FloorX)
8737 return IC.replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8738 break;
8739 case FCmpInst::FCMP_OGE:
8740 // fcmp oge ceil(x), x => fcmp ord x, 0
8741 if (CeilX)
8742 return new FCmpInst(FCmpInst::FCMP_ORD, RHS, ConstantFP::getZero(Ty: OpType),
8743 "", &I);
8744 break;
8745 case FCmpInst::FCMP_OLT:
8746 // fcmp olt ceil(x), x => false
8747 if (CeilX)
8748 return IC.replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8749 break;
8750 case FCmpInst::FCMP_ULE:
8751 // fcmp ule floor(x), x => true
8752 if (FloorX)
8753 return IC.replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8754 break;
8755 case FCmpInst::FCMP_UGT:
8756 // fcmp ugt floor(x), x => fcmp uno x, 0
8757 if (FloorX)
8758 return new FCmpInst(FCmpInst::FCMP_UNO, RHS, ConstantFP::getZero(Ty: OpType),
8759 "", &I);
8760 break;
8761 case FCmpInst::FCMP_UGE:
8762 // fcmp uge ceil(x), x => true
8763 if (CeilX)
8764 return IC.replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8765 break;
8766 case FCmpInst::FCMP_ULT:
8767 // fcmp ult ceil(x), x => fcmp uno x, 0
8768 if (CeilX)
8769 return new FCmpInst(FCmpInst::FCMP_UNO, RHS, ConstantFP::getZero(Ty: OpType),
8770 "", &I);
8771 break;
8772 default:
8773 break;
8774 }
8775
8776 return nullptr;
8777}
8778
8779/// Returns true if a select that implements a min/max is redundant and
8780/// select result can be replaced with its non-constant operand, e.g.,
8781/// select ( (si/ui-to-fp A) <= C ), C, (si/ui-to-fp A)
8782/// where C is the FP constant equal to the minimum integer value
8783/// representable by A.
8784static bool isMinMaxCmpSelectEliminable(SelectPatternFlavor Flavor, Value *A,
8785 Value *B) {
8786 const APFloat *APF;
8787 if (!match(V: B, P: m_APFloat(Res&: APF)))
8788 return false;
8789
8790 auto *I = dyn_cast<Instruction>(Val: A);
8791 if (!I || !(I->getOpcode() == Instruction::SIToFP ||
8792 I->getOpcode() == Instruction::UIToFP))
8793 return false;
8794
8795 bool IsUnsigned = I->getOpcode() == Instruction::UIToFP;
8796 unsigned BitWidth = I->getOperand(i: 0)->getType()->getScalarSizeInBits();
8797 APSInt IntBoundary = (Flavor == SPF_FMAXNUM)
8798 ? APSInt::getMinValue(numBits: BitWidth, Unsigned: IsUnsigned)
8799 : APSInt::getMaxValue(numBits: BitWidth, Unsigned: IsUnsigned);
8800 APSInt ConvertedInt(BitWidth, IsUnsigned);
8801 bool IsExact;
8802 APFloat::opStatus Status =
8803 APF->convertToInteger(Result&: ConvertedInt, RM: APFloat::rmTowardZero, IsExact: &IsExact);
8804 return Status == APFloat::opOK && IsExact && ConvertedInt == IntBoundary;
8805}
8806
8807Instruction *InstCombinerImpl::visitFCmpInst(FCmpInst &I) {
8808 bool Changed = false;
8809
8810 /// Orders the operands of the compare so that they are listed from most
8811 /// complex to least complex. This puts constants before unary operators,
8812 /// before binary operators.
8813 if (getComplexity(V: I.getOperand(i_nocapture: 0)) < getComplexity(V: I.getOperand(i_nocapture: 1))) {
8814 I.swapOperands();
8815 Changed = true;
8816 }
8817
8818 const CmpInst::Predicate Pred = I.getPredicate();
8819 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
8820 if (Value *V = simplifyFCmpInst(Predicate: Pred, LHS: Op0, RHS: Op1, FMF: I.getFastMathFlags(),
8821 Q: SQ.getWithInstruction(I: &I)))
8822 return replaceInstUsesWith(I, V);
8823
8824 // Simplify 'fcmp pred X, X'
8825 Type *OpType = Op0->getType();
8826 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
8827 if (Op0 == Op1) {
8828 switch (Pred) {
8829 default:
8830 break;
8831 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
8832 case FCmpInst::FCMP_ULT: // True if unordered or less than
8833 case FCmpInst::FCMP_UGT: // True if unordered or greater than
8834 case FCmpInst::FCMP_UNE: // True if unordered or not equal
8835 // Canonicalize these to be 'fcmp uno %X, 0.0'.
8836 I.setPredicate(FCmpInst::FCMP_UNO);
8837 I.setOperand(i_nocapture: 1, Val_nocapture: Constant::getNullValue(Ty: OpType));
8838 return &I;
8839
8840 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
8841 case FCmpInst::FCMP_OEQ: // True if ordered and equal
8842 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
8843 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
8844 // Canonicalize these to be 'fcmp ord %X, 0.0'.
8845 I.setPredicate(FCmpInst::FCMP_ORD);
8846 I.setOperand(i_nocapture: 1, Val_nocapture: Constant::getNullValue(Ty: OpType));
8847 return &I;
8848 }
8849 }
8850
8851 if (I.isCommutative()) {
8852 if (auto Pair = matchSymmetricPair(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1))) {
8853 replaceOperand(I, OpNum: 0, V: Pair->first);
8854 replaceOperand(I, OpNum: 1, V: Pair->second);
8855 return &I;
8856 }
8857 }
8858
8859 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
8860 // then canonicalize the operand to 0.0.
8861 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
8862 if (!match(V: Op0, P: m_PosZeroFP()) &&
8863 isKnownNeverNaN(V: Op0, SQ: getSimplifyQuery().getWithInstruction(I: &I)))
8864 return replaceOperand(I, OpNum: 0, V: ConstantFP::getZero(Ty: OpType));
8865
8866 if (!match(V: Op1, P: m_PosZeroFP()) &&
8867 isKnownNeverNaN(V: Op1, SQ: getSimplifyQuery().getWithInstruction(I: &I)))
8868 return replaceOperand(I, OpNum: 1, V: ConstantFP::getZero(Ty: OpType));
8869 }
8870
8871 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
8872 Value *X, *Y;
8873 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: X))) && match(V: Op1, P: m_FNeg(X: m_Value(V&: Y))))
8874 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
8875
8876 if (Instruction *R = foldFCmpFNegCommonOp(I))
8877 return R;
8878
8879 // Test if the FCmpInst instruction is used exclusively by a select as
8880 // part of a minimum or maximum operation. If so, refrain from doing
8881 // any other folding. This helps out other analyses which understand
8882 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
8883 // and CodeGen. And in this case, at least one of the comparison
8884 // operands has at least one user besides the compare (the select),
8885 // which would often largely negate the benefit of folding anyway.
8886 if (I.hasOneUse())
8887 if (SelectInst *SI = dyn_cast<SelectInst>(Val: I.user_back())) {
8888 Value *A, *B;
8889 SelectPatternResult SPR = matchSelectPattern(V: SI, LHS&: A, RHS&: B);
8890 bool IsRedundantMinMaxClamp =
8891 (SPR.Flavor == SPF_FMAXNUM || SPR.Flavor == SPF_FMINNUM) &&
8892 isMinMaxCmpSelectEliminable(Flavor: SPR.Flavor, A, B);
8893 if (SPR.Flavor != SPF_UNKNOWN && !IsRedundantMinMaxClamp)
8894 return nullptr;
8895 }
8896
8897 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
8898 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
8899 if (match(V: Op1, P: m_AnyZeroFP()) && !match(V: Op1, P: m_PosZeroFP()))
8900 return replaceOperand(I, OpNum: 1, V: ConstantFP::getZero(Ty: OpType));
8901
8902 // Canonicalize:
8903 // fcmp olt X, +inf -> fcmp one X, +inf
8904 // fcmp ole X, +inf -> fcmp ord X, 0
8905 // fcmp ogt X, +inf -> false
8906 // fcmp oge X, +inf -> fcmp oeq X, +inf
8907 // fcmp ult X, +inf -> fcmp une X, +inf
8908 // fcmp ule X, +inf -> true
8909 // fcmp ugt X, +inf -> fcmp uno X, 0
8910 // fcmp uge X, +inf -> fcmp ueq X, +inf
8911 // fcmp olt X, -inf -> false
8912 // fcmp ole X, -inf -> fcmp oeq X, -inf
8913 // fcmp ogt X, -inf -> fcmp one X, -inf
8914 // fcmp oge X, -inf -> fcmp ord X, 0
8915 // fcmp ult X, -inf -> fcmp uno X, 0
8916 // fcmp ule X, -inf -> fcmp ueq X, -inf
8917 // fcmp ugt X, -inf -> fcmp une X, -inf
8918 // fcmp uge X, -inf -> true
8919 const APFloat *C;
8920 if (match(V: Op1, P: m_APFloat(Res&: C)) && C->isInfinity()) {
8921 switch (C->isNegative() ? FCmpInst::getSwappedPredicate(pred: Pred) : Pred) {
8922 default:
8923 break;
8924 case FCmpInst::FCMP_ORD:
8925 case FCmpInst::FCMP_UNO:
8926 case FCmpInst::FCMP_TRUE:
8927 case FCmpInst::FCMP_FALSE:
8928 case FCmpInst::FCMP_OGT:
8929 case FCmpInst::FCMP_ULE:
8930 llvm_unreachable("Should be simplified by InstSimplify");
8931 case FCmpInst::FCMP_OLT:
8932 return new FCmpInst(FCmpInst::FCMP_ONE, Op0, Op1, "", &I);
8933 case FCmpInst::FCMP_OLE:
8934 return new FCmpInst(FCmpInst::FCMP_ORD, Op0, ConstantFP::getZero(Ty: OpType),
8935 "", &I);
8936 case FCmpInst::FCMP_OGE:
8937 return new FCmpInst(FCmpInst::FCMP_OEQ, Op0, Op1, "", &I);
8938 case FCmpInst::FCMP_ULT:
8939 return new FCmpInst(FCmpInst::FCMP_UNE, Op0, Op1, "", &I);
8940 case FCmpInst::FCMP_UGT:
8941 return new FCmpInst(FCmpInst::FCMP_UNO, Op0, ConstantFP::getZero(Ty: OpType),
8942 "", &I);
8943 case FCmpInst::FCMP_UGE:
8944 return new FCmpInst(FCmpInst::FCMP_UEQ, Op0, Op1, "", &I);
8945 }
8946 }
8947
8948 // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
8949 // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
8950 if (match(V: Op1, P: m_PosZeroFP()) &&
8951 match(V: Op0, P: m_OneUse(SubPattern: m_ElementWiseBitCast(Op: m_Value(V&: X)))) &&
8952 !F.getDenormalMode(FPType: Op1->getType()->getScalarType()->getFltSemantics())
8953 .inputsMayBeZero()) {
8954 ICmpInst::Predicate IntPred = ICmpInst::BAD_ICMP_PREDICATE;
8955 if (Pred == FCmpInst::FCMP_OEQ)
8956 IntPred = ICmpInst::ICMP_EQ;
8957 else if (Pred == FCmpInst::FCMP_UNE)
8958 IntPred = ICmpInst::ICMP_NE;
8959
8960 if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
8961 Type *IntTy = X->getType();
8962 const APInt &SignMask = ~APInt::getSignMask(BitWidth: IntTy->getScalarSizeInBits());
8963 Value *MaskX = Builder.CreateAnd(LHS: X, RHS: ConstantInt::get(Ty: IntTy, V: SignMask));
8964 return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(Ty: IntTy));
8965 }
8966 }
8967
8968 // Handle fcmp with instruction LHS and constant RHS.
8969 Instruction *LHSI;
8970 Constant *RHSC;
8971 if (match(V: Op0, P: m_Instruction(I&: LHSI)) && match(V: Op1, P: m_Constant(C&: RHSC))) {
8972 switch (LHSI->getOpcode()) {
8973 case Instruction::Select:
8974 // fcmp eq (cond ? x : -x), 0 --> fcmp eq x, 0
8975 if (FCmpInst::isEquality(Pred) && match(V: RHSC, P: m_AnyZeroFP()) &&
8976 match(V: LHSI, P: m_c_Select(L: m_FNeg(X: m_Value(V&: X)), R: m_Deferred(V: X))))
8977 return replaceOperand(I, OpNum: 0, V: X);
8978 if (Instruction *NV = FoldOpIntoSelect(Op&: I, SI: cast<SelectInst>(Val: LHSI)))
8979 return NV;
8980 break;
8981 case Instruction::FSub:
8982 if (LHSI->hasOneUse())
8983 if (Instruction *NV = foldFCmpFSubIntoFCmp(I, LHSI, RHSC, CI&: *this))
8984 return NV;
8985 break;
8986 case Instruction::PHI:
8987 if (Instruction *NV = foldOpIntoPhi(I, PN: cast<PHINode>(Val: LHSI)))
8988 return NV;
8989 break;
8990 case Instruction::SIToFP:
8991 case Instruction::UIToFP:
8992 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
8993 return NV;
8994 break;
8995 case Instruction::FDiv:
8996 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
8997 return NV;
8998 break;
8999 case Instruction::Load:
9000 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: LHSI->getOperand(i: 0)))
9001 if (Instruction *Res =
9002 foldCmpLoadFromIndexedGlobal(LI: cast<LoadInst>(Val: LHSI), GEP, ICI&: I))
9003 return Res;
9004 break;
9005 case Instruction::FPTrunc:
9006 if (Instruction *NV = foldFCmpFpTrunc(I, FPTrunc: *LHSI, C: *RHSC))
9007 return NV;
9008 break;
9009 }
9010 }
9011
9012 if (Instruction *R = foldFabsWithFcmpZero(I, IC&: *this))
9013 return R;
9014
9015 if (Instruction *R = foldSqrtWithFcmpZero(I, IC&: *this))
9016 return R;
9017
9018 if (Instruction *R = foldFCmpWithFloorAndCeil(I, IC&: *this))
9019 return R;
9020
9021 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: X)))) {
9022 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
9023 Constant *C;
9024 if (match(V: Op1, P: m_Constant(C)))
9025 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL))
9026 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
9027 }
9028
9029 // fcmp (fadd X, 0.0), Y --> fcmp X, Y
9030 if (match(V: Op0, P: m_FAdd(L: m_Value(V&: X), R: m_AnyZeroFP())))
9031 return new FCmpInst(Pred, X, Op1, "", &I);
9032
9033 // fcmp X, (fadd Y, 0.0) --> fcmp X, Y
9034 if (match(V: Op1, P: m_FAdd(L: m_Value(V&: Y), R: m_AnyZeroFP())))
9035 return new FCmpInst(Pred, Op0, Y, "", &I);
9036
9037 if (match(V: Op0, P: m_FPExt(Op: m_Value(V&: X)))) {
9038 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
9039 if (match(V: Op1, P: m_FPExt(Op: m_Value(V&: Y))) && X->getType() == Y->getType())
9040 return new FCmpInst(Pred, X, Y, "", &I);
9041
9042 const APFloat *C;
9043 if (match(V: Op1, P: m_APFloat(Res&: C))) {
9044 const fltSemantics &FPSem =
9045 X->getType()->getScalarType()->getFltSemantics();
9046 bool Lossy;
9047 APFloat TruncC = *C;
9048 TruncC.convert(ToSemantics: FPSem, RM: APFloat::rmNearestTiesToEven, losesInfo: &Lossy);
9049
9050 if (Lossy) {
9051 // X can't possibly equal the higher-precision constant, so reduce any
9052 // equality comparison.
9053 // TODO: Other predicates can be handled via getFCmpCode().
9054 switch (Pred) {
9055 case FCmpInst::FCMP_OEQ:
9056 // X is ordered and equal to an impossible constant --> false
9057 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
9058 case FCmpInst::FCMP_ONE:
9059 // X is ordered and not equal to an impossible constant --> ordered
9060 return new FCmpInst(FCmpInst::FCMP_ORD, X,
9061 ConstantFP::getZero(Ty: X->getType()));
9062 case FCmpInst::FCMP_UEQ:
9063 // X is unordered or equal to an impossible constant --> unordered
9064 return new FCmpInst(FCmpInst::FCMP_UNO, X,
9065 ConstantFP::getZero(Ty: X->getType()));
9066 case FCmpInst::FCMP_UNE:
9067 // X is unordered or not equal to an impossible constant --> true
9068 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
9069 default:
9070 break;
9071 }
9072 }
9073
9074 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
9075 // Avoid lossy conversions and denormals.
9076 // Zero is a special case that's OK to convert.
9077 APFloat Fabs = TruncC;
9078 Fabs.clearSign();
9079 if (!Lossy &&
9080 (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(Sem: FPSem)))) {
9081 Constant *NewC = ConstantFP::get(Ty: X->getType(), V: TruncC);
9082 return new FCmpInst(Pred, X, NewC, "", &I);
9083 }
9084 }
9085 }
9086
9087 // Convert a sign-bit test of an FP value into a cast and integer compare.
9088 // TODO: Simplify if the copysign constant is 0.0 or NaN.
9089 // TODO: Handle non-zero compare constants.
9090 // TODO: Handle other predicates.
9091 if (match(V: Op0, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::copysign>(Op0: m_APFloat(Res&: C),
9092 Op1: m_Value(V&: X)))) &&
9093 match(V: Op1, P: m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
9094 Type *IntType = Builder.getIntNTy(N: X->getType()->getScalarSizeInBits());
9095 if (auto *VecTy = dyn_cast<VectorType>(Val: OpType))
9096 IntType = VectorType::get(ElementType: IntType, EC: VecTy->getElementCount());
9097
9098 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
9099 if (Pred == FCmpInst::FCMP_OLT) {
9100 Value *IntX = Builder.CreateBitCast(V: X, DestTy: IntType);
9101 return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
9102 ConstantInt::getNullValue(Ty: IntType));
9103 }
9104 }
9105
9106 {
9107 Value *CanonLHS = nullptr;
9108 match(V: Op0, P: m_Intrinsic<Intrinsic::canonicalize>(Op0: m_Value(V&: CanonLHS)));
9109 // (canonicalize(x) == x) => (x == x)
9110 if (CanonLHS == Op1)
9111 return new FCmpInst(Pred, Op1, Op1, "", &I);
9112
9113 Value *CanonRHS = nullptr;
9114 match(V: Op1, P: m_Intrinsic<Intrinsic::canonicalize>(Op0: m_Value(V&: CanonRHS)));
9115 // (x == canonicalize(x)) => (x == x)
9116 if (CanonRHS == Op0)
9117 return new FCmpInst(Pred, Op0, Op0, "", &I);
9118
9119 // (canonicalize(x) == canonicalize(y)) => (x == y)
9120 if (CanonLHS && CanonRHS)
9121 return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
9122 }
9123
9124 if (I.getType()->isVectorTy())
9125 if (Instruction *Res = foldVectorCmp(Cmp&: I, Builder))
9126 return Res;
9127
9128 return Changed ? &I : nullptr;
9129}
9130