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/Instruction.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/PatternMatch.h"
33#include "llvm/Support/KnownBits.h"
34#include "llvm/Transforms/InstCombine/InstCombiner.h"
35#include <bitset>
36
37using namespace llvm;
38using namespace PatternMatch;
39
40#define DEBUG_TYPE "instcombine"
41
42// How many times is a select replaced by one of its operands?
43STATISTIC(NumSel, "Number of select opts");
44
45namespace llvm {
46extern cl::opt<bool> ProfcheckDisableMetadataFixes;
47}
48
49/// Compute Result = In1+In2, returning true if the result overflowed for this
50/// type.
51static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
52 bool IsSigned = false) {
53 bool Overflow;
54 if (IsSigned)
55 Result = In1.sadd_ov(RHS: In2, Overflow);
56 else
57 Result = In1.uadd_ov(RHS: In2, Overflow);
58
59 return Overflow;
60}
61
62/// Compute Result = In1-In2, returning true if the result overflowed for this
63/// type.
64static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
65 bool IsSigned = false) {
66 bool Overflow;
67 if (IsSigned)
68 Result = In1.ssub_ov(RHS: In2, Overflow);
69 else
70 Result = In1.usub_ov(RHS: In2, Overflow);
71
72 return Overflow;
73}
74
75/// Given an icmp instruction, return true if any use of this comparison is a
76/// branch on sign bit comparison.
77static bool hasBranchUse(ICmpInst &I) {
78 for (auto *U : I.users())
79 if (isa<CondBrInst>(Val: U))
80 return true;
81 return false;
82}
83
84/// Returns true if the exploded icmp can be expressed as a signed comparison
85/// to zero and updates the predicate accordingly.
86/// The signedness of the comparison is preserved.
87/// TODO: Refactor with decomposeBitTestICmp()?
88static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
89 if (!ICmpInst::isSigned(Pred))
90 return false;
91
92 if (C.isZero())
93 return ICmpInst::isRelational(P: Pred);
94
95 if (C.isOne()) {
96 if (Pred == ICmpInst::ICMP_SLT) {
97 Pred = ICmpInst::ICMP_SLE;
98 return true;
99 }
100 } else if (C.isAllOnes()) {
101 if (Pred == ICmpInst::ICMP_SGT) {
102 Pred = ICmpInst::ICMP_SGE;
103 return true;
104 }
105 }
106
107 return false;
108}
109
110/// This is called when we see this pattern:
111/// cmp pred (load (gep GV, ...)), cmpcst
112/// where GV is a global variable with a constant initializer. Try to simplify
113/// this into some simple computation that does not need the load. For example
114/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
115///
116/// If AndCst is non-null, then the loaded value is masked with that constant
117/// before doing the comparison. This handles cases like "A[i]&4 == 0".
118///
119/// We allow multi-use cases in this fold, even though it can increase
120/// instruction count, because it appears to be mostly beneficial in practice.
121/// Even if there are multiple uses, they can often be sunk into the block
122/// guarded by the icmp.
123Instruction *InstCombinerImpl::foldCmpLoadFromIndexedGlobal(
124 LoadInst *LI, GetElementPtrInst *GEP, CmpInst &ICI, ConstantInt *AndCst) {
125 auto *GV = dyn_cast<GlobalVariable>(Val: getUnderlyingObject(V: GEP));
126 if (LI->isVolatile() || !GV || !GV->isConstant() ||
127 !GV->hasDefinitiveInitializer())
128 return nullptr;
129
130 Type *EltTy = LI->getType();
131 TypeSize EltSize = DL.getTypeStoreSize(Ty: EltTy);
132 if (EltSize.isScalable())
133 return nullptr;
134
135 LinearExpression Expr = decomposeLinearExpression(DL, Ptr: GEP);
136 if (!Expr.Index || Expr.BasePtr != GV || Expr.Offset.getBitWidth() > 64)
137 return nullptr;
138
139 Constant *Init = GV->getInitializer();
140 TypeSize GlobalSize = DL.getTypeAllocSize(Ty: Init->getType());
141
142 Value *Idx = Expr.Index;
143 const APInt &Stride = Expr.Scale;
144 const APInt &ConstOffset = Expr.Offset;
145
146 // Allow an additional context offset, but only within the stride.
147 if (!ConstOffset.ult(RHS: Stride))
148 return nullptr;
149
150 // Don't handle overlapping loads for now.
151 if (!Stride.uge(RHS: EltSize.getFixedValue()))
152 return nullptr;
153
154 // Don't blow up on huge arrays.
155 uint64_t ArrayElementCount =
156 divideCeil(Numerator: (GlobalSize.getFixedValue() - ConstOffset.getZExtValue()),
157 Denominator: Stride.getZExtValue());
158 if (ArrayElementCount > MaxArraySizeForCombine)
159 return nullptr;
160
161 enum { Overdefined = -3, Undefined = -2 };
162
163 // Variables for our state machines.
164
165 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
166 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
167 // and 87 is the second (and last) index. FirstTrueElement is -2 when
168 // undefined, otherwise set to the first true element. SecondTrueElement is
169 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
170 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
171
172 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
173 // form "i != 47 & i != 87". Same state transitions as for true elements.
174 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
175
176 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
177 /// define a state machine that triggers for ranges of values that the index
178 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
179 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
180 /// index in the range (inclusive). We use -2 for undefined here because we
181 /// use relative comparisons and don't want 0-1 to match -1.
182 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
183
184 // MagicBitvector - This is a magic bitvector where we set a bit if the
185 // comparison is true for element 'i'. If there are 64 elements or less in
186 // the array, this will fully represent all the comparison results.
187 uint64_t MagicBitvector = 0;
188
189 // Scan the array and see if one of our patterns matches.
190 Constant *CompareRHS = cast<Constant>(Val: ICI.getOperand(i_nocapture: 1));
191 APInt Offset = ConstOffset;
192 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i, Offset += Stride) {
193 Constant *Elt = ConstantFoldLoadFromConst(C: Init, Ty: EltTy, Offset, DL);
194 if (!Elt)
195 return nullptr;
196
197 // If the element is masked, handle it.
198 if (AndCst) {
199 Elt = ConstantFoldBinaryOpOperands(Opcode: Instruction::And, LHS: Elt, RHS: AndCst, DL);
200 if (!Elt)
201 return nullptr;
202 }
203
204 // Find out if the comparison would be true or false for the i'th element.
205 Constant *C = ConstantFoldCompareInstOperands(Predicate: ICI.getPredicate(), LHS: Elt,
206 RHS: CompareRHS, DL, TLI: &TLI);
207 if (!C)
208 return nullptr;
209
210 // If the result is undef for this element, ignore it.
211 if (isa<UndefValue>(Val: C)) {
212 // Extend range state machines to cover this element in case there is an
213 // undef in the middle of the range.
214 if (TrueRangeEnd == (int)i - 1)
215 TrueRangeEnd = i;
216 if (FalseRangeEnd == (int)i - 1)
217 FalseRangeEnd = i;
218 continue;
219 }
220
221 // If we can't compute the result for any of the elements, we have to give
222 // up evaluating the entire conditional.
223 if (!isa<ConstantInt>(Val: C))
224 return nullptr;
225
226 // Otherwise, we know if the comparison is true or false for this element,
227 // update our state machines.
228 bool IsTrueForElt = !cast<ConstantInt>(Val: C)->isZero();
229
230 // State machine for single/double/range index comparison.
231 if (IsTrueForElt) {
232 // Update the TrueElement state machine.
233 if (FirstTrueElement == Undefined)
234 FirstTrueElement = TrueRangeEnd = i; // First true element.
235 else {
236 // Update double-compare state machine.
237 if (SecondTrueElement == Undefined)
238 SecondTrueElement = i;
239 else
240 SecondTrueElement = Overdefined;
241
242 // Update range state machine.
243 if (TrueRangeEnd == (int)i - 1)
244 TrueRangeEnd = i;
245 else
246 TrueRangeEnd = Overdefined;
247 }
248 } else {
249 // Update the FalseElement state machine.
250 if (FirstFalseElement == Undefined)
251 FirstFalseElement = FalseRangeEnd = i; // First false element.
252 else {
253 // Update double-compare state machine.
254 if (SecondFalseElement == Undefined)
255 SecondFalseElement = i;
256 else
257 SecondFalseElement = Overdefined;
258
259 // Update range state machine.
260 if (FalseRangeEnd == (int)i - 1)
261 FalseRangeEnd = i;
262 else
263 FalseRangeEnd = Overdefined;
264 }
265 }
266
267 // If this element is in range, update our magic bitvector.
268 if (i < 64 && IsTrueForElt)
269 MagicBitvector |= 1ULL << i;
270
271 // If all of our states become overdefined, bail out early. Since the
272 // predicate is expensive, only check it every 8 elements. This is only
273 // really useful for really huge arrays.
274 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
275 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
276 FalseRangeEnd == Overdefined)
277 return nullptr;
278 }
279
280 // Now that we've scanned the entire array, emit our new comparison(s). We
281 // order the state machines in complexity of the generated code.
282
283 // If inbounds keyword is not present, Idx * Stride can overflow.
284 // Let's assume that Stride is 2 and the wanted value is at offset 0.
285 // Then, there are two possible values for Idx to match offset 0:
286 // 0x00..00, 0x80..00.
287 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
288 // comparison is false if Idx was 0x80..00.
289 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
290 auto MaskIdx = [&](Value *Idx) {
291 if (!Expr.Flags.isInBounds() && Stride.countr_zero() != 0) {
292 Value *Mask = Constant::getAllOnesValue(Ty: Idx->getType());
293 Mask = Builder.CreateLShr(LHS: Mask, RHS: Stride.countr_zero());
294 Idx = Builder.CreateAnd(LHS: Idx, RHS: Mask);
295 }
296 return Idx;
297 };
298
299 // If the comparison is only true for one or two elements, emit direct
300 // comparisons.
301 if (SecondTrueElement != Overdefined) {
302 Idx = MaskIdx(Idx);
303 // None true -> false.
304 if (FirstTrueElement == Undefined)
305 return replaceInstUsesWith(I&: ICI, V: Builder.getFalse());
306
307 Value *FirstTrueIdx = ConstantInt::get(Ty: Idx->getType(), V: FirstTrueElement);
308
309 // True for one element -> 'i == 47'.
310 if (SecondTrueElement == Undefined)
311 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
312
313 // True for two elements -> 'i == 47 | i == 72'.
314 Value *C1 = Builder.CreateICmpEQ(LHS: Idx, RHS: FirstTrueIdx);
315 Value *SecondTrueIdx = ConstantInt::get(Ty: Idx->getType(), V: SecondTrueElement);
316 Value *C2 = Builder.CreateICmpEQ(LHS: Idx, RHS: SecondTrueIdx);
317 return BinaryOperator::CreateOr(V1: C1, V2: C2);
318 }
319
320 // If the comparison is only false for one or two elements, emit direct
321 // comparisons.
322 if (SecondFalseElement != Overdefined) {
323 Idx = MaskIdx(Idx);
324 // None false -> true.
325 if (FirstFalseElement == Undefined)
326 return replaceInstUsesWith(I&: ICI, V: Builder.getTrue());
327
328 Value *FirstFalseIdx = ConstantInt::get(Ty: Idx->getType(), V: FirstFalseElement);
329
330 // False for one element -> 'i != 47'.
331 if (SecondFalseElement == Undefined)
332 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
333
334 // False for two elements -> 'i != 47 & i != 72'.
335 Value *C1 = Builder.CreateICmpNE(LHS: Idx, RHS: FirstFalseIdx);
336 Value *SecondFalseIdx =
337 ConstantInt::get(Ty: Idx->getType(), V: SecondFalseElement);
338 Value *C2 = Builder.CreateICmpNE(LHS: Idx, RHS: SecondFalseIdx);
339 return BinaryOperator::CreateAnd(V1: C1, V2: C2);
340 }
341
342 // If the comparison can be replaced with a range comparison for the elements
343 // where it is true, emit the range check.
344 if (TrueRangeEnd != Overdefined) {
345 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
346 Idx = MaskIdx(Idx);
347
348 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
349 if (FirstTrueElement) {
350 Value *Offs = ConstantInt::getSigned(Ty: Idx->getType(), V: -FirstTrueElement);
351 Idx = Builder.CreateAdd(LHS: Idx, RHS: Offs);
352 }
353
354 Value *End =
355 ConstantInt::get(Ty: Idx->getType(), V: TrueRangeEnd - FirstTrueElement + 1);
356 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
357 }
358
359 // False range check.
360 if (FalseRangeEnd != Overdefined) {
361 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
362 Idx = MaskIdx(Idx);
363 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
364 if (FirstFalseElement) {
365 Value *Offs = ConstantInt::getSigned(Ty: Idx->getType(), V: -FirstFalseElement);
366 Idx = Builder.CreateAdd(LHS: Idx, RHS: Offs);
367 }
368
369 Value *End =
370 ConstantInt::get(Ty: Idx->getType(), V: FalseRangeEnd - FirstFalseElement);
371 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
372 }
373
374 // If a magic bitvector captures the entire comparison state
375 // of this load, replace it with computation that does:
376 // ((magic_cst >> i) & 1) != 0
377 {
378 Type *Ty = nullptr;
379
380 // Look for an appropriate type:
381 // - The type of Idx if the magic fits
382 // - The smallest fitting legal type
383 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
384 Ty = Idx->getType();
385 else
386 Ty = DL.getSmallestLegalIntType(C&: Init->getContext(), Width: ArrayElementCount);
387
388 if (Ty) {
389 Idx = MaskIdx(Idx);
390 Value *V = Builder.CreateIntCast(V: Idx, DestTy: Ty, isSigned: false);
391 V = Builder.CreateLShr(LHS: ConstantInt::get(Ty, V: MagicBitvector), RHS: V);
392 V = Builder.CreateAnd(LHS: ConstantInt::get(Ty, V: 1), RHS: V);
393 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, V: 0));
394 }
395 }
396
397 return nullptr;
398}
399
400/// Returns true if we can rewrite Start as a GEP with pointer Base
401/// and some integer offset. The nodes that need to be re-written
402/// for this transformation will be added to Explored.
403static bool canRewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags &NW,
404 const DataLayout &DL,
405 SetVector<Value *> &Explored) {
406 SmallVector<Value *, 16> WorkList(1, Start);
407 Explored.insert(X: Base);
408
409 // The following traversal gives us an order which can be used
410 // when doing the final transformation. Since in the final
411 // transformation we create the PHI replacement instructions first,
412 // we don't have to get them in any particular order.
413 //
414 // However, for other instructions we will have to traverse the
415 // operands of an instruction first, which means that we have to
416 // do a post-order traversal.
417 while (!WorkList.empty()) {
418 SetVector<PHINode *> PHIs;
419
420 while (!WorkList.empty()) {
421 if (Explored.size() >= 100)
422 return false;
423
424 Value *V = WorkList.back();
425
426 if (Explored.contains(key: V)) {
427 WorkList.pop_back();
428 continue;
429 }
430
431 if (!isa<GetElementPtrInst>(Val: V) && !isa<PHINode>(Val: V))
432 // We've found some value that we can't explore which is different from
433 // the base. Therefore we can't do this transformation.
434 return false;
435
436 if (auto *GEP = dyn_cast<GEPOperator>(Val: V)) {
437 // Only allow inbounds GEPs with at most one variable offset.
438 auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(Val: V); };
439 if (!GEP->isInBounds() || count_if(Range: GEP->indices(), P: IsNonConst) > 1)
440 return false;
441
442 NW = NW.intersectForOffsetAdd(Other: GEP->getNoWrapFlags());
443 if (!Explored.contains(key: GEP->getOperand(i_nocapture: 0)))
444 WorkList.push_back(Elt: GEP->getOperand(i_nocapture: 0));
445 }
446
447 if (WorkList.back() == V) {
448 WorkList.pop_back();
449 // We've finished visiting this node, mark it as such.
450 Explored.insert(X: V);
451 }
452
453 if (auto *PN = dyn_cast<PHINode>(Val: V)) {
454 // We cannot transform PHIs on unsplittable basic blocks.
455 if (isa<CatchSwitchInst>(Val: PN->getParent()->getTerminator()))
456 return false;
457 Explored.insert(X: PN);
458 PHIs.insert(X: PN);
459 }
460 }
461
462 // Explore the PHI nodes further.
463 for (auto *PN : PHIs)
464 for (Value *Op : PN->incoming_values())
465 if (!Explored.contains(key: Op))
466 WorkList.push_back(Elt: Op);
467 }
468
469 // Make sure that we can do this. Since we can't insert GEPs in a basic
470 // block before a PHI node, we can't easily do this transformation if
471 // we have PHI node users of transformed instructions.
472 for (Value *Val : Explored) {
473 for (Value *Use : Val->uses()) {
474
475 auto *PHI = dyn_cast<PHINode>(Val: Use);
476 auto *Inst = dyn_cast<Instruction>(Val);
477
478 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
479 !Explored.contains(key: PHI))
480 continue;
481
482 if (PHI->getParent() == Inst->getParent())
483 return false;
484 }
485 }
486 return true;
487}
488
489// Sets the appropriate insert point on Builder where we can add
490// a replacement Instruction for V (if that is possible).
491static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
492 bool Before = true) {
493 if (auto *PHI = dyn_cast<PHINode>(Val: V)) {
494 BasicBlock *Parent = PHI->getParent();
495 Builder.SetInsertPoint(TheBB: Parent, IP: Parent->getFirstInsertionPt());
496 return;
497 }
498 if (auto *I = dyn_cast<Instruction>(Val: V)) {
499 if (!Before)
500 I = &*std::next(x: I->getIterator());
501 Builder.SetInsertPoint(I);
502 return;
503 }
504 if (auto *A = dyn_cast<Argument>(Val: V)) {
505 // Set the insertion point in the entry block.
506 BasicBlock &Entry = A->getParent()->getEntryBlock();
507 Builder.SetInsertPoint(TheBB: &Entry, IP: Entry.getFirstInsertionPt());
508 return;
509 }
510 // Otherwise, this is a constant and we don't need to set a new
511 // insertion point.
512 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
513}
514
515/// Returns a re-written value of Start as an indexed GEP using Base as a
516/// pointer.
517static Value *rewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags NW,
518 const DataLayout &DL,
519 SetVector<Value *> &Explored,
520 InstCombiner &IC) {
521 // Perform all the substitutions. This is a bit tricky because we can
522 // have cycles in our use-def chains.
523 // 1. Create the PHI nodes without any incoming values.
524 // 2. Create all the other values.
525 // 3. Add the edges for the PHI nodes.
526 // 4. Emit GEPs to get the original pointers.
527 // 5. Remove the original instructions.
528 Type *IndexType = IntegerType::get(
529 C&: Base->getContext(), NumBits: DL.getIndexTypeSizeInBits(Ty: Start->getType()));
530
531 DenseMap<Value *, Value *> NewInsts;
532 NewInsts[Base] = ConstantInt::getNullValue(Ty: IndexType);
533
534 // Create the new PHI nodes, without adding any incoming values.
535 for (Value *Val : Explored) {
536 if (Val == Base)
537 continue;
538 // Create empty phi nodes. This avoids cyclic dependencies when creating
539 // the remaining instructions.
540 if (auto *PHI = dyn_cast<PHINode>(Val))
541 NewInsts[PHI] =
542 PHINode::Create(Ty: IndexType, NumReservedValues: PHI->getNumIncomingValues(),
543 NameStr: PHI->getName() + ".idx", InsertBefore: PHI->getIterator());
544 }
545 IRBuilder<> Builder(Base->getContext());
546
547 // Create all the other instructions.
548 for (Value *Val : Explored) {
549 if (NewInsts.contains(Val))
550 continue;
551
552 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
553 setInsertionPoint(Builder, V: GEP);
554 Value *Op = NewInsts[GEP->getOperand(i_nocapture: 0)];
555 Value *OffsetV = emitGEPOffset(Builder: &Builder, DL, GEP);
556 if (isa<ConstantInt>(Val: Op) && cast<ConstantInt>(Val: Op)->isZero())
557 NewInsts[GEP] = OffsetV;
558 else
559 NewInsts[GEP] = Builder.CreateAdd(
560 LHS: Op, RHS: OffsetV, Name: GEP->getOperand(i_nocapture: 0)->getName() + ".add",
561 /*NUW=*/HasNUW: NW.hasNoUnsignedWrap(),
562 /*NSW=*/HasNSW: NW.hasNoUnsignedSignedWrap());
563 continue;
564 }
565 if (isa<PHINode>(Val))
566 continue;
567
568 llvm_unreachable("Unexpected instruction type");
569 }
570
571 // Add the incoming values to the PHI nodes.
572 for (Value *Val : Explored) {
573 if (Val == Base)
574 continue;
575 // All the instructions have been created, we can now add edges to the
576 // phi nodes.
577 if (auto *PHI = dyn_cast<PHINode>(Val)) {
578 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
579 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
580 Value *NewIncoming = PHI->getIncomingValue(i: I);
581
582 auto It = NewInsts.find(Val: NewIncoming);
583 if (It != NewInsts.end())
584 NewIncoming = It->second;
585
586 NewPhi->addIncoming(V: NewIncoming, BB: PHI->getIncomingBlock(i: I));
587 }
588 }
589 }
590
591 for (Value *Val : Explored) {
592 if (Val == Base)
593 continue;
594
595 setInsertionPoint(Builder, V: Val, Before: false);
596 // Create GEP for external users.
597 Value *NewVal = Builder.CreateGEP(Ty: Builder.getInt8Ty(), Ptr: Base, IdxList: NewInsts[Val],
598 Name: Val->getName() + ".ptr", NW);
599 IC.replaceInstUsesWith(I&: *cast<Instruction>(Val), V: NewVal);
600 // Add old instruction to worklist for DCE. We don't directly remove it
601 // here because the original compare is one of the users.
602 IC.addToWorklist(I: cast<Instruction>(Val));
603 }
604
605 return NewInsts[Start];
606}
607
608/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
609/// We can look through PHIs, GEPs and casts in order to determine a common base
610/// between GEPLHS and RHS.
611static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
612 CmpPredicate Cond,
613 const DataLayout &DL,
614 InstCombiner &IC) {
615 // FIXME: Support vector of pointers.
616 if (GEPLHS->getType()->isVectorTy())
617 return nullptr;
618
619 if (!GEPLHS->hasAllConstantIndices())
620 return nullptr;
621
622 APInt Offset(DL.getIndexTypeSizeInBits(Ty: GEPLHS->getType()), 0);
623 Value *PtrBase =
624 GEPLHS->stripAndAccumulateConstantOffsets(DL, Offset,
625 /*AllowNonInbounds*/ false);
626
627 // Bail if we looked through addrspacecast.
628 if (PtrBase->getType() != GEPLHS->getType())
629 return nullptr;
630
631 // The set of nodes that will take part in this transformation.
632 SetVector<Value *> Nodes;
633 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags();
634 if (!canRewriteGEPAsOffset(Start: RHS, Base: PtrBase, NW, DL, Explored&: Nodes))
635 return nullptr;
636
637 // We know we can re-write this as
638 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
639 // Since we've only looked through inbouds GEPs we know that we
640 // can't have overflow on either side. We can therefore re-write
641 // this as:
642 // OFFSET1 cmp OFFSET2
643 Value *NewRHS = rewriteGEPAsOffset(Start: RHS, Base: PtrBase, NW, DL, Explored&: Nodes, IC);
644
645 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
646 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
647 // offset. Since Index is the offset of LHS to the base pointer, we will now
648 // compare the offsets instead of comparing the pointers.
649 return new ICmpInst(ICmpInst::getSignedPredicate(Pred: Cond),
650 IC.Builder.getInt(AI: Offset), NewRHS);
651}
652
653/// Fold comparisons between a GEP instruction and something else. At this point
654/// we know that the GEP is on the LHS of the comparison.
655Instruction *InstCombinerImpl::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
656 CmpPredicate Cond, Instruction &I) {
657 // Don't transform signed compares of GEPs into index compares. Even if the
658 // GEP is inbounds, the final add of the base pointer can have signed overflow
659 // and would change the result of the icmp.
660 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
661 // the maximum signed value for the pointer type.
662 if (ICmpInst::isSigned(Pred: Cond))
663 return nullptr;
664
665 // Look through bitcasts and addrspacecasts. We do not however want to remove
666 // 0 GEPs.
667 if (!isa<GetElementPtrInst>(Val: RHS))
668 RHS = RHS->stripPointerCasts();
669
670 auto CanFold = [Cond](GEPNoWrapFlags NW) {
671 if (ICmpInst::isEquality(P: Cond))
672 return true;
673
674 // Unsigned predicates can be folded if the GEPs have *any* nowrap flags.
675 assert(ICmpInst::isUnsigned(Cond));
676 return NW != GEPNoWrapFlags::none();
677 };
678
679 auto NewICmp = [Cond](GEPNoWrapFlags NW, Value *Op1, Value *Op2) {
680 if (!NW.hasNoUnsignedWrap()) {
681 // Convert signed to unsigned comparison.
682 return new ICmpInst(ICmpInst::getSignedPredicate(Pred: Cond), Op1, Op2);
683 }
684
685 auto *I = new ICmpInst(Cond, Op1, Op2);
686 I->setSameSign(NW.hasNoUnsignedSignedWrap());
687 return I;
688 };
689
690 CommonPointerBase Base = CommonPointerBase::compute(LHS: GEPLHS, RHS);
691 if (Base.Ptr == RHS && CanFold(Base.LHSNW) && !Base.isExpensive()) {
692 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
693 Type *IdxTy = DL.getIndexType(PtrTy: GEPLHS->getType());
694 Value *Offset =
695 EmitGEPOffsets(GEPs: Base.LHSGEPs, NW: Base.LHSNW, IdxTy, /*RewriteGEPs=*/true);
696 return NewICmp(Base.LHSNW, Offset,
697 Constant::getNullValue(Ty: Offset->getType()));
698 }
699
700 if (GEPLHS->isInBounds() && ICmpInst::isEquality(P: Cond) &&
701 isa<ConstantPointerNull>(Val: RHS) &&
702 !NullPointerIsDefined(F: I.getFunction(),
703 AS: RHS->getType()->getPointerAddressSpace())) {
704 // For most address spaces, an allocation can't be placed at null, but null
705 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
706 // the only valid inbounds address derived from null, is null itself.
707 // Thus, we have four cases to consider:
708 // 1) Base == nullptr, Offset == 0 -> inbounds, null
709 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
710 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
711 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
712 //
713 // (Note if we're indexing a type of size 0, that simply collapses into one
714 // of the buckets above.)
715 //
716 // In general, we're allowed to make values less poison (i.e. remove
717 // sources of full UB), so in this case, we just select between the two
718 // non-poison cases (1 and 4 above).
719 //
720 // For vectors, we apply the same reasoning on a per-lane basis.
721 auto *Base = GEPLHS->getPointerOperand();
722 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
723 auto EC = cast<VectorType>(Val: GEPLHS->getType())->getElementCount();
724 Base = Builder.CreateVectorSplat(EC, V: Base);
725 }
726 return new ICmpInst(Cond, Base,
727 ConstantExpr::getPointerBitCastOrAddrSpaceCast(
728 C: cast<Constant>(Val: RHS), Ty: Base->getType()));
729 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(Val: RHS)) {
730 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags() & GEPRHS->getNoWrapFlags();
731
732 // If the base pointers are different, but the indices are the same, just
733 // compare the base pointer.
734 if (GEPLHS->getOperand(i_nocapture: 0) != GEPRHS->getOperand(i_nocapture: 0)) {
735 bool IndicesTheSame =
736 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
737 GEPLHS->getPointerOperand()->getType() ==
738 GEPRHS->getPointerOperand()->getType() &&
739 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
740 if (IndicesTheSame)
741 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
742 if (GEPLHS->getOperand(i_nocapture: i) != GEPRHS->getOperand(i_nocapture: i)) {
743 IndicesTheSame = false;
744 break;
745 }
746
747 // If all indices are the same, just compare the base pointers.
748 Type *BaseType = GEPLHS->getOperand(i_nocapture: 0)->getType();
749 if (IndicesTheSame &&
750 CmpInst::makeCmpResultType(opnd_type: BaseType) == I.getType() && CanFold(NW))
751 return new ICmpInst(Cond, GEPLHS->getOperand(i_nocapture: 0), GEPRHS->getOperand(i_nocapture: 0));
752
753 // If we're comparing GEPs with two base pointers that only differ in type
754 // and both GEPs have only constant indices or just one use, then fold
755 // the compare with the adjusted indices.
756 // FIXME: Support vector of pointers.
757 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
758 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
759 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
760 GEPLHS->getOperand(i_nocapture: 0)->stripPointerCasts() ==
761 GEPRHS->getOperand(i_nocapture: 0)->stripPointerCasts() &&
762 !GEPLHS->getType()->isVectorTy()) {
763 Value *LOffset = EmitGEPOffset(GEP: GEPLHS);
764 Value *ROffset = EmitGEPOffset(GEP: GEPRHS);
765
766 // If we looked through an addrspacecast between different sized address
767 // spaces, the LHS and RHS pointers are different sized
768 // integers. Truncate to the smaller one.
769 Type *LHSIndexTy = LOffset->getType();
770 Type *RHSIndexTy = ROffset->getType();
771 if (LHSIndexTy != RHSIndexTy) {
772 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
773 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
774 ROffset = Builder.CreateTrunc(V: ROffset, DestTy: LHSIndexTy);
775 } else
776 LOffset = Builder.CreateTrunc(V: LOffset, DestTy: RHSIndexTy);
777 }
778
779 Value *Cmp = Builder.CreateICmp(P: ICmpInst::getSignedPredicate(Pred: Cond),
780 LHS: LOffset, RHS: ROffset);
781 return replaceInstUsesWith(I, V: Cmp);
782 }
783 }
784
785 if (GEPLHS->getOperand(i_nocapture: 0) == GEPRHS->getOperand(i_nocapture: 0) &&
786 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
787 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
788 // If the GEPs only differ by one index, compare it.
789 unsigned NumDifferences = 0; // Keep track of # differences.
790 unsigned DiffOperand = 0; // The operand that differs.
791 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
792 if (GEPLHS->getOperand(i_nocapture: i) != GEPRHS->getOperand(i_nocapture: i)) {
793 Type *LHSType = GEPLHS->getOperand(i_nocapture: i)->getType();
794 Type *RHSType = GEPRHS->getOperand(i_nocapture: i)->getType();
795 // FIXME: Better support for vector of pointers.
796 if (LHSType->getPrimitiveSizeInBits() !=
797 RHSType->getPrimitiveSizeInBits() ||
798 (GEPLHS->getType()->isVectorTy() &&
799 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
800 // Irreconcilable differences.
801 NumDifferences = 2;
802 break;
803 }
804
805 if (NumDifferences++)
806 break;
807 DiffOperand = i;
808 }
809
810 if (NumDifferences == 0) // SAME GEP?
811 return replaceInstUsesWith(
812 I, // No comparison is needed here.
813 V: ConstantInt::get(Ty: I.getType(), V: ICmpInst::isTrueWhenEqual(predicate: Cond)));
814 // If two GEPs only differ by an index, compare them.
815 // Note that nowrap flags are always needed when comparing two indices.
816 else if (NumDifferences == 1 && NW != GEPNoWrapFlags::none()) {
817 Value *LHSV = GEPLHS->getOperand(i_nocapture: DiffOperand);
818 Value *RHSV = GEPRHS->getOperand(i_nocapture: DiffOperand);
819 return NewICmp(NW, LHSV, RHSV);
820 }
821 }
822
823 if (Base.Ptr && !Base.isExpensive()) {
824 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
825 bool DoFold = CanFold(Base.LHSNW & Base.RHSNW);
826
827 if (!DoFold && Base.Ptr->getType()->isPointerTy()) {
828 // Without the flags, we can still fold if the offsets are constant and
829 // they cross the base's alignment boundary the same number of times, so
830 // either both arguments will wrap, or none of them will.
831 unsigned BW = DL.getIndexTypeSizeInBits(Ty: GEPLHS->getType());
832 APInt Alignment = APInt(BW, Base.Ptr->getPointerAlignment(DL).value());
833 APInt LOff(BW, 0);
834 APInt ROff(BW, 0);
835 if (GEPLHS->stripAndAccumulateConstantOffsets(
836 DL, Offset&: LOff, /*AllowNonInbounds=*/true) == Base.Ptr &&
837 RHS->stripAndAccumulateConstantOffsets(
838 DL, Offset&: ROff, /*AllowNonInbounds=*/true) == Base.Ptr)
839 DoFold =
840 APIntOps::RoundingSDiv(A: LOff, B: Alignment, RM: APInt::Rounding::DOWN) ==
841 APIntOps::RoundingSDiv(A: ROff, B: Alignment, RM: APInt::Rounding::DOWN);
842 }
843
844 if (DoFold) {
845 Type *IdxTy = DL.getIndexType(PtrTy: GEPLHS->getType());
846 Value *L = EmitGEPOffsets(GEPs: Base.LHSGEPs, NW: Base.LHSNW, IdxTy,
847 /*RewriteGEP=*/RewriteGEPs: true);
848 Value *R = EmitGEPOffsets(GEPs: Base.RHSGEPs, NW: Base.RHSNW, IdxTy,
849 /*RewriteGEP=*/RewriteGEPs: true);
850 return NewICmp(Base.LHSNW & Base.RHSNW, L, R);
851 }
852 }
853 }
854
855 // Try convert this to an indexed compare by looking through PHIs/casts as a
856 // last resort.
857 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, IC&: *this);
858}
859
860bool InstCombinerImpl::foldAllocaCmp(AllocaInst *Alloca) {
861 // It would be tempting to fold away comparisons between allocas and any
862 // pointer not based on that alloca (e.g. an argument). However, even
863 // though such pointers cannot alias, they can still compare equal.
864 //
865 // But LLVM doesn't specify where allocas get their memory, so if the alloca
866 // doesn't escape we can argue that it's impossible to guess its value, and we
867 // can therefore act as if any such guesses are wrong.
868 //
869 // However, we need to ensure that this folding is consistent: We can't fold
870 // one comparison to false, and then leave a different comparison against the
871 // same value alone (as it might evaluate to true at runtime, leading to a
872 // contradiction). As such, this code ensures that all comparisons are folded
873 // at the same time, and there are no other escapes.
874
875 struct CmpCaptureTracker : public CaptureTracker {
876 AllocaInst *Alloca;
877 bool Captured = false;
878 /// The value of the map is a bit mask of which icmp operands the alloca is
879 /// used in.
880 SmallMapVector<ICmpInst *, unsigned, 4> ICmps;
881
882 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
883
884 void tooManyUses() override { Captured = true; }
885
886 Action captured(const Use *U, UseCaptureInfo CI) override {
887 // TODO(captures): Use UseCaptureInfo.
888 auto *ICmp = dyn_cast<ICmpInst>(Val: U->getUser());
889 // We need to check that U is based *only* on the alloca, and doesn't
890 // have other contributions from a select/phi operand.
891 // TODO: We could check whether getUnderlyingObjects() reduces to one
892 // object, which would allow looking through phi nodes.
893 if (ICmp && ICmp->isEquality() && getUnderlyingObject(V: *U) == Alloca) {
894 // Collect equality icmps of the alloca, and don't treat them as
895 // captures.
896 ICmps[ICmp] |= 1u << U->getOperandNo();
897 return Continue;
898 }
899
900 Captured = true;
901 return Stop;
902 }
903 };
904
905 CmpCaptureTracker Tracker(Alloca);
906 PointerMayBeCaptured(V: Alloca, Tracker: &Tracker);
907 if (Tracker.Captured)
908 return false;
909
910 bool Changed = false;
911 for (auto [ICmp, Operands] : Tracker.ICmps) {
912 switch (Operands) {
913 case 1:
914 case 2: {
915 // The alloca is only used in one icmp operand. Assume that the
916 // equality is false.
917 auto *Res = ConstantInt::get(Ty: ICmp->getType(),
918 V: ICmp->getPredicate() == ICmpInst::ICMP_NE);
919 replaceInstUsesWith(I&: *ICmp, V: Res);
920 eraseInstFromFunction(I&: *ICmp);
921 Changed = true;
922 break;
923 }
924 case 3:
925 // Both icmp operands are based on the alloca, so this is comparing
926 // pointer offsets, without leaking any information about the address
927 // of the alloca. Ignore such comparisons.
928 break;
929 default:
930 llvm_unreachable("Cannot happen");
931 }
932 }
933
934 return Changed;
935}
936
937/// Fold "icmp pred (X+C), X".
938Instruction *InstCombinerImpl::foldICmpAddOpConst(Value *X, const APInt &C,
939 CmpPredicate Pred) {
940 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
941 // so the values can never be equal. Similarly for all other "or equals"
942 // operators.
943 assert(!!C && "C should not be zero!");
944
945 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
946 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
947 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
948 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
949 Constant *R =
950 ConstantInt::get(Ty: X->getType(), V: APInt::getMaxValue(numBits: C.getBitWidth()) - C);
951 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
952 }
953
954 // (X+1) >u X --> X <u (0-1) --> X != 255
955 // (X+2) >u X --> X <u (0-2) --> X <u 254
956 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
957 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
958 return new ICmpInst(ICmpInst::ICMP_ULT, X,
959 ConstantInt::get(Ty: X->getType(), V: -C));
960
961 APInt SMax = APInt::getSignedMaxValue(numBits: C.getBitWidth());
962
963 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
964 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
965 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
966 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
967 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
968 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
969 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
970 return new ICmpInst(ICmpInst::ICMP_SGT, X,
971 ConstantInt::get(Ty: X->getType(), V: SMax - C));
972
973 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
974 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
975 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
976 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
977 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
978 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
979
980 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
981 return new ICmpInst(ICmpInst::ICMP_SLT, X,
982 ConstantInt::get(Ty: X->getType(), V: SMax - (C - 1)));
983}
984
985/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
986/// (icmp eq/ne A, Log2(AP2/AP1)) ->
987/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
988Instruction *InstCombinerImpl::foldICmpShrConstConst(ICmpInst &I, Value *A,
989 const APInt &AP1,
990 const APInt &AP2) {
991 assert(I.isEquality() && "Cannot fold icmp gt/lt");
992
993 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
994 if (I.getPredicate() == I.ICMP_NE)
995 Pred = CmpInst::getInversePredicate(pred: Pred);
996 return new ICmpInst(Pred, LHS, RHS);
997 };
998
999 // Don't bother doing any work for cases which InstSimplify handles.
1000 if (AP2.isZero())
1001 return nullptr;
1002
1003 bool IsAShr = isa<AShrOperator>(Val: I.getOperand(i_nocapture: 0));
1004 if (IsAShr) {
1005 if (AP2.isAllOnes())
1006 return nullptr;
1007 if (AP2.isNegative() != AP1.isNegative())
1008 return nullptr;
1009 if (AP2.sgt(RHS: AP1))
1010 return nullptr;
1011 }
1012
1013 if (!AP1)
1014 // 'A' must be large enough to shift out the highest set bit.
1015 return getICmp(I.ICMP_UGT, A,
1016 ConstantInt::get(Ty: A->getType(), V: AP2.logBase2()));
1017
1018 if (AP1 == AP2)
1019 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(Ty: A->getType()));
1020
1021 int Shift;
1022 if (IsAShr && AP1.isNegative())
1023 Shift = AP1.countl_one() - AP2.countl_one();
1024 else
1025 Shift = AP1.countl_zero() - AP2.countl_zero();
1026
1027 if (Shift > 0) {
1028 if (IsAShr && AP1 == AP2.ashr(ShiftAmt: Shift)) {
1029 // There are multiple solutions if we are comparing against -1 and the LHS
1030 // of the ashr is not a power of two.
1031 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1032 return getICmp(I.ICMP_UGE, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1033 return getICmp(I.ICMP_EQ, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1034 } else if (AP1 == AP2.lshr(shiftAmt: Shift)) {
1035 return getICmp(I.ICMP_EQ, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1036 }
1037 }
1038
1039 // Shifting const2 will never be equal to const1.
1040 // FIXME: This should always be handled by InstSimplify?
1041 auto *TorF = ConstantInt::get(Ty: I.getType(), V: I.getPredicate() == I.ICMP_NE);
1042 return replaceInstUsesWith(I, V: TorF);
1043}
1044
1045/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1046/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1047Instruction *InstCombinerImpl::foldICmpShlConstConst(ICmpInst &I, Value *A,
1048 const APInt &AP1,
1049 const APInt &AP2) {
1050 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1051
1052 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1053 if (I.getPredicate() == I.ICMP_NE)
1054 Pred = CmpInst::getInversePredicate(pred: Pred);
1055 return new ICmpInst(Pred, LHS, RHS);
1056 };
1057
1058 // Don't bother doing any work for cases which InstSimplify handles.
1059 if (AP2.isZero())
1060 return nullptr;
1061
1062 unsigned AP2TrailingZeros = AP2.countr_zero();
1063
1064 if (!AP1 && AP2TrailingZeros != 0)
1065 return getICmp(
1066 I.ICMP_UGE, A,
1067 ConstantInt::get(Ty: A->getType(), V: AP2.getBitWidth() - AP2TrailingZeros));
1068
1069 if (AP1 == AP2)
1070 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(Ty: A->getType()));
1071
1072 // Get the distance between the lowest bits that are set.
1073 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1074
1075 if (Shift > 0 && AP2.shl(shiftAmt: Shift) == AP1)
1076 return getICmp(I.ICMP_EQ, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1077
1078 // Shifting const2 will never be equal to const1.
1079 // FIXME: This should always be handled by InstSimplify?
1080 auto *TorF = ConstantInt::get(Ty: I.getType(), V: I.getPredicate() == I.ICMP_NE);
1081 return replaceInstUsesWith(I, V: TorF);
1082}
1083
1084/// The caller has matched a pattern of the form:
1085/// I = icmp ugt (add (add A, B), CI2), CI1
1086/// If this is of the form:
1087/// sum = a + b
1088/// if (sum+128 >u 255)
1089/// Then replace it with llvm.sadd.with.overflow.i8.
1090///
1091static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1092 ConstantInt *CI2, ConstantInt *CI1,
1093 InstCombinerImpl &IC) {
1094 // The transformation we're trying to do here is to transform this into an
1095 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1096 // with a narrower add, and discard the add-with-constant that is part of the
1097 // range check (if we can't eliminate it, this isn't profitable).
1098
1099 // In order to eliminate the add-with-constant, the compare can be its only
1100 // use.
1101 Instruction *AddWithCst = cast<Instruction>(Val: I.getOperand(i_nocapture: 0));
1102 if (!AddWithCst->hasOneUse())
1103 return nullptr;
1104
1105 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1106 if (!CI2->getValue().isPowerOf2())
1107 return nullptr;
1108 unsigned NewWidth = CI2->getValue().countr_zero();
1109 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1110 return nullptr;
1111
1112 // The width of the new add formed is 1 more than the bias.
1113 ++NewWidth;
1114
1115 // Check to see that CI1 is an all-ones value with NewWidth bits.
1116 if (CI1->getBitWidth() == NewWidth ||
1117 CI1->getValue() != APInt::getLowBitsSet(numBits: CI1->getBitWidth(), loBitsSet: NewWidth))
1118 return nullptr;
1119
1120 // This is only really a signed overflow check if the inputs have been
1121 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1122 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1123 if (IC.ComputeMaxSignificantBits(Op: A, CxtI: &I) > NewWidth ||
1124 IC.ComputeMaxSignificantBits(Op: B, CxtI: &I) > NewWidth)
1125 return nullptr;
1126
1127 // In order to replace the original add with a narrower
1128 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1129 // and truncates that discard the high bits of the add. Verify that this is
1130 // the case.
1131 Instruction *OrigAdd = cast<Instruction>(Val: AddWithCst->getOperand(i: 0));
1132 for (User *U : OrigAdd->users()) {
1133 if (U == AddWithCst)
1134 continue;
1135
1136 // Only accept truncates for now. We would really like a nice recursive
1137 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1138 // chain to see which bits of a value are actually demanded. If the
1139 // original add had another add which was then immediately truncated, we
1140 // could still do the transformation.
1141 TruncInst *TI = dyn_cast<TruncInst>(Val: U);
1142 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1143 return nullptr;
1144 }
1145
1146 // If the pattern matches, truncate the inputs to the narrower type and
1147 // use the sadd_with_overflow intrinsic to efficiently compute both the
1148 // result and the overflow bit.
1149 Type *NewType = IntegerType::get(C&: OrigAdd->getContext(), NumBits: NewWidth);
1150 Function *F = Intrinsic::getOrInsertDeclaration(
1151 M: I.getModule(), id: Intrinsic::sadd_with_overflow, OverloadTys: NewType);
1152
1153 InstCombiner::BuilderTy &Builder = IC.Builder;
1154
1155 // Put the new code above the original add, in case there are any uses of the
1156 // add between the add and the compare.
1157 Builder.SetInsertPoint(OrigAdd);
1158
1159 Value *TruncA = Builder.CreateTrunc(V: A, DestTy: NewType, Name: A->getName() + ".trunc");
1160 Value *TruncB = Builder.CreateTrunc(V: B, DestTy: NewType, Name: B->getName() + ".trunc");
1161 CallInst *Call = Builder.CreateCall(Callee: F, Args: {TruncA, TruncB}, Name: "sadd");
1162 Value *Add = Builder.CreateExtractValue(Agg: Call, Idxs: 0, Name: "sadd.result");
1163 Value *ZExt = Builder.CreateZExt(V: Add, DestTy: OrigAdd->getType());
1164
1165 // The inner add was the result of the narrow add, zero extended to the
1166 // wider type. Replace it with the result computed by the intrinsic.
1167 IC.replaceInstUsesWith(I&: *OrigAdd, V: ZExt);
1168 IC.eraseInstFromFunction(I&: *OrigAdd);
1169
1170 // The original icmp gets replaced with the overflow value.
1171 return ExtractValueInst::Create(Agg: Call, Idxs: 1, NameStr: "sadd.overflow");
1172}
1173
1174/// If we have:
1175/// icmp eq/ne (urem/srem %x, %y), 0
1176/// iff %y is a power-of-two, we can replace this with a bit test:
1177/// icmp eq/ne (and %x, (add %y, -1)), 0
1178Instruction *InstCombinerImpl::foldIRemByPowerOfTwoToBitTest(ICmpInst &I) {
1179 // This fold is only valid for equality predicates.
1180 if (!I.isEquality())
1181 return nullptr;
1182 CmpPredicate Pred;
1183 Value *X, *Y, *Zero;
1184 if (!match(V: &I, P: m_ICmp(Pred, L: m_OneUse(SubPattern: m_IRem(L: m_Value(V&: X), R: m_Value(V&: Y))),
1185 R: m_CombineAnd(Ps: m_Zero(), Ps: m_Value(V&: Zero)))))
1186 return nullptr;
1187 if (!isKnownToBeAPowerOfTwo(V: Y, /*OrZero*/ true, CxtI: &I))
1188 return nullptr;
1189 // This may increase instruction count, we don't enforce that Y is a constant.
1190 Value *Mask = Builder.CreateAdd(LHS: Y, RHS: Constant::getAllOnesValue(Ty: Y->getType()));
1191 Value *Masked = Builder.CreateAnd(LHS: X, RHS: Mask);
1192 return ICmpInst::Create(Op: Instruction::ICmp, Pred, S1: Masked, S2: Zero);
1193}
1194
1195/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1196/// by one-less-than-bitwidth into a sign test on the original value.
1197Instruction *InstCombinerImpl::foldSignBitTest(ICmpInst &I) {
1198 Instruction *Val;
1199 CmpPredicate Pred;
1200 if (!I.isEquality() || !match(V: &I, P: m_ICmp(Pred, L: m_Instruction(I&: Val), R: m_Zero())))
1201 return nullptr;
1202
1203 Value *X;
1204 Type *XTy;
1205
1206 Constant *C;
1207 if (match(V: Val, P: m_TruncOrSelf(Op: m_Shr(L: m_Value(V&: X), R: m_Constant(C))))) {
1208 XTy = X->getType();
1209 unsigned XBitWidth = XTy->getScalarSizeInBits();
1210 if (!match(V: C, P: m_SpecificInt_ICMP(Predicate: ICmpInst::Predicate::ICMP_EQ,
1211 Threshold: APInt(XBitWidth, XBitWidth - 1))))
1212 return nullptr;
1213 } else if (isa<BinaryOperator>(Val) &&
1214 (X = reassociateShiftAmtsOfTwoSameDirectionShifts(
1215 Sh0: cast<BinaryOperator>(Val), SQ: SQ.getWithInstruction(I: Val),
1216 /*AnalyzeForSignBitExtraction=*/true))) {
1217 XTy = X->getType();
1218 } else
1219 return nullptr;
1220
1221 return ICmpInst::Create(Op: Instruction::ICmp,
1222 Pred: Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SGE
1223 : ICmpInst::ICMP_SLT,
1224 S1: X, S2: ConstantInt::getNullValue(Ty: XTy));
1225}
1226
1227// Handle icmp pred X, 0
1228Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) {
1229 CmpInst::Predicate Pred = Cmp.getPredicate();
1230 if (!match(V: Cmp.getOperand(i_nocapture: 1), P: m_Zero()))
1231 return nullptr;
1232
1233 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1234 if (Pred == ICmpInst::ICMP_SGT) {
1235 Value *A, *B;
1236 if (match(V: Cmp.getOperand(i_nocapture: 0), P: m_SMin(Op0: m_Value(V&: A), Op1: m_Value(V&: B)))) {
1237 if (isKnownPositive(V: A, SQ: SQ.getWithInstruction(I: &Cmp)))
1238 return new ICmpInst(Pred, B, Cmp.getOperand(i_nocapture: 1));
1239 if (isKnownPositive(V: B, SQ: SQ.getWithInstruction(I: &Cmp)))
1240 return new ICmpInst(Pred, A, Cmp.getOperand(i_nocapture: 1));
1241 }
1242 }
1243
1244 if (Instruction *New = foldIRemByPowerOfTwoToBitTest(I&: Cmp))
1245 return New;
1246
1247 // Given:
1248 // icmp eq/ne (urem %x, %y), 0
1249 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1250 // icmp eq/ne %x, 0
1251 Value *X, *Y;
1252 if (match(V: Cmp.getOperand(i_nocapture: 0), P: m_URem(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
1253 ICmpInst::isEquality(P: Pred)) {
1254 KnownBits XKnown = computeKnownBits(V: X, CxtI: &Cmp);
1255 KnownBits YKnown = computeKnownBits(V: Y, CxtI: &Cmp);
1256 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1257 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
1258 }
1259
1260 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1261 // odd/non-zero/there is no overflow.
1262 if (match(V: Cmp.getOperand(i_nocapture: 0), P: m_Mul(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
1263 ICmpInst::isEquality(P: Pred)) {
1264
1265 KnownBits XKnown = computeKnownBits(V: X, CxtI: &Cmp);
1266 // if X % 2 != 0
1267 // (icmp eq/ne Y)
1268 if (XKnown.countMaxTrailingZeros() == 0)
1269 return new ICmpInst(Pred, Y, Cmp.getOperand(i_nocapture: 1));
1270
1271 KnownBits YKnown = computeKnownBits(V: Y, CxtI: &Cmp);
1272 // if Y % 2 != 0
1273 // (icmp eq/ne X)
1274 if (YKnown.countMaxTrailingZeros() == 0)
1275 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
1276
1277 auto *BO0 = cast<OverflowingBinaryOperator>(Val: Cmp.getOperand(i_nocapture: 0));
1278 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1279 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
1280 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1281 // but to avoid unnecessary work, first just if this is an obvious case.
1282
1283 // if X non-zero and NoOverflow(X * Y)
1284 // (icmp eq/ne Y)
1285 if (!XKnown.One.isZero() || isKnownNonZero(V: X, Q))
1286 return new ICmpInst(Pred, Y, Cmp.getOperand(i_nocapture: 1));
1287
1288 // if Y non-zero and NoOverflow(X * Y)
1289 // (icmp eq/ne X)
1290 if (!YKnown.One.isZero() || isKnownNonZero(V: Y, Q))
1291 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
1292 }
1293 // Note, we are skipping cases:
1294 // if Y % 2 != 0 AND X % 2 != 0
1295 // (false/true)
1296 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1297 // (false/true)
1298 // Those can be simplified later as we would have already replaced the (icmp
1299 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1300 // will fold to a constant elsewhere.
1301 }
1302
1303 // (icmp eq/ne f(X), 0) -> (icmp eq/ne X, 0)
1304 // where f(X) == 0 if and only if X == 0
1305 if (ICmpInst::isEquality(P: Pred))
1306 if (Value *Stripped = stripNullTest(V: Cmp.getOperand(i_nocapture: 0)))
1307 return new ICmpInst(Pred, Stripped,
1308 Constant::getNullValue(Ty: Stripped->getType()));
1309
1310 return nullptr;
1311}
1312
1313/// Fold icmp eq (num + mask) & ~mask, num
1314/// to
1315/// icmp eq (and num, mask), 0
1316/// Where mask is a low bit mask.
1317Instruction *InstCombinerImpl::foldIsMultipleOfAPowerOfTwo(ICmpInst &Cmp) {
1318 Value *Num;
1319 CmpPredicate Pred;
1320 const APInt *Mask, *Neg;
1321
1322 if (!match(V: &Cmp,
1323 P: m_c_ICmp(Pred, L: m_Value(V&: Num),
1324 R: m_OneUse(SubPattern: m_c_And(L: m_OneUse(SubPattern: m_c_Add(L: m_Deferred(V: Num),
1325 R: m_LowBitMask(V&: Mask))),
1326 R: m_APInt(Res&: Neg))))))
1327 return nullptr;
1328
1329 if (*Neg != ~*Mask)
1330 return nullptr;
1331
1332 if (!ICmpInst::isEquality(P: Pred))
1333 return nullptr;
1334
1335 // Create new icmp eq (num & mask), 0
1336 auto *NewAnd = Builder.CreateAnd(LHS: Num, RHS: *Mask);
1337 auto *Zero = Constant::getNullValue(Ty: Num->getType());
1338
1339 return new ICmpInst(Pred, NewAnd, Zero);
1340}
1341
1342/// Fold icmp Pred X, C.
1343/// TODO: This code structure does not make sense. The saturating add fold
1344/// should be moved to some other helper and extended as noted below (it is also
1345/// possible that code has been made unnecessary - do we canonicalize IR to
1346/// overflow/saturating intrinsics or not?).
1347Instruction *InstCombinerImpl::foldICmpWithConstant(ICmpInst &Cmp) {
1348 // Match the following pattern, which is a common idiom when writing
1349 // overflow-safe integer arithmetic functions. The source performs an addition
1350 // in wider type and explicitly checks for overflow using comparisons against
1351 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1352 //
1353 // TODO: This could probably be generalized to handle other overflow-safe
1354 // operations if we worked out the formulas to compute the appropriate magic
1355 // constants.
1356 //
1357 // sum = a + b
1358 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1359 CmpInst::Predicate Pred = Cmp.getPredicate();
1360 Value *Op0 = Cmp.getOperand(i_nocapture: 0), *Op1 = Cmp.getOperand(i_nocapture: 1);
1361 Value *A, *B;
1362 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1363 if (Pred == ICmpInst::ICMP_UGT && match(V: Op1, P: m_ConstantInt(CI)) &&
1364 match(V: Op0, P: m_Add(L: m_Add(L: m_Value(V&: A), R: m_Value(V&: B)), R: m_ConstantInt(CI&: CI2))))
1365 if (Instruction *Res = processUGT_ADDCST_ADD(I&: Cmp, A, B, CI2, CI1: CI, IC&: *this))
1366 return Res;
1367
1368 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1369 Constant *C = dyn_cast<Constant>(Val: Op1);
1370 if (!C)
1371 return nullptr;
1372
1373 if (auto *Phi = dyn_cast<PHINode>(Val: Op0))
1374 if (all_of(Range: Phi->operands(), P: IsaPred<Constant>)) {
1375 SmallVector<Constant *> Ops;
1376 for (Value *V : Phi->incoming_values()) {
1377 Constant *Res =
1378 ConstantFoldCompareInstOperands(Predicate: Pred, LHS: cast<Constant>(Val: V), RHS: C, DL);
1379 if (!Res)
1380 return nullptr;
1381 Ops.push_back(Elt: Res);
1382 }
1383 Builder.SetInsertPoint(Phi);
1384 PHINode *NewPhi = Builder.CreatePHI(Ty: Cmp.getType(), NumReservedValues: Phi->getNumOperands());
1385 for (auto [V, Pred] : zip(t&: Ops, u: Phi->blocks()))
1386 NewPhi->addIncoming(V, BB: Pred);
1387 return replaceInstUsesWith(I&: Cmp, V: NewPhi);
1388 }
1389
1390 if (Instruction *R = tryFoldInstWithCtpopWithNot(I: &Cmp))
1391 return R;
1392
1393 return nullptr;
1394}
1395
1396/// Canonicalize icmp instructions based on dominating conditions.
1397Instruction *InstCombinerImpl::foldICmpWithDominatingICmp(ICmpInst &Cmp) {
1398 // We already checked simple implication in InstSimplify, only handle complex
1399 // cases here.
1400 Value *X = Cmp.getOperand(i_nocapture: 0), *Y = Cmp.getOperand(i_nocapture: 1);
1401 const APInt *C;
1402 if (!match(V: Y, P: m_APInt(Res&: C)))
1403 return nullptr;
1404
1405 CmpInst::Predicate Pred = Cmp.getPredicate();
1406 ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, Other: *C);
1407
1408 auto handleDomCond = [&](ICmpInst::Predicate DomPred,
1409 const APInt *DomC) -> Instruction * {
1410 // We have 2 compares of a variable with constants. Calculate the constant
1411 // ranges of those compares to see if we can transform the 2nd compare:
1412 // DomBB:
1413 // DomCond = icmp DomPred X, DomC
1414 // br DomCond, CmpBB, FalseBB
1415 // CmpBB:
1416 // Cmp = icmp Pred X, C
1417 ConstantRange DominatingCR =
1418 ConstantRange::makeExactICmpRegion(Pred: DomPred, Other: *DomC);
1419 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1420 ConstantRange Difference = DominatingCR.difference(CR);
1421 if (Intersection.isEmptySet())
1422 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
1423 if (Difference.isEmptySet())
1424 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
1425
1426 // Canonicalizing a sign bit comparison that gets used in a branch,
1427 // pessimizes codegen by generating branch on zero instruction instead
1428 // of a test and branch. So we avoid canonicalizing in such situations
1429 // because test and branch instruction has better branch displacement
1430 // than compare and branch instruction.
1431 bool UnusedBit;
1432 bool IsSignBit = isSignBitCheck(Pred, RHS: *C, TrueIfSigned&: UnusedBit);
1433 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(I&: Cmp)))
1434 return nullptr;
1435
1436 // Avoid an infinite loop with min/max canonicalization.
1437 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1438 if (Cmp.hasOneUse() &&
1439 match(V: Cmp.user_back(), P: m_MaxOrMin(Op0: m_Value(), Op1: m_Value())))
1440 return nullptr;
1441
1442 if (const APInt *EqC = Intersection.getSingleElement())
1443 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(AI: *EqC));
1444 if (const APInt *NeC = Difference.getSingleElement())
1445 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(AI: *NeC));
1446 return nullptr;
1447 };
1448
1449 for (CondBrInst *BI : DC.conditionsFor(V: X)) {
1450 CmpPredicate DomPred;
1451 const APInt *DomC;
1452 if (!match(V: BI->getCondition(),
1453 P: m_ICmp(Pred&: DomPred, L: m_Specific(V: X), R: m_APInt(Res&: DomC))))
1454 continue;
1455
1456 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(i: 0));
1457 if (DT.dominates(BBE: Edge0, BB: Cmp.getParent())) {
1458 if (auto *V = handleDomCond(DomPred, DomC))
1459 return V;
1460 } else {
1461 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(i: 1));
1462 if (DT.dominates(BBE: Edge1, BB: Cmp.getParent()))
1463 if (auto *V =
1464 handleDomCond(CmpInst::getInversePredicate(pred: DomPred), DomC))
1465 return V;
1466 }
1467 }
1468
1469 return nullptr;
1470}
1471
1472/// Fold icmp (trunc X), C.
1473Instruction *InstCombinerImpl::foldICmpTruncConstant(ICmpInst &Cmp,
1474 TruncInst *Trunc,
1475 const APInt &C) {
1476 ICmpInst::Predicate Pred = Cmp.getPredicate();
1477 Value *X = Trunc->getOperand(i_nocapture: 0);
1478 Type *SrcTy = X->getType();
1479 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1480 SrcBits = SrcTy->getScalarSizeInBits();
1481
1482 // Match (icmp pred (trunc nuw/nsw X), C)
1483 // Which we can convert to (icmp pred X, (sext/zext C))
1484 if (shouldChangeType(From: Trunc->getType(), To: SrcTy)) {
1485 if (Trunc->hasNoSignedWrap())
1486 return new ICmpInst(Pred, X, ConstantInt::get(Ty: SrcTy, V: C.sext(width: SrcBits)));
1487 if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())
1488 return new ICmpInst(Pred, X, ConstantInt::get(Ty: SrcTy, V: C.zext(width: SrcBits)));
1489 }
1490
1491 if (C.isOne() && C.getBitWidth() > 1) {
1492 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1493 Value *V = nullptr;
1494 if (Pred == ICmpInst::ICMP_SLT && match(V: X, P: m_Signum(V: m_Value(V))))
1495 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1496 ConstantInt::get(Ty: V->getType(), V: 1));
1497 }
1498
1499 // TODO: Handle non-equality predicates.
1500 Value *Y;
1501 const APInt *Pow2;
1502 if (Cmp.isEquality() && match(V: X, P: m_Shl(L: m_Power2(V&: Pow2), R: m_Value(V&: Y))) &&
1503 DstBits > Pow2->logBase2()) {
1504 // (trunc (Pow2 << Y) to iN) == 0 --> Y u>= N - log2(Pow2)
1505 // (trunc (Pow2 << Y) to iN) != 0 --> Y u< N - log2(Pow2)
1506 // iff N > log2(Pow2)
1507 if (C.isZero()) {
1508 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1509 return new ICmpInst(NewPred, Y,
1510 ConstantInt::get(Ty: SrcTy, V: DstBits - Pow2->logBase2()));
1511 }
1512 // (trunc (Pow2 << Y) to iN) == 2**C --> Y == C - log2(Pow2)
1513 // (trunc (Pow2 << Y) to iN) != 2**C --> Y != C - log2(Pow2)
1514 if (C.isPowerOf2())
1515 return new ICmpInst(
1516 Pred, Y, ConstantInt::get(Ty: SrcTy, V: C.logBase2() - Pow2->logBase2()));
1517 }
1518
1519 if (Cmp.isEquality() && (Trunc->hasOneUse() || Trunc->hasNoUnsignedWrap())) {
1520 // Canonicalize to a mask and wider compare if the wide type is suitable:
1521 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1522 if (!SrcTy->isVectorTy() && shouldChangeType(FromBitWidth: DstBits, ToBitWidth: SrcBits)) {
1523 Constant *Mask =
1524 ConstantInt::get(Ty: SrcTy, V: APInt::getLowBitsSet(numBits: SrcBits, loBitsSet: DstBits));
1525 Value *And = Trunc->hasNoUnsignedWrap() ? X : Builder.CreateAnd(LHS: X, RHS: Mask);
1526 Constant *WideC = ConstantInt::get(Ty: SrcTy, V: C.zext(width: SrcBits));
1527 return new ICmpInst(Pred, And, WideC);
1528 }
1529
1530 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1531 // of the high bits truncated out of x are known.
1532 KnownBits Known = computeKnownBits(V: X, CxtI: &Cmp);
1533
1534 // If all the high bits are known, we can do this xform.
1535 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1536 // Pull in the high bits from known-ones set.
1537 APInt NewRHS = C.zext(width: SrcBits);
1538 NewRHS |= Known.One & APInt::getHighBitsSet(numBits: SrcBits, hiBitsSet: SrcBits - DstBits);
1539 return new ICmpInst(Pred, X, ConstantInt::get(Ty: SrcTy, V: NewRHS));
1540 }
1541 }
1542
1543 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1544 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1545 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1546 Value *ShOp;
1547 uint64_t ShAmt;
1548 bool TrueIfSigned;
1549 if (isSignBitCheck(Pred, RHS: C, TrueIfSigned) &&
1550 match(V: X, P: m_Shr(L: m_Value(V&: ShOp), R: m_ConstantInt(V&: ShAmt))) &&
1551 DstBits == SrcBits - ShAmt) {
1552 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1553 ConstantInt::getNullValue(Ty: SrcTy))
1554 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1555 ConstantInt::getAllOnesValue(Ty: SrcTy));
1556 }
1557
1558 return nullptr;
1559}
1560
1561/// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
1562/// Fold icmp (trunc nuw/nsw X), (zext/sext Y).
1563Instruction *
1564InstCombinerImpl::foldICmpTruncWithTruncOrExt(ICmpInst &Cmp,
1565 const SimplifyQuery &Q) {
1566 Value *X, *Y;
1567 CmpPredicate Pred;
1568 bool YIsSExt = false;
1569 // Try to match icmp (trunc X), (trunc Y)
1570 if (match(V: &Cmp, P: m_ICmp(Pred, L: m_Trunc(Op: m_Value(V&: X)), R: m_Trunc(Op: m_Value(V&: Y))))) {
1571 unsigned NoWrapFlags = cast<TruncInst>(Val: Cmp.getOperand(i_nocapture: 0))->getNoWrapKind() &
1572 cast<TruncInst>(Val: Cmp.getOperand(i_nocapture: 1))->getNoWrapKind();
1573 if (Cmp.isSigned()) {
1574 // For signed comparisons, both truncs must be nsw.
1575 if (!(NoWrapFlags & TruncInst::NoSignedWrap))
1576 return nullptr;
1577 } else {
1578 // For unsigned and equality comparisons, either both must be nuw or
1579 // both must be nsw, we don't care which.
1580 if (!NoWrapFlags)
1581 return nullptr;
1582 }
1583
1584 if (X->getType() != Y->getType() &&
1585 (!Cmp.getOperand(i_nocapture: 0)->hasOneUse() || !Cmp.getOperand(i_nocapture: 1)->hasOneUse()))
1586 return nullptr;
1587 if (!isDesirableIntType(BitWidth: X->getType()->getScalarSizeInBits()) &&
1588 isDesirableIntType(BitWidth: Y->getType()->getScalarSizeInBits())) {
1589 std::swap(a&: X, b&: Y);
1590 Pred = Cmp.getSwappedPredicate(pred: Pred);
1591 }
1592 YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);
1593 }
1594 // Try to match icmp (trunc nuw X), (zext Y)
1595 else if (!Cmp.isSigned() &&
1596 match(V: &Cmp, P: m_c_ICmp(Pred, L: m_NUWTrunc(Op: m_Value(V&: X)),
1597 R: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: Y)))))) {
1598 // Can fold trunc nuw + zext for unsigned and equality predicates.
1599 }
1600 // Try to match icmp (trunc nsw X), (sext Y)
1601 else if (match(V: &Cmp, P: m_c_ICmp(Pred, L: m_NSWTrunc(Op: m_Value(V&: X)),
1602 R: m_OneUse(SubPattern: m_ZExtOrSExt(Op: m_Value(V&: Y)))))) {
1603 // Can fold trunc nsw + zext/sext for all predicates.
1604 YIsSExt =
1605 isa<SExtInst>(Val: Cmp.getOperand(i_nocapture: 0)) || isa<SExtInst>(Val: Cmp.getOperand(i_nocapture: 1));
1606 } else
1607 return nullptr;
1608
1609 Type *TruncTy = Cmp.getOperand(i_nocapture: 0)->getType();
1610 unsigned TruncBits = TruncTy->getScalarSizeInBits();
1611
1612 // If this transform will end up changing from desirable types -> undesirable
1613 // types skip it.
1614 if (isDesirableIntType(BitWidth: TruncBits) &&
1615 !isDesirableIntType(BitWidth: X->getType()->getScalarSizeInBits()))
1616 return nullptr;
1617
1618 Value *NewY = Builder.CreateIntCast(V: Y, DestTy: X->getType(), isSigned: YIsSExt);
1619 return new ICmpInst(Pred, X, NewY);
1620}
1621
1622/// Fold icmp (xor X, Y), C.
1623Instruction *InstCombinerImpl::foldICmpXorConstant(ICmpInst &Cmp,
1624 BinaryOperator *Xor,
1625 const APInt &C) {
1626 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1627 return I;
1628
1629 Value *X = Xor->getOperand(i_nocapture: 0);
1630 Value *Y = Xor->getOperand(i_nocapture: 1);
1631 const APInt *XorC;
1632 if (!match(V: Y, P: m_APInt(Res&: XorC)))
1633 return nullptr;
1634
1635 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1636 // fold the xor.
1637 ICmpInst::Predicate Pred = Cmp.getPredicate();
1638 bool TrueIfSigned = false;
1639 if (isSignBitCheck(Pred: Cmp.getPredicate(), RHS: C, TrueIfSigned)) {
1640
1641 // If the sign bit of the XorCst is not set, there is no change to
1642 // the operation, just stop using the Xor.
1643 if (!XorC->isNegative())
1644 return replaceOperand(I&: Cmp, OpNum: 0, V: X);
1645
1646 // Emit the opposite comparison.
1647 if (TrueIfSigned)
1648 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1649 ConstantInt::getAllOnesValue(Ty: X->getType()));
1650 else
1651 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1652 ConstantInt::getNullValue(Ty: X->getType()));
1653 }
1654
1655 if (Xor->hasOneUse()) {
1656 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1657 if (!Cmp.isEquality() && XorC->isSignMask()) {
1658 Pred = Cmp.getFlippedSignednessPredicate();
1659 return new ICmpInst(Pred, X, ConstantInt::get(Ty: X->getType(), V: C ^ *XorC));
1660 }
1661
1662 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1663 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1664 Pred = Cmp.getFlippedSignednessPredicate();
1665 Pred = Cmp.getSwappedPredicate(pred: Pred);
1666 return new ICmpInst(Pred, X, ConstantInt::get(Ty: X->getType(), V: C ^ *XorC));
1667 }
1668 }
1669
1670 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1671 if (Pred == ICmpInst::ICMP_UGT) {
1672 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1673 if (*XorC == ~C && (C + 1).isPowerOf2())
1674 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1675 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1676 if (*XorC == C && (C + 1).isPowerOf2())
1677 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1678 }
1679 if (Pred == ICmpInst::ICMP_ULT) {
1680 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1681 if (*XorC == -C && C.isPowerOf2())
1682 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1683 ConstantInt::get(Ty: X->getType(), V: ~C));
1684 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1685 if (*XorC == C && (-C).isPowerOf2())
1686 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1687 ConstantInt::get(Ty: X->getType(), V: ~C));
1688 }
1689 return nullptr;
1690}
1691
1692/// For power-of-2 C:
1693/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1694/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1695Instruction *InstCombinerImpl::foldICmpXorShiftConst(ICmpInst &Cmp,
1696 BinaryOperator *Xor,
1697 const APInt &C) {
1698 CmpInst::Predicate Pred = Cmp.getPredicate();
1699 APInt PowerOf2;
1700 if (Pred == ICmpInst::ICMP_ULT)
1701 PowerOf2 = C;
1702 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1703 PowerOf2 = C + 1;
1704 else
1705 return nullptr;
1706 if (!PowerOf2.isPowerOf2())
1707 return nullptr;
1708 Value *X;
1709 const APInt *ShiftC;
1710 if (!match(V: Xor, P: m_OneUse(SubPattern: m_c_Xor(L: m_Value(V&: X),
1711 R: m_AShr(L: m_Deferred(V: X), R: m_APInt(Res&: ShiftC))))))
1712 return nullptr;
1713 uint64_t Shift = ShiftC->getLimitedValue();
1714 Type *XType = X->getType();
1715 if (Shift == 0 || PowerOf2.isMinSignedValue())
1716 return nullptr;
1717 Value *Add = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty: XType, V: PowerOf2));
1718 APInt Bound =
1719 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1720 return new ICmpInst(Pred, Add, ConstantInt::get(Ty: XType, V: Bound));
1721}
1722
1723/// Fold icmp (and (sh X, Y), C2), C1.
1724Instruction *InstCombinerImpl::foldICmpAndShift(ICmpInst &Cmp,
1725 BinaryOperator *And,
1726 const APInt &C1,
1727 const APInt &C2) {
1728 BinaryOperator *Shift = dyn_cast<BinaryOperator>(Val: And->getOperand(i_nocapture: 0));
1729 if (!Shift || !Shift->isShift())
1730 return nullptr;
1731
1732 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1733 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1734 // code produced by the clang front-end, for bitfield access.
1735 // This seemingly simple opportunity to fold away a shift turns out to be
1736 // rather complicated. See PR17827 for details.
1737 unsigned ShiftOpcode = Shift->getOpcode();
1738 bool IsShl = ShiftOpcode == Instruction::Shl;
1739 const APInt *C3;
1740 if (match(V: Shift->getOperand(i_nocapture: 1), P: m_APInt(Res&: C3))) {
1741 APInt NewAndCst, NewCmpCst;
1742 bool AnyCmpCstBitsShiftedOut;
1743 if (ShiftOpcode == Instruction::Shl) {
1744 // For a left shift, we can fold if the comparison is not signed. We can
1745 // also fold a signed comparison if the mask value and comparison value
1746 // are not negative. These constraints may not be obvious, but we can
1747 // prove that they are correct using an SMT solver.
1748 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1749 return nullptr;
1750
1751 NewCmpCst = C1.lshr(ShiftAmt: *C3);
1752 NewAndCst = C2.lshr(ShiftAmt: *C3);
1753 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(ShiftAmt: *C3) != C1;
1754 } else if (ShiftOpcode == Instruction::LShr) {
1755 // For a logical right shift, we can fold if the comparison is not signed.
1756 // We can also fold a signed comparison if the shifted mask value and the
1757 // shifted comparison value are not negative. These constraints may not be
1758 // obvious, but we can prove that they are correct using an SMT solver.
1759 NewCmpCst = C1.shl(ShiftAmt: *C3);
1760 NewAndCst = C2.shl(ShiftAmt: *C3);
1761 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(ShiftAmt: *C3) != C1;
1762 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1763 return nullptr;
1764 } else {
1765 // For an arithmetic shift, check that both constants don't use (in a
1766 // signed sense) the top bits being shifted out.
1767 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1768 NewCmpCst = C1.shl(ShiftAmt: *C3);
1769 NewAndCst = C2.shl(ShiftAmt: *C3);
1770 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(ShiftAmt: *C3) != C1;
1771 if (NewAndCst.ashr(ShiftAmt: *C3) != C2)
1772 return nullptr;
1773 }
1774
1775 if (AnyCmpCstBitsShiftedOut) {
1776 // If we shifted bits out, the fold is not going to work out. As a
1777 // special case, check to see if this means that the result is always
1778 // true or false now.
1779 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1780 return replaceInstUsesWith(I&: Cmp, V: ConstantInt::getFalse(Ty: Cmp.getType()));
1781 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1782 return replaceInstUsesWith(I&: Cmp, V: ConstantInt::getTrue(Ty: Cmp.getType()));
1783 } else {
1784 Value *NewAnd = Builder.CreateAnd(
1785 LHS: Shift->getOperand(i_nocapture: 0), RHS: ConstantInt::get(Ty: And->getType(), V: NewAndCst));
1786 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1787 ConstantInt::get(Ty: And->getType(), V: NewCmpCst));
1788 }
1789 }
1790
1791 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1792 // preferable because it allows the C2 << Y expression to be hoisted out of a
1793 // loop if Y is invariant and X is not.
1794 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1795 !Shift->isArithmeticShift() &&
1796 ((!IsShl && C2.isOne()) || !isa<Constant>(Val: Shift->getOperand(i_nocapture: 0)))) {
1797 // Compute C2 << Y.
1798 Value *NewShift =
1799 IsShl ? Builder.CreateLShr(LHS: And->getOperand(i_nocapture: 1), RHS: Shift->getOperand(i_nocapture: 1))
1800 : Builder.CreateShl(LHS: And->getOperand(i_nocapture: 1), RHS: Shift->getOperand(i_nocapture: 1));
1801
1802 // Compute X & (C2 << Y).
1803 Value *NewAnd = Builder.CreateAnd(LHS: Shift->getOperand(i_nocapture: 0), RHS: NewShift);
1804 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(i_nocapture: 1));
1805 }
1806
1807 return nullptr;
1808}
1809
1810/// Fold icmp (and X, C2), C1.
1811Instruction *InstCombinerImpl::foldICmpAndConstConst(ICmpInst &Cmp,
1812 BinaryOperator *And,
1813 const APInt &C1) {
1814 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1815
1816 // icmp ne (and X, 1), 0 --> trunc X to i1
1817 if (isICMP_NE && C1.isZero() && match(V: And->getOperand(i_nocapture: 1), P: m_One()))
1818 return new TruncInst(And->getOperand(i_nocapture: 0), Cmp.getType());
1819
1820 const APInt *C2;
1821 Value *X;
1822 if (!match(V: And, P: m_And(L: m_Value(V&: X), R: m_APInt(Res&: C2))))
1823 return nullptr;
1824
1825 // (and X, highmask) s> [0, ~highmask] --> X s> ~highmask
1826 if (Cmp.getPredicate() == ICmpInst::ICMP_SGT && C1.ule(RHS: ~*C2) &&
1827 C2->isNegatedPowerOf2())
1828 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1829 ConstantInt::get(Ty: X->getType(), V: ~*C2));
1830 // (and X, highmask) s< [1, -highmask] --> X s< -highmask
1831 if (Cmp.getPredicate() == ICmpInst::ICMP_SLT && !C1.isSignMask() &&
1832 (C1 - 1).ule(RHS: ~*C2) && C2->isNegatedPowerOf2() && !C2->isSignMask())
1833 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1834 ConstantInt::get(Ty: X->getType(), V: -*C2));
1835
1836 // Don't perform the following transforms if the AND has multiple uses
1837 if (!And->hasOneUse())
1838 return nullptr;
1839
1840 if (Cmp.isEquality() && C1.isZero()) {
1841 // Restrict this fold to single-use 'and' (PR10267).
1842 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1843 if (C2->isSignMask()) {
1844 Constant *Zero = Constant::getNullValue(Ty: X->getType());
1845 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1846 return new ICmpInst(NewPred, X, Zero);
1847 }
1848
1849 APInt NewC2 = *C2;
1850 KnownBits Know = computeKnownBits(V: And->getOperand(i_nocapture: 0), CxtI: And);
1851 // Set high zeros of C2 to allow matching negated power-of-2.
1852 NewC2 = *C2 | APInt::getHighBitsSet(numBits: C2->getBitWidth(),
1853 hiBitsSet: Know.countMinLeadingZeros());
1854
1855 // Restrict this fold only for single-use 'and' (PR10267).
1856 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1857 if (NewC2.isNegatedPowerOf2()) {
1858 Constant *NegBOC = ConstantInt::get(Ty: And->getType(), V: -NewC2);
1859 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1860 return new ICmpInst(NewPred, X, NegBOC);
1861 }
1862 }
1863
1864 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1865 // the input width without changing the value produced, eliminate the cast:
1866 //
1867 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1868 //
1869 // We can do this transformation if the constants do not have their sign bits
1870 // set or if it is an equality comparison. Extending a relational comparison
1871 // when we're checking the sign bit would not work.
1872 Value *W;
1873 if (match(V: And->getOperand(i_nocapture: 0), P: m_OneUse(SubPattern: m_Trunc(Op: m_Value(V&: W)))) &&
1874 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1875 // TODO: Is this a good transform for vectors? Wider types may reduce
1876 // throughput. Should this transform be limited (even for scalars) by using
1877 // shouldChangeType()?
1878 if (!Cmp.getType()->isVectorTy()) {
1879 Type *WideType = W->getType();
1880 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1881 Constant *ZextC1 = ConstantInt::get(Ty: WideType, V: C1.zext(width: WideScalarBits));
1882 Constant *ZextC2 = ConstantInt::get(Ty: WideType, V: C2->zext(width: WideScalarBits));
1883 Value *NewAnd = Builder.CreateAnd(LHS: W, RHS: ZextC2, Name: And->getName());
1884 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1885 }
1886 }
1887
1888 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, C2: *C2))
1889 return I;
1890
1891 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1892 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1893 //
1894 // iff pred isn't signed
1895 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(i_nocapture: 0)->hasOneUse() &&
1896 match(V: And->getOperand(i_nocapture: 1), P: m_One())) {
1897 Constant *One = cast<Constant>(Val: And->getOperand(i_nocapture: 1));
1898 Value *Or = And->getOperand(i_nocapture: 0);
1899 Value *A, *B, *LShr;
1900 if (match(V: Or, P: m_Or(L: m_Value(V&: LShr), R: m_Value(V&: A))) &&
1901 match(V: LShr, P: m_LShr(L: m_Specific(V: A), R: m_Value(V&: B)))) {
1902 unsigned UsesRemoved = 0;
1903 if (And->hasOneUse())
1904 ++UsesRemoved;
1905 if (Or->hasOneUse())
1906 ++UsesRemoved;
1907 if (LShr->hasOneUse())
1908 ++UsesRemoved;
1909
1910 // Compute A & ((1 << B) | 1)
1911 unsigned RequireUsesRemoved = match(V: B, P: m_ImmConstant()) ? 1 : 3;
1912 if (UsesRemoved >= RequireUsesRemoved) {
1913 Value *NewOr =
1914 Builder.CreateOr(LHS: Builder.CreateShl(LHS: One, RHS: B, Name: LShr->getName(),
1915 /*HasNUW=*/true),
1916 RHS: One, Name: Or->getName());
1917 Value *NewAnd = Builder.CreateAnd(LHS: A, RHS: NewOr, Name: And->getName());
1918 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(i_nocapture: 1));
1919 }
1920 }
1921 }
1922
1923 // (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->
1924 // llvm.is.fpclass(X, fcInf|fcNan)
1925 // (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->
1926 // llvm.is.fpclass(X, ~(fcInf|fcNan))
1927 // (icmp eq (and (bitcast X to int), ExponentMask), 0) -->
1928 // llvm.is.fpclass(X, fcSubnormal|fcZero)
1929 // (icmp ne (and (bitcast X to int), ExponentMask), 0) -->
1930 // llvm.is.fpclass(X, ~(fcSubnormal|fcZero))
1931 Value *V;
1932 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1933 Kind: Attribute::NoImplicitFloat) &&
1934 Cmp.isEquality() &&
1935 match(V: X, P: m_OneUse(SubPattern: m_ElementWiseBitCast(Op: m_Value(V))))) {
1936 Type *FPType = V->getType()->getScalarType();
1937 if (FPType->isIEEELikeFPTy() && (C1.isZero() || C1 == *C2)) {
1938 APInt ExponentMask =
1939 APFloat::getInf(Sem: FPType->getFltSemantics()).bitcastToAPInt();
1940 if (*C2 == ExponentMask) {
1941 unsigned Mask = C1.isZero()
1942 ? FPClassTest::fcZero | FPClassTest::fcSubnormal
1943 : FPClassTest::fcNan | FPClassTest::fcInf;
1944 if (isICMP_NE)
1945 Mask = ~Mask & fcAllFlags;
1946 return replaceInstUsesWith(I&: Cmp, V: Builder.createIsFPClass(FPNum: V, Test: Mask));
1947 }
1948 }
1949 }
1950
1951 return nullptr;
1952}
1953
1954/// Fold icmp (and X, Y), C.
1955Instruction *InstCombinerImpl::foldICmpAndConstant(ICmpInst &Cmp,
1956 BinaryOperator *And,
1957 const APInt &C) {
1958 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C1: C))
1959 return I;
1960
1961 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1962 bool TrueIfNeg;
1963 if (isSignBitCheck(Pred, RHS: C, TrueIfSigned&: TrueIfNeg)) {
1964 // ((X - 1) & ~X) < 0 --> X == 0
1965 // ((X - 1) & ~X) >= 0 --> X != 0
1966 Value *X;
1967 if (match(V: And->getOperand(i_nocapture: 0), P: m_Add(L: m_Value(V&: X), R: m_AllOnes())) &&
1968 match(V: And->getOperand(i_nocapture: 1), P: m_Not(V: m_Specific(V: X)))) {
1969 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1970 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(Ty: X->getType()));
1971 }
1972 // (X & -X) < 0 --> X == MinSignedC
1973 // (X & -X) > -1 --> X != MinSignedC
1974 if (match(V: And, P: m_c_And(L: m_Neg(V: m_Value(V&: X)), R: m_Deferred(V: X)))) {
1975 Constant *MinSignedC = ConstantInt::get(
1976 Ty: X->getType(),
1977 V: APInt::getSignedMinValue(numBits: X->getType()->getScalarSizeInBits()));
1978 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1979 return new ICmpInst(NewPred, X, MinSignedC);
1980 }
1981 }
1982
1983 // TODO: These all require that Y is constant too, so refactor with the above.
1984
1985 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1986 Value *X = And->getOperand(i_nocapture: 0);
1987 Value *Y = And->getOperand(i_nocapture: 1);
1988 if (auto *C2 = dyn_cast<ConstantInt>(Val: Y))
1989 if (auto *LI = dyn_cast<LoadInst>(Val: X))
1990 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: LI->getOperand(i_nocapture: 0)))
1991 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(LI, GEP, ICI&: Cmp, AndCst: C2))
1992 return Res;
1993
1994 if (!Cmp.isEquality())
1995 return nullptr;
1996
1997 // (X & -X) == 0 --> X == 0
1998 // (X & -X) != 0 --> X != 0
1999 // (X & -X) == 1 --> trunc X to i1
2000 // (X & -X) != 1 --> !(trunc X to i1)
2001 // Cmp is == or != by the check above.
2002 Value *MatchedX;
2003 // Match X & -X in either operand order.
2004 if (C.getBitWidth() > 1 && (C.isZero() || C.isOne()) &&
2005 match(V: And, P: m_c_And(L: m_Neg(V: m_Value(V&: MatchedX)), R: m_Deferred(V: MatchedX)))) {
2006 // Preserve the predicate: (X & -X) ==/!= 0 --> X ==/!= 0.
2007 if (C.isZero())
2008 return new ICmpInst(Pred, MatchedX, Cmp.getOperand(i_nocapture: 1));
2009
2010 // (X & -X) == 1 iff the low bit of X is set.
2011 if (Pred == CmpInst::ICMP_EQ)
2012 return new TruncInst(MatchedX, Cmp.getType());
2013
2014 // The remaining case needs a trunc and not. Require the original and
2015 // to become dead to avoid increasing the instruction count.
2016 if (And->hasOneUse()) {
2017 Value *Trunc = Builder.CreateTrunc(V: MatchedX, DestTy: Cmp.getType());
2018 return BinaryOperator::CreateNot(Op: Trunc);
2019 }
2020 }
2021
2022 // X & -C == -C -> X > u ~C
2023 // X & -C != -C -> X <= u ~C
2024 // iff C is a power of 2
2025 if (Cmp.getOperand(i_nocapture: 1) == Y && C.isNegatedPowerOf2()) {
2026 auto NewPred =
2027 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT : CmpInst::ICMP_ULE;
2028 return new ICmpInst(NewPred, X, SubOne(C: cast<Constant>(Val: Cmp.getOperand(i_nocapture: 1))));
2029 }
2030
2031 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
2032 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
2033 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
2034 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
2035 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)))) &&
2036 X->getType()->isIntOrIntVectorTy(BitWidth: 1) && (C.isZero() || C.isOne())) {
2037 Value *TruncY = Builder.CreateTrunc(V: Y, DestTy: X->getType());
2038 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
2039 Value *And = Builder.CreateAnd(LHS: TruncY, RHS: X);
2040 return BinaryOperator::CreateNot(Op: And);
2041 }
2042 return BinaryOperator::CreateAnd(V1: TruncY, V2: X);
2043 }
2044
2045 // (icmp eq/ne (and (shl -1, X), Y), 0)
2046 // -> (icmp eq/ne (lshr Y, X), 0)
2047 // We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems
2048 // highly unlikely the non-zero case will ever show up in code.
2049 if (C.isZero() &&
2050 match(V: And, P: m_OneUse(SubPattern: m_c_And(L: m_OneUse(SubPattern: m_Shl(L: m_AllOnes(), R: m_Value(V&: X))),
2051 R: m_Value(V&: Y))))) {
2052 Value *LShr = Builder.CreateLShr(LHS: Y, RHS: X);
2053 return new ICmpInst(Pred, LShr, Constant::getNullValue(Ty: LShr->getType()));
2054 }
2055
2056 // (icmp eq/ne (and (add A, Addend), Msk), C)
2057 // -> (icmp eq/ne (and A, Msk), (and (sub C, Addend), Msk))
2058 {
2059 Value *A;
2060 const APInt *Addend, *Msk;
2061 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))),
2062 R: m_LowBitMask(V&: Msk)))) &&
2063 C.ule(RHS: *Msk)) {
2064 APInt NewComperand = (C - *Addend) & *Msk;
2065 Value *MaskA = Builder.CreateAnd(LHS: A, RHS: ConstantInt::get(Ty: A->getType(), V: *Msk));
2066 return new ICmpInst(Pred, MaskA,
2067 ConstantInt::get(Ty: MaskA->getType(), V: NewComperand));
2068 }
2069 }
2070
2071 return nullptr;
2072}
2073
2074/// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
2075static Value *foldICmpOrXorSubChain(ICmpInst &Cmp, BinaryOperator *Or,
2076 InstCombiner::BuilderTy &Builder) {
2077 // Are we using xors or subs to bitwise check for a pair or pairs of
2078 // (in)equalities? Convert to a shorter form that has more potential to be
2079 // folded even further.
2080 // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
2081 // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
2082 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
2083 // (X1 == X2) && (X3 == X4) && (X5 == X6)
2084 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
2085 // (X1 != X2) || (X3 != X4) || (X5 != X6)
2086 SmallVector<std::pair<Value *, Value *>, 2> CmpValues;
2087 SmallVector<Value *, 16> WorkList(1, Or);
2088
2089 while (!WorkList.empty()) {
2090 auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
2091 Value *Lhs, *Rhs;
2092
2093 if (match(V: OrOperatorArgument,
2094 P: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: Lhs), R: m_Value(V&: Rhs))))) {
2095 CmpValues.emplace_back(Args&: Lhs, Args&: Rhs);
2096 return;
2097 }
2098
2099 if (match(V: OrOperatorArgument,
2100 P: m_OneUse(SubPattern: m_Sub(L: m_Value(V&: Lhs), R: m_Value(V&: Rhs))))) {
2101 CmpValues.emplace_back(Args&: Lhs, Args&: Rhs);
2102 return;
2103 }
2104
2105 WorkList.push_back(Elt: OrOperatorArgument);
2106 };
2107
2108 Value *CurrentValue = WorkList.pop_back_val();
2109 Value *OrOperatorLhs, *OrOperatorRhs;
2110
2111 if (!match(V: CurrentValue,
2112 P: m_Or(L: m_Value(V&: OrOperatorLhs), R: m_Value(V&: OrOperatorRhs)))) {
2113 return nullptr;
2114 }
2115
2116 MatchOrOperatorArgument(OrOperatorRhs);
2117 MatchOrOperatorArgument(OrOperatorLhs);
2118 }
2119
2120 ICmpInst::Predicate Pred = Cmp.getPredicate();
2121 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2122 Value *LhsCmp = Builder.CreateICmp(P: Pred, LHS: CmpValues.rbegin()->first,
2123 RHS: CmpValues.rbegin()->second);
2124
2125 for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
2126 Value *RhsCmp = Builder.CreateICmp(P: Pred, LHS: It->first, RHS: It->second);
2127 LhsCmp = Builder.CreateBinOp(Opc: BOpc, LHS: LhsCmp, RHS: RhsCmp);
2128 }
2129
2130 return LhsCmp;
2131}
2132
2133/// Fold icmp (or X, Y), C.
2134Instruction *InstCombinerImpl::foldICmpOrConstant(ICmpInst &Cmp,
2135 BinaryOperator *Or,
2136 const APInt &C) {
2137 ICmpInst::Predicate Pred = Cmp.getPredicate();
2138 if (C.isOne()) {
2139 // icmp slt signum(V) 1 --> icmp slt V, 1
2140 Value *V = nullptr;
2141 if (Pred == ICmpInst::ICMP_SLT && match(V: Or, P: m_Signum(V: m_Value(V))))
2142 return new ICmpInst(ICmpInst::ICMP_SLT, V,
2143 ConstantInt::get(Ty: V->getType(), V: 1));
2144 }
2145
2146 Value *OrOp0 = Or->getOperand(i_nocapture: 0), *OrOp1 = Or->getOperand(i_nocapture: 1);
2147
2148 // (icmp eq/ne (or disjoint x, C0), C1)
2149 // -> (icmp eq/ne x, C0^C1)
2150 if (Cmp.isEquality() && match(V: OrOp1, P: m_ImmConstant()) &&
2151 cast<PossiblyDisjointInst>(Val: Or)->isDisjoint()) {
2152 Value *NewC =
2153 Builder.CreateXor(LHS: OrOp1, RHS: ConstantInt::get(Ty: OrOp1->getType(), V: C));
2154 return new ICmpInst(Pred, OrOp0, NewC);
2155 }
2156
2157 const APInt *MaskC;
2158 if (match(V: OrOp1, P: m_APInt(Res&: MaskC)) && Cmp.isEquality()) {
2159 if (*MaskC == C && (C + 1).isPowerOf2()) {
2160 // X | C == C --> X <=u C
2161 // X | C != C --> X >u C
2162 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
2163 Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT;
2164 return new ICmpInst(Pred, OrOp0, OrOp1);
2165 }
2166
2167 // More general: canonicalize 'equality with set bits mask' to
2168 // 'equality with clear bits mask'.
2169 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2170 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2171 if (Or->hasOneUse()) {
2172 Value *And = Builder.CreateAnd(LHS: OrOp0, RHS: ~(*MaskC));
2173 Constant *NewC = ConstantInt::get(Ty: Or->getType(), V: C ^ (*MaskC));
2174 return new ICmpInst(Pred, And, NewC);
2175 }
2176 }
2177
2178 // (X | (X-1)) s< 0 --> X s< 1
2179 // (X | (X-1)) s> -1 --> X s> 0
2180 Value *X;
2181 bool TrueIfSigned;
2182 if (isSignBitCheck(Pred, RHS: C, TrueIfSigned) &&
2183 match(V: Or, P: m_c_Or(L: m_Add(L: m_Value(V&: X), R: m_AllOnes()), R: m_Deferred(V: X)))) {
2184 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2185 Constant *NewC = ConstantInt::get(Ty: X->getType(), V: TrueIfSigned ? 1 : 0);
2186 return new ICmpInst(NewPred, X, NewC);
2187 }
2188
2189 const APInt *OrC;
2190 // icmp(X | OrC, C) --> icmp(X, 0)
2191 if (C.isNonNegative() && match(V: Or, P: m_Or(L: m_Value(V&: X), R: m_APInt(Res&: OrC)))) {
2192 switch (Pred) {
2193 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2194 case ICmpInst::ICMP_SLT:
2195 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2196 case ICmpInst::ICMP_SGE:
2197 if (OrC->sge(RHS: C))
2198 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: X->getType()));
2199 break;
2200 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2201 case ICmpInst::ICMP_SLE:
2202 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2203 case ICmpInst::ICMP_SGT:
2204 if (OrC->sgt(RHS: C))
2205 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), X,
2206 ConstantInt::getNullValue(Ty: X->getType()));
2207 break;
2208 default:
2209 break;
2210 }
2211 }
2212
2213 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2214 return nullptr;
2215
2216 Value *P, *Q;
2217 if (match(V: Or, P: m_Or(L: m_PtrToInt(Op: m_Value(V&: P)), R: m_PtrToInt(Op: m_Value(V&: Q))))) {
2218 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2219 // -> and (icmp eq P, null), (icmp eq Q, null).
2220 Value *CmpP =
2221 Builder.CreateICmp(P: Pred, LHS: P, RHS: ConstantInt::getNullValue(Ty: P->getType()));
2222 Value *CmpQ =
2223 Builder.CreateICmp(P: Pred, LHS: Q, RHS: ConstantInt::getNullValue(Ty: Q->getType()));
2224 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2225 return BinaryOperator::Create(Op: BOpc, S1: CmpP, S2: CmpQ);
2226 }
2227
2228 if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2229 return replaceInstUsesWith(I&: Cmp, V);
2230
2231 return nullptr;
2232}
2233
2234/// Fold icmp (mul X, Y), C.
2235Instruction *InstCombinerImpl::foldICmpMulConstant(ICmpInst &Cmp,
2236 BinaryOperator *Mul,
2237 const APInt &C) {
2238 ICmpInst::Predicate Pred = Cmp.getPredicate();
2239 Type *MulTy = Mul->getType();
2240 Value *X = Mul->getOperand(i_nocapture: 0);
2241
2242 // If comparing a square with a constant, try simplifying to comparing square
2243 // roots.
2244 if (X == Mul->getOperand(i_nocapture: 1) && !Cmp.isSigned()) {
2245 APInt R = C.sqrtFloor();
2246 bool IsSqr = C == R * R;
2247
2248 // X * X eq/ne C
2249 if (Cmp.isEquality() &&
2250 (Mul->hasNoUnsignedWrap() || (Mul->hasNoSignedWrap() && C.isZero()))) {
2251
2252 // If constant is not a square, eq/ne is false/true respectively
2253 if (!IsSqr)
2254 return replaceInstUsesWith(
2255 I&: Cmp,
2256 V: ConstantInt::getBool(Ty: Cmp.getType(), V: Pred == ICmpInst::ICMP_NE));
2257
2258 return new ICmpInst(Pred, X, ConstantInt::get(Ty: MulTy, V: R));
2259 }
2260
2261 // If the multiply does not wrap
2262 // X * X pred C --> X pred R
2263 if (Mul->hasNoUnsignedWrap()) {
2264
2265 if (IsSqr)
2266 return new ICmpInst(Pred, X, ConstantInt::get(Ty: MulTy, V: R));
2267
2268 // If C is not a square, we use floor/ceil of sqrt(C).
2269 //
2270 // If LT or LE, we need R to be an overestimate of sqrt(C),
2271 // then use the strict predicate (LT->LT, LE->LT).
2272 //
2273 // If GT or GE, we need R to be an underestimate of sqrt(C),
2274 // then use the strict predicate (GT->GT, GE->GT).
2275 //
2276 // R is already an underestimate of sqrt(C) due to sqrtFloor.
2277 if (ICmpInst::isLT(P: Pred) || ICmpInst::isLE(P: Pred))
2278 ++R;
2279
2280 return new ICmpInst(Cmp.getStrictPredicate(), X,
2281 ConstantInt::get(Ty: MulTy, V: R));
2282 }
2283 }
2284
2285 const APInt *MulC;
2286 if (!match(V: Mul->getOperand(i_nocapture: 1), P: m_APInt(Res&: MulC)))
2287 return nullptr;
2288
2289 // If this is a test of the sign bit and the multiply is sign-preserving with
2290 // a constant operand, use the multiply LHS operand instead:
2291 // (X * +MulC) < 0 --> X < 0
2292 // (X * -MulC) < 0 --> X > 0
2293 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2294 if (MulC->isNegative())
2295 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
2296 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: MulTy));
2297 }
2298
2299 if (MulC->isZero())
2300 return nullptr;
2301
2302 // If the multiply does not wrap or the constant is odd, try to divide the
2303 // compare constant by the multiplication factor.
2304 if (Cmp.isEquality()) {
2305 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2306 if (Mul->hasNoSignedWrap() && C.srem(RHS: *MulC).isZero()) {
2307 Constant *NewC = ConstantInt::get(Ty: MulTy, V: C.sdiv(RHS: *MulC));
2308 return new ICmpInst(Pred, X, NewC);
2309 }
2310
2311 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2312 // correct to transform if MulC * N == C including overflow. I.e with i8
2313 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2314 // miss that case.
2315 if (C.urem(RHS: *MulC).isZero()) {
2316 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2317 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2318 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2319 Constant *NewC = ConstantInt::get(Ty: MulTy, V: C.udiv(RHS: *MulC));
2320 return new ICmpInst(Pred, X, NewC);
2321 }
2322 }
2323 }
2324
2325 // With a matching no-overflow guarantee, fold the constants:
2326 // (X * MulC) < C --> X < (C / MulC)
2327 // (X * MulC) > C --> X > (C / MulC)
2328 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2329 Constant *NewC = nullptr;
2330 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2331 // MININT / -1 --> overflow.
2332 if (C.isMinSignedValue() && MulC->isAllOnes())
2333 return nullptr;
2334 if (MulC->isNegative())
2335 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
2336
2337 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2338 NewC = ConstantInt::get(
2339 Ty: MulTy, V: APIntOps::RoundingSDiv(A: C, B: *MulC, RM: APInt::Rounding::UP));
2340 } else {
2341 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2342 "Unexpected predicate");
2343 NewC = ConstantInt::get(
2344 Ty: MulTy, V: APIntOps::RoundingSDiv(A: C, B: *MulC, RM: APInt::Rounding::DOWN));
2345 }
2346 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2347 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2348 NewC = ConstantInt::get(
2349 Ty: MulTy, V: APIntOps::RoundingUDiv(A: C, B: *MulC, RM: APInt::Rounding::UP));
2350 } else {
2351 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2352 "Unexpected predicate");
2353 NewC = ConstantInt::get(
2354 Ty: MulTy, V: APIntOps::RoundingUDiv(A: C, B: *MulC, RM: APInt::Rounding::DOWN));
2355 }
2356 }
2357
2358 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2359}
2360
2361/// Fold icmp (shl nuw C2, Y), C.
2362static Instruction *foldICmpShlLHSC(ICmpInst &Cmp, Instruction *Shl,
2363 const APInt &C) {
2364 Value *Y;
2365 const APInt *C2;
2366 if (!match(V: Shl, P: m_NUWShl(L: m_APInt(Res&: C2), R: m_Value(V&: Y))))
2367 return nullptr;
2368
2369 Type *ShiftType = Shl->getType();
2370 unsigned TypeBits = C.getBitWidth();
2371 ICmpInst::Predicate Pred = Cmp.getPredicate();
2372 if (Cmp.isUnsigned()) {
2373 if (C2->isZero() || C2->ugt(RHS: C))
2374 return nullptr;
2375 APInt Div, Rem;
2376 APInt::udivrem(LHS: C, RHS: *C2, Quotient&: Div, Remainder&: Rem);
2377 bool CIsPowerOf2 = Rem.isZero() && Div.isPowerOf2();
2378
2379 // (1 << Y) pred C -> Y pred Log2(C)
2380 if (!CIsPowerOf2) {
2381 // (1 << Y) < 30 -> Y <= 4
2382 // (1 << Y) <= 30 -> Y <= 4
2383 // (1 << Y) >= 30 -> Y > 4
2384 // (1 << Y) > 30 -> Y > 4
2385 if (Pred == ICmpInst::ICMP_ULT)
2386 Pred = ICmpInst::ICMP_ULE;
2387 else if (Pred == ICmpInst::ICMP_UGE)
2388 Pred = ICmpInst::ICMP_UGT;
2389 }
2390
2391 unsigned CLog2 = Div.logBase2();
2392 return new ICmpInst(Pred, Y, ConstantInt::get(Ty: ShiftType, V: CLog2));
2393 } else if (Cmp.isSigned() && C2->isOne()) {
2394 Constant *BitWidthMinusOne = ConstantInt::get(Ty: ShiftType, V: TypeBits - 1);
2395 // (1 << Y) > 0 -> Y != 31
2396 // (1 << Y) > C -> Y != 31 if C is negative.
2397 if (Pred == ICmpInst::ICMP_SGT && C.sle(RHS: 0))
2398 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2399
2400 // (1 << Y) < 0 -> Y == 31
2401 // (1 << Y) < 1 -> Y == 31
2402 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2403 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2404 if (Pred == ICmpInst::ICMP_SLT && (C - 1).sle(RHS: 0))
2405 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2406 }
2407
2408 return nullptr;
2409}
2410
2411/// Fold icmp (shl X, Y), C.
2412Instruction *InstCombinerImpl::foldICmpShlConstant(ICmpInst &Cmp,
2413 BinaryOperator *Shl,
2414 const APInt &C) {
2415 const APInt *ShiftVal;
2416 if (Cmp.isEquality() && match(V: Shl->getOperand(i_nocapture: 0), P: m_APInt(Res&: ShiftVal)))
2417 return foldICmpShlConstConst(I&: Cmp, A: Shl->getOperand(i_nocapture: 1), AP1: C, AP2: *ShiftVal);
2418
2419 ICmpInst::Predicate Pred = Cmp.getPredicate();
2420 // (icmp pred (shl nuw&nsw X, Y), Csle0)
2421 // -> (icmp pred X, Csle0)
2422 //
2423 // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2424 // so X's must be what is used.
2425 if (C.sle(RHS: 0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2426 return new ICmpInst(Pred, Shl->getOperand(i_nocapture: 0), Cmp.getOperand(i_nocapture: 1));
2427
2428 // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2429 // -> (icmp eq/ne X, 0)
2430 if (ICmpInst::isEquality(P: Pred) && C.isZero() &&
2431 (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2432 return new ICmpInst(Pred, Shl->getOperand(i_nocapture: 0), Cmp.getOperand(i_nocapture: 1));
2433
2434 // (icmp slt (shl nsw X, Y), 0/1)
2435 // -> (icmp slt X, 0/1)
2436 // (icmp sgt (shl nsw X, Y), 0/-1)
2437 // -> (icmp sgt X, 0/-1)
2438 //
2439 // NB: sge/sle with a constant will canonicalize to sgt/slt.
2440 if (Shl->hasNoSignedWrap() &&
2441 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2442 if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2443 return new ICmpInst(Pred, Shl->getOperand(i_nocapture: 0), Cmp.getOperand(i_nocapture: 1));
2444
2445 const APInt *ShiftAmt;
2446 if (!match(V: Shl->getOperand(i_nocapture: 1), P: m_APInt(Res&: ShiftAmt)))
2447 return foldICmpShlLHSC(Cmp, Shl, C);
2448
2449 // Check that the shift amount is in range. If not, don't perform undefined
2450 // shifts. When the shift is visited, it will be simplified.
2451 unsigned TypeBits = C.getBitWidth();
2452 if (ShiftAmt->uge(RHS: TypeBits))
2453 return nullptr;
2454
2455 Value *X = Shl->getOperand(i_nocapture: 0);
2456 Type *ShType = Shl->getType();
2457
2458 // NSW guarantees that we are only shifting out sign bits from the high bits,
2459 // so we can ASHR the compare constant without needing a mask and eliminate
2460 // the shift.
2461 if (Shl->hasNoSignedWrap()) {
2462 if (Pred == ICmpInst::ICMP_SGT) {
2463 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2464 APInt ShiftedC = C.ashr(ShiftAmt: *ShiftAmt);
2465 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2466 }
2467 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2468 C.ashr(ShiftAmt: *ShiftAmt).shl(ShiftAmt: *ShiftAmt) == C) {
2469 APInt ShiftedC = C.ashr(ShiftAmt: *ShiftAmt);
2470 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2471 }
2472 if (Pred == ICmpInst::ICMP_SLT) {
2473 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2474 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2475 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2476 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2477 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2478 APInt ShiftedC = (C - 1).ashr(ShiftAmt: *ShiftAmt) + 1;
2479 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2480 }
2481 }
2482
2483 // NUW guarantees that we are only shifting out zero bits from the high bits,
2484 // so we can LSHR the compare constant without needing a mask and eliminate
2485 // the shift.
2486 if (Shl->hasNoUnsignedWrap()) {
2487 if (Pred == ICmpInst::ICMP_UGT) {
2488 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2489 APInt ShiftedC = C.lshr(ShiftAmt: *ShiftAmt);
2490 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2491 }
2492 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2493 C.lshr(ShiftAmt: *ShiftAmt).shl(ShiftAmt: *ShiftAmt) == C) {
2494 APInt ShiftedC = C.lshr(ShiftAmt: *ShiftAmt);
2495 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2496 }
2497 if (Pred == ICmpInst::ICMP_ULT) {
2498 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2499 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2500 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2501 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2502 assert(C.ugt(0) && "ult 0 should have been eliminated");
2503 APInt ShiftedC = (C - 1).lshr(ShiftAmt: *ShiftAmt) + 1;
2504 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2505 }
2506 }
2507
2508 if (Cmp.isEquality() && Shl->hasOneUse()) {
2509 // Strength-reduce the shift into an 'and'.
2510 Constant *Mask = ConstantInt::get(
2511 Ty: ShType,
2512 V: APInt::getLowBitsSet(numBits: TypeBits, loBitsSet: TypeBits - ShiftAmt->getZExtValue()));
2513 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask, Name: Shl->getName() + ".mask");
2514 Constant *LShrC = ConstantInt::get(Ty: ShType, V: C.lshr(ShiftAmt: *ShiftAmt));
2515 return new ICmpInst(Pred, And, LShrC);
2516 }
2517
2518 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2519 bool TrueIfSigned = false;
2520 if (Shl->hasOneUse() && isSignBitCheck(Pred, RHS: C, TrueIfSigned)) {
2521 // (X << 31) <s 0 --> (X & 1) != 0
2522 Constant *Mask = ConstantInt::get(
2523 Ty: ShType,
2524 V: APInt::getOneBitSet(numBits: TypeBits, BitNo: TypeBits - ShiftAmt->getZExtValue() - 1));
2525 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask, Name: Shl->getName() + ".mask");
2526 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2527 And, Constant::getNullValue(Ty: ShType));
2528 }
2529
2530 // Simplify 'shl' inequality test into 'and' equality test.
2531 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2532 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2533 if ((C + 1).isPowerOf2() &&
2534 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2535 Value *And = Builder.CreateAnd(LHS: X, RHS: (~C).lshr(shiftAmt: ShiftAmt->getZExtValue()));
2536 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2537 : ICmpInst::ICMP_NE,
2538 And, Constant::getNullValue(Ty: ShType));
2539 }
2540 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2541 if (C.isPowerOf2() &&
2542 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2543 Value *And =
2544 Builder.CreateAnd(LHS: X, RHS: (~(C - 1)).lshr(shiftAmt: ShiftAmt->getZExtValue()));
2545 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2546 : ICmpInst::ICMP_NE,
2547 And, Constant::getNullValue(Ty: ShType));
2548 }
2549 }
2550
2551 // Transform (icmp pred iM (shl iM %v, N), C)
2552 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2553 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2554 // This enables us to get rid of the shift in favor of a trunc that may be
2555 // free on the target. It has the additional benefit of comparing to a
2556 // smaller constant that may be more target-friendly.
2557 unsigned Amt = ShiftAmt->getLimitedValue(Limit: TypeBits - 1);
2558 if (Shl->hasOneUse() && Amt != 0 &&
2559 shouldChangeType(FromBitWidth: ShType->getScalarSizeInBits(), ToBitWidth: TypeBits - Amt)) {
2560 ICmpInst::Predicate CmpPred = Pred;
2561 APInt RHSC = C;
2562
2563 if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(predicate: CmpPred)) {
2564 // Try the flipped strictness predicate.
2565 // e.g.:
2566 // icmp ult i64 (shl X, 32), 8589934593 ->
2567 // icmp ule i64 (shl X, 32), 8589934592 ->
2568 // icmp ule i32 (trunc X, i32), 2 ->
2569 // icmp ult i32 (trunc X, i32), 3
2570 if (auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(
2571 Pred, C: ConstantInt::get(Context&: ShType->getContext(), V: C))) {
2572 CmpPred = FlippedStrictness->first;
2573 RHSC = cast<ConstantInt>(Val: FlippedStrictness->second)->getValue();
2574 }
2575 }
2576
2577 if (RHSC.countr_zero() >= Amt) {
2578 Type *TruncTy = ShType->getWithNewBitWidth(NewBitWidth: TypeBits - Amt);
2579 Constant *NewC =
2580 ConstantInt::get(Ty: TruncTy, V: RHSC.ashr(ShiftAmt: *ShiftAmt).trunc(width: TypeBits - Amt));
2581 return new ICmpInst(CmpPred,
2582 Builder.CreateTrunc(V: X, DestTy: TruncTy, Name: "", /*IsNUW=*/false,
2583 IsNSW: Shl->hasNoSignedWrap()),
2584 NewC);
2585 }
2586 }
2587
2588 return nullptr;
2589}
2590
2591/// Fold icmp ({al}shr X, Y), C.
2592Instruction *InstCombinerImpl::foldICmpShrConstant(ICmpInst &Cmp,
2593 BinaryOperator *Shr,
2594 const APInt &C) {
2595 // An exact shr only shifts out zero bits, so:
2596 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2597 Value *X = Shr->getOperand(i_nocapture: 0);
2598 CmpInst::Predicate Pred = Cmp.getPredicate();
2599 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2600 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
2601
2602 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2603 const APInt *ShiftValC;
2604 if (match(V: X, P: m_APInt(Res&: ShiftValC))) {
2605 if (Cmp.isEquality())
2606 return foldICmpShrConstConst(I&: Cmp, A: Shr->getOperand(i_nocapture: 1), AP1: C, AP2: *ShiftValC);
2607
2608 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2609 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2610 bool TrueIfSigned;
2611 if (!IsAShr && ShiftValC->isNegative() &&
2612 isSignBitCheck(Pred, RHS: C, TrueIfSigned))
2613 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2614 Shr->getOperand(i_nocapture: 1),
2615 ConstantInt::getNullValue(Ty: X->getType()));
2616
2617 // If the shifted constant is a power-of-2, test the shift amount directly:
2618 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2619 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2620 if (!IsAShr && ShiftValC->isPowerOf2() &&
2621 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2622 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2623 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2624 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2625
2626 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2627 unsigned ShiftLZ = ShiftValC->countl_zero();
2628 Constant *NewC = ConstantInt::get(Ty: Shr->getType(), V: CmpLZ - ShiftLZ);
2629 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2630 return new ICmpInst(NewPred, Shr->getOperand(i_nocapture: 1), NewC);
2631 }
2632 }
2633
2634 const APInt *ShiftAmtC;
2635 if (!match(V: Shr->getOperand(i_nocapture: 1), P: m_APInt(Res&: ShiftAmtC)))
2636 return nullptr;
2637
2638 // Check that the shift amount is in range. If not, don't perform undefined
2639 // shifts. When the shift is visited it will be simplified.
2640 unsigned TypeBits = C.getBitWidth();
2641 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(Limit: TypeBits);
2642 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2643 return nullptr;
2644
2645 bool IsExact = Shr->isExact();
2646 Type *ShrTy = Shr->getType();
2647 // TODO: If we could guarantee that InstSimplify would handle all of the
2648 // constant-value-based preconditions in the folds below, then we could assert
2649 // those conditions rather than checking them. This is difficult because of
2650 // undef/poison (PR34838).
2651 if (IsAShr && Shr->hasOneUse()) {
2652 if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&
2653 (C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {
2654 // When C - 1 is a power of two and the transform can be legally
2655 // performed, prefer this form so the produced constant is close to a
2656 // power of two.
2657 // icmp slt/ult (ashr exact X, ShAmtC), C
2658 // --> icmp slt/ult X, (C - 1) << ShAmtC) + 1
2659 APInt ShiftedC = (C - 1).shl(shiftAmt: ShAmtVal) + 1;
2660 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2661 }
2662 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2663 // When ShAmtC can be shifted losslessly:
2664 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2665 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2666 APInt ShiftedC = C.shl(shiftAmt: ShAmtVal);
2667 if (ShiftedC.ashr(ShiftAmt: ShAmtVal) == C)
2668 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2669 }
2670 if (Pred == CmpInst::ICMP_SGT) {
2671 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2672 APInt ShiftedC = (C + 1).shl(shiftAmt: ShAmtVal) - 1;
2673 if (!C.isMaxSignedValue() && !(C + 1).shl(shiftAmt: ShAmtVal).isMinSignedValue() &&
2674 (ShiftedC + 1).ashr(ShiftAmt: ShAmtVal) == (C + 1))
2675 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2676 }
2677 if (Pred == CmpInst::ICMP_UGT) {
2678 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2679 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2680 // clause accounts for that pattern.
2681 APInt ShiftedC = (C + 1).shl(shiftAmt: ShAmtVal) - 1;
2682 if ((ShiftedC + 1).ashr(ShiftAmt: ShAmtVal) == (C + 1) ||
2683 (C + 1).shl(shiftAmt: ShAmtVal).isMinSignedValue())
2684 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2685 }
2686
2687 // If the compare constant has significant bits above the lowest sign-bit,
2688 // then convert an unsigned cmp to a test of the sign-bit:
2689 // (ashr X, ShiftC) u> C --> X s< 0
2690 // (ashr X, ShiftC) u< C --> X s> -1
2691 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2692 if (Pred == CmpInst::ICMP_UGT) {
2693 return new ICmpInst(CmpInst::ICMP_SLT, X,
2694 ConstantInt::getNullValue(Ty: ShrTy));
2695 }
2696 if (Pred == CmpInst::ICMP_ULT) {
2697 return new ICmpInst(CmpInst::ICMP_SGT, X,
2698 ConstantInt::getAllOnesValue(Ty: ShrTy));
2699 }
2700 }
2701 } else if (!IsAShr) {
2702 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2703 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2704 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2705 APInt ShiftedC = C.shl(shiftAmt: ShAmtVal);
2706 if (ShiftedC.lshr(shiftAmt: ShAmtVal) == C)
2707 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2708 }
2709 if (Pred == CmpInst::ICMP_UGT) {
2710 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2711 APInt ShiftedC = (C + 1).shl(shiftAmt: ShAmtVal) - 1;
2712 if ((ShiftedC + 1).lshr(shiftAmt: ShAmtVal) == (C + 1))
2713 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2714 }
2715 }
2716
2717 if (!Cmp.isEquality())
2718 return nullptr;
2719
2720 // Handle equality comparisons of shift-by-constant.
2721
2722 // If the comparison constant changes with the shift, the comparison cannot
2723 // succeed (bits of the comparison constant cannot match the shifted value).
2724 // This should be known by InstSimplify and already be folded to true/false.
2725 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2726 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2727 "Expected icmp+shr simplify did not occur.");
2728
2729 // If the bits shifted out are known zero, compare the unshifted value:
2730 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2731 if (Shr->isExact())
2732 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: C << ShAmtVal));
2733
2734 if (Shr->hasOneUse()) {
2735 // Canonicalize the shift into an 'and':
2736 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2737 APInt Val(APInt::getHighBitsSet(numBits: TypeBits, hiBitsSet: TypeBits - ShAmtVal));
2738 Constant *Mask = ConstantInt::get(Ty: ShrTy, V: Val);
2739 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask, Name: Shr->getName() + ".mask");
2740 return new ICmpInst(Pred, And, ConstantInt::get(Ty: ShrTy, V: C << ShAmtVal));
2741 }
2742
2743 return nullptr;
2744}
2745
2746Instruction *InstCombinerImpl::foldICmpSRemConstant(ICmpInst &Cmp,
2747 BinaryOperator *SRem,
2748 const APInt &C) {
2749 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2750 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT) {
2751 // Canonicalize unsigned predicates to signed:
2752 // (X s% DivisorC) u> C -> (X s% DivisorC) s< 0
2753 // iff (C s< 0 ? ~C : C) u>= abs(DivisorC)-1
2754 // (X s% DivisorC) u< C+1 -> (X s% DivisorC) s> -1
2755 // iff (C+1 s< 0 ? ~C : C) u>= abs(DivisorC)-1
2756
2757 const APInt *DivisorC;
2758 if (!match(V: SRem->getOperand(i_nocapture: 1), P: m_APInt(Res&: DivisorC)))
2759 return nullptr;
2760 if (DivisorC->isZero())
2761 return nullptr;
2762
2763 APInt NormalizedC = C;
2764 if (Pred == ICmpInst::ICMP_ULT) {
2765 assert(!NormalizedC.isZero() &&
2766 "ult X, 0 should have been simplified already.");
2767 --NormalizedC;
2768 }
2769 if (C.isNegative())
2770 NormalizedC.flipAllBits();
2771 if (!NormalizedC.uge(RHS: DivisorC->abs() - 1))
2772 return nullptr;
2773
2774 Type *Ty = SRem->getType();
2775 if (Pred == ICmpInst::ICMP_UGT)
2776 return new ICmpInst(ICmpInst::ICMP_SLT, SRem,
2777 ConstantInt::getNullValue(Ty));
2778 return new ICmpInst(ICmpInst::ICMP_SGT, SRem,
2779 ConstantInt::getAllOnesValue(Ty));
2780 }
2781 // Match an 'is positive' or 'is negative' comparison of remainder by a
2782 // constant power-of-2 value:
2783 // (X % pow2C) sgt/slt 0
2784 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2785 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2786 return nullptr;
2787
2788 // TODO: The one-use check is standard because we do not typically want to
2789 // create longer instruction sequences, but this might be a special-case
2790 // because srem is not good for analysis or codegen.
2791 if (!SRem->hasOneUse())
2792 return nullptr;
2793
2794 const APInt *DivisorC;
2795 if (!match(V: SRem->getOperand(i_nocapture: 1), P: m_Power2(V&: DivisorC)))
2796 return nullptr;
2797
2798 // For cmp_sgt/cmp_slt only zero valued C is handled.
2799 // For cmp_eq/cmp_ne only positive valued C is handled.
2800 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2801 !C.isZero()) ||
2802 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2803 !C.isStrictlyPositive()))
2804 return nullptr;
2805
2806 // Mask off the sign bit and the modulo bits (low-bits).
2807 Type *Ty = SRem->getType();
2808 APInt SignMask = APInt::getSignMask(BitWidth: Ty->getScalarSizeInBits());
2809 Constant *MaskC = ConstantInt::get(Ty, V: SignMask | (*DivisorC - 1));
2810 Value *And = Builder.CreateAnd(LHS: SRem->getOperand(i_nocapture: 0), RHS: MaskC);
2811
2812 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2813 return new ICmpInst(Pred, And, ConstantInt::get(Ty, V: C));
2814
2815 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2816 // bit is set. Example:
2817 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2818 if (Pred == ICmpInst::ICMP_SGT)
2819 return new ICmpInst(ICmpInst::ICMP_SGT, And, ConstantInt::getNullValue(Ty));
2820
2821 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2822 // bit is set. Example:
2823 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2824 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, V: SignMask));
2825}
2826
2827/// Fold icmp (udiv X, Y), C.
2828Instruction *InstCombinerImpl::foldICmpUDivConstant(ICmpInst &Cmp,
2829 BinaryOperator *UDiv,
2830 const APInt &C) {
2831 ICmpInst::Predicate Pred = Cmp.getPredicate();
2832 Value *X = UDiv->getOperand(i_nocapture: 0);
2833 Value *Y = UDiv->getOperand(i_nocapture: 1);
2834 Type *Ty = UDiv->getType();
2835
2836 const APInt *C2;
2837 if (!match(V: X, P: m_APInt(Res&: C2)))
2838 return nullptr;
2839
2840 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2841
2842 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2843 if (Pred == ICmpInst::ICMP_UGT) {
2844 assert(!C.isMaxValue() &&
2845 "icmp ugt X, UINT_MAX should have been simplified already.");
2846 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2847 ConstantInt::get(Ty, V: C2->udiv(RHS: C + 1)));
2848 }
2849
2850 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2851 if (Pred == ICmpInst::ICMP_ULT) {
2852 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2853 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2854 ConstantInt::get(Ty, V: C2->udiv(RHS: C)));
2855 }
2856
2857 return nullptr;
2858}
2859
2860/// Fold icmp ({su}div X, Y), C.
2861Instruction *InstCombinerImpl::foldICmpDivConstant(ICmpInst &Cmp,
2862 BinaryOperator *Div,
2863 const APInt &C) {
2864 ICmpInst::Predicate Pred = Cmp.getPredicate();
2865 Value *X = Div->getOperand(i_nocapture: 0);
2866 Value *Y = Div->getOperand(i_nocapture: 1);
2867 Type *Ty = Div->getType();
2868 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2869
2870 // If unsigned division and the compare constant is bigger than
2871 // UMAX/2 (negative), there's only one pair of values that satisfies an
2872 // equality check, so eliminate the division:
2873 // (X u/ Y) == C --> (X == C) && (Y == 1)
2874 // (X u/ Y) != C --> (X != C) || (Y != 1)
2875 // Similarly, if signed division and the compare constant is exactly SMIN:
2876 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2877 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2878 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2879 (!DivIsSigned || C.isMinSignedValue())) {
2880 Value *XBig = Builder.CreateICmp(P: Pred, LHS: X, RHS: ConstantInt::get(Ty, V: C));
2881 Value *YOne = Builder.CreateICmp(P: Pred, LHS: Y, RHS: ConstantInt::get(Ty, V: 1));
2882 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2883 return BinaryOperator::Create(Op: Logic, S1: XBig, S2: YOne);
2884 }
2885
2886 // Fold: icmp pred ([us]div X, C2), C -> range test
2887 // Fold this div into the comparison, producing a range check.
2888 // Determine, based on the divide type, what the range is being
2889 // checked. If there is an overflow on the low or high side, remember
2890 // it, otherwise compute the range [low, hi) bounding the new value.
2891 // See: InsertRangeTest above for the kinds of replacements possible.
2892 const APInt *C2;
2893 if (!match(V: Y, P: m_APInt(Res&: C2)))
2894 return nullptr;
2895
2896 // FIXME: If the operand types don't match the type of the divide
2897 // then don't attempt this transform. The code below doesn't have the
2898 // logic to deal with a signed divide and an unsigned compare (and
2899 // vice versa). This is because (x /s C2) <s C produces different
2900 // results than (x /s C2) <u C or (x /u C2) <s C or even
2901 // (x /u C2) <u C. Simply casting the operands and result won't
2902 // work. :( The if statement below tests that condition and bails
2903 // if it finds it.
2904 // However, when the divisor is a positive constant and the dividend is
2905 // known non-negative, sdiv is equivalent to udiv, so we can lower
2906 // DivIsSigned and proceed through the unsigned path.
2907 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) {
2908 if (!DivIsSigned || !C2->isStrictlyPositive() ||
2909 !isKnownNonNegative(V: X, SQ: SQ.getWithInstruction(I: &Cmp)))
2910 return nullptr;
2911 DivIsSigned = false;
2912 }
2913
2914 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2915 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2916 // division-by-constant cases should be present, we can not assert that they
2917 // have happened before we reach this icmp instruction.
2918 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2919 return nullptr;
2920
2921 // Compute Prod = C * C2. We are essentially solving an equation of
2922 // form X / C2 = C. We solve for X by multiplying C2 and C.
2923 // By solving for X, we can turn this into a range check instead of computing
2924 // a divide.
2925 APInt Prod = C * *C2;
2926
2927 // Determine if the product overflows by seeing if the product is not equal to
2928 // the divide. Make sure we do the same kind of divide as in the LHS
2929 // instruction that we're folding.
2930 bool ProdOV = (DivIsSigned ? Prod.sdiv(RHS: *C2) : Prod.udiv(RHS: *C2)) != C;
2931
2932 // If the division is known to be exact, then there is no remainder from the
2933 // divide, so the covered range size is unit, otherwise it is the divisor.
2934 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2935
2936 // Figure out the interval that is being checked. For example, a comparison
2937 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2938 // Compute this interval based on the constants involved and the signedness of
2939 // the compare/divide. This computes a half-open interval, keeping track of
2940 // whether either value in the interval overflows. After analysis each
2941 // overflow variable is set to 0 if it's corresponding bound variable is valid
2942 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2943 int LoOverflow = 0, HiOverflow = 0;
2944 APInt LoBound, HiBound;
2945
2946 if (!DivIsSigned) { // udiv
2947 // e.g. X/5 op 3 --> [15, 20)
2948 LoBound = Prod;
2949 HiOverflow = LoOverflow = ProdOV;
2950 if (!HiOverflow) {
2951 // If this is not an exact divide, then many values in the range collapse
2952 // to the same result value.
2953 HiOverflow = addWithOverflow(Result&: HiBound, In1: LoBound, In2: RangeSize, IsSigned: false);
2954 }
2955 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2956 if (C.isZero()) { // (X / pos) op 0
2957 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2958 LoBound = -(RangeSize - 1);
2959 HiBound = RangeSize;
2960 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2961 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2962 HiOverflow = LoOverflow = ProdOV;
2963 if (!HiOverflow)
2964 HiOverflow = addWithOverflow(Result&: HiBound, In1: Prod, In2: RangeSize, IsSigned: true);
2965 } else { // (X / pos) op neg
2966 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2967 HiBound = Prod + 1;
2968 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2969 if (!LoOverflow) {
2970 APInt DivNeg = -RangeSize;
2971 LoOverflow = addWithOverflow(Result&: LoBound, In1: HiBound, In2: DivNeg, IsSigned: true) ? -1 : 0;
2972 }
2973 }
2974 } else if (C2->isNegative()) { // Divisor is < 0.
2975 if (Div->isExact())
2976 RangeSize.negate();
2977 if (C.isZero()) { // (X / neg) op 0
2978 // e.g. X/-5 op 0 --> [-4, 5)
2979 LoBound = RangeSize + 1;
2980 HiBound = -RangeSize;
2981 if (HiBound == *C2) { // -INTMIN = INTMIN
2982 HiOverflow = 1; // [INTMIN+1, overflow)
2983 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2984 }
2985 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2986 // e.g. X/-5 op 3 --> [-19, -14)
2987 HiBound = Prod + 1;
2988 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2989 if (!LoOverflow)
2990 LoOverflow =
2991 addWithOverflow(Result&: LoBound, In1: HiBound, In2: RangeSize, IsSigned: true) ? -1 : 0;
2992 } else { // (X / neg) op neg
2993 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2994 LoOverflow = HiOverflow = ProdOV;
2995 if (!HiOverflow)
2996 HiOverflow = subWithOverflow(Result&: HiBound, In1: Prod, In2: RangeSize, IsSigned: true);
2997 }
2998
2999 // Dividing by a negative swaps the condition. LT <-> GT
3000 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
3001 }
3002
3003 switch (Pred) {
3004 default:
3005 llvm_unreachable("Unhandled icmp predicate!");
3006 case ICmpInst::ICMP_EQ:
3007 if (LoOverflow && HiOverflow)
3008 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
3009 if (HiOverflow)
3010 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3011 X, ConstantInt::get(Ty, V: LoBound));
3012 if (LoOverflow)
3013 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3014 X, ConstantInt::get(Ty, V: HiBound));
3015 return replaceInstUsesWith(
3016 I&: Cmp, V: insertRangeTest(V: X, Lo: LoBound, Hi: HiBound, isSigned: DivIsSigned, Inside: true));
3017 case ICmpInst::ICMP_NE:
3018 if (LoOverflow && HiOverflow)
3019 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
3020 if (HiOverflow)
3021 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3022 X, ConstantInt::get(Ty, V: LoBound));
3023 if (LoOverflow)
3024 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3025 X, ConstantInt::get(Ty, V: HiBound));
3026 return replaceInstUsesWith(
3027 I&: Cmp, V: insertRangeTest(V: X, Lo: LoBound, Hi: HiBound, isSigned: DivIsSigned, Inside: false));
3028 case ICmpInst::ICMP_ULT:
3029 case ICmpInst::ICMP_SLT:
3030 if (LoOverflow == +1) // Low bound is greater than input range.
3031 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
3032 if (LoOverflow == -1) // Low bound is less than input range.
3033 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
3034 return new ICmpInst(Pred, X, ConstantInt::get(Ty, V: LoBound));
3035 case ICmpInst::ICMP_UGT:
3036 case ICmpInst::ICMP_SGT:
3037 if (HiOverflow == +1) // High bound greater than input range.
3038 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
3039 if (HiOverflow == -1) // High bound less than input range.
3040 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
3041 if (Pred == ICmpInst::ICMP_UGT)
3042 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, V: HiBound));
3043 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, V: HiBound));
3044 }
3045
3046 return nullptr;
3047}
3048
3049/// Fold icmp (sub X, Y), C.
3050Instruction *InstCombinerImpl::foldICmpSubConstant(ICmpInst &Cmp,
3051 BinaryOperator *Sub,
3052 const APInt &C) {
3053 Value *X = Sub->getOperand(i_nocapture: 0), *Y = Sub->getOperand(i_nocapture: 1);
3054 ICmpInst::Predicate Pred = Cmp.getPredicate();
3055 Type *Ty = Sub->getType();
3056
3057 // (X - (X urem D)) is D*(X/D), a multiple of D, so it is u> C exactly when
3058 // X u>= D (for C u< D), and u< C exactly when X u< D (for 0 u< C u<= D):
3059 // icmp ugt (sub X, (urem X, D)), C --> icmp ugt X, D-1
3060 // icmp ult (sub X, (urem X, D)), C --> icmp ult X, D
3061 const APInt *D;
3062 if (match(V: Y, P: m_URem(L: m_Specific(V: X), R: m_APInt(Res&: D))) && !D->isZero()) {
3063 if (Pred == ICmpInst::ICMP_UGT && C.ult(RHS: *D))
3064 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, V: *D - 1));
3065 if (Pred == ICmpInst::ICMP_ULT && !C.isZero() && C.ule(RHS: *D))
3066 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, V: *D));
3067 }
3068
3069 // (SubC - Y) == C) --> Y == (SubC - C)
3070 // (SubC - Y) != C) --> Y != (SubC - C)
3071 Constant *SubC;
3072 if (Cmp.isEquality() && match(V: X, P: m_ImmConstant(C&: SubC))) {
3073 return new ICmpInst(Pred, Y,
3074 ConstantExpr::getSub(C1: SubC, C2: ConstantInt::get(Ty, V: C)));
3075 }
3076
3077 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
3078 const APInt *C2;
3079 APInt SubResult;
3080 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
3081 bool HasNSW = Sub->hasNoSignedWrap();
3082 bool HasNUW = Sub->hasNoUnsignedWrap();
3083 if (match(V: X, P: m_APInt(Res&: C2)) &&
3084 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
3085 !subWithOverflow(Result&: SubResult, In1: *C2, In2: C, IsSigned: Cmp.isSigned()))
3086 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, V: SubResult));
3087
3088 // X - Y == 0 --> X == Y.
3089 // X - Y != 0 --> X != Y.
3090 // TODO: We allow this with multiple uses as long as the other uses are not
3091 // in phis. The phi use check is guarding against a codegen regression
3092 // for a loop test. If the backend could undo this (and possibly
3093 // subsequent transforms), we would not need this hack.
3094 if (Cmp.isEquality() && C.isZero() &&
3095 none_of(Range: (Sub->users()), P: [](const User *U) { return isa<PHINode>(Val: U); }))
3096 return new ICmpInst(Pred, X, Y);
3097
3098 // The following transforms are only worth it if the only user of the subtract
3099 // is the icmp.
3100 // TODO: This is an artificial restriction for all of the transforms below
3101 // that only need a single replacement icmp. Can these use the phi test
3102 // like the transform above here?
3103 if (!Sub->hasOneUse())
3104 return nullptr;
3105
3106 if (Sub->hasNoSignedWrap()) {
3107 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
3108 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3109 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3110
3111 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
3112 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
3113 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3114
3115 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
3116 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
3117 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3118
3119 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
3120 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3121 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3122 }
3123
3124 if (!match(V: X, P: m_APInt(Res&: C2)))
3125 return nullptr;
3126
3127 // C2 - Y <u C -> (Y | (C - 1)) == C2
3128 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
3129 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
3130 (*C2 & (C - 1)) == (C - 1))
3131 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(LHS: Y, RHS: C - 1), X);
3132
3133 // C2 - Y >u C -> (Y | C) != C2
3134 // iff C2 & C == C and C + 1 is a power of 2
3135 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
3136 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(LHS: Y, RHS: C), X);
3137
3138 // We have handled special cases that reduce.
3139 // Canonicalize any remaining sub to add as:
3140 // (C2 - Y) > C --> (Y + ~C2) < ~C
3141 Value *Add = Builder.CreateAdd(LHS: Y, RHS: ConstantInt::get(Ty, V: ~(*C2)), Name: "notsub",
3142 HasNUW, HasNSW);
3143 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, V: ~C));
3144}
3145
3146static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
3147 Value *Op1, IRBuilderBase &Builder,
3148 bool HasOneUse) {
3149 auto FoldConstant = [&](bool Val) {
3150 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3151 if (Op0->getType()->isVectorTy())
3152 Res = ConstantVector::getSplat(
3153 EC: cast<VectorType>(Val: Op0->getType())->getElementCount(), Elt: Res);
3154 return Res;
3155 };
3156
3157 switch (Table.to_ulong()) {
3158 case 0: // 0 0 0 0
3159 return FoldConstant(false);
3160 case 1: // 0 0 0 1
3161 return HasOneUse ? Builder.CreateNot(V: Builder.CreateOr(LHS: Op0, RHS: Op1)) : nullptr;
3162 case 2: // 0 0 1 0
3163 return HasOneUse ? Builder.CreateAnd(LHS: Builder.CreateNot(V: Op0), RHS: Op1) : nullptr;
3164 case 3: // 0 0 1 1
3165 return Builder.CreateNot(V: Op0);
3166 case 4: // 0 1 0 0
3167 return HasOneUse ? Builder.CreateAnd(LHS: Op0, RHS: Builder.CreateNot(V: Op1)) : nullptr;
3168 case 5: // 0 1 0 1
3169 return Builder.CreateNot(V: Op1);
3170 case 6: // 0 1 1 0
3171 return Builder.CreateXor(LHS: Op0, RHS: Op1);
3172 case 7: // 0 1 1 1
3173 return HasOneUse ? Builder.CreateNot(V: Builder.CreateAnd(LHS: Op0, RHS: Op1)) : nullptr;
3174 case 8: // 1 0 0 0
3175 return Builder.CreateAnd(LHS: Op0, RHS: Op1);
3176 case 9: // 1 0 0 1
3177 return HasOneUse ? Builder.CreateNot(V: Builder.CreateXor(LHS: Op0, RHS: Op1)) : nullptr;
3178 case 10: // 1 0 1 0
3179 return Op1;
3180 case 11: // 1 0 1 1
3181 return HasOneUse ? Builder.CreateOr(LHS: Builder.CreateNot(V: Op0), RHS: Op1) : nullptr;
3182 case 12: // 1 1 0 0
3183 return Op0;
3184 case 13: // 1 1 0 1
3185 return HasOneUse ? Builder.CreateOr(LHS: Op0, RHS: Builder.CreateNot(V: Op1)) : nullptr;
3186 case 14: // 1 1 1 0
3187 return Builder.CreateOr(LHS: Op0, RHS: Op1);
3188 case 15: // 1 1 1 1
3189 return FoldConstant(true);
3190 default:
3191 llvm_unreachable("Invalid Operation");
3192 }
3193 return nullptr;
3194}
3195
3196Instruction *InstCombinerImpl::foldICmpBinOpWithConstantViaTruthTable(
3197 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3198 Value *A, *B;
3199 Constant *C1, *C2, *C3, *C4;
3200 if (!match(V: BO->getOperand(i_nocapture: 0),
3201 P: m_SelectLike(C: m_Value(V&: A), TrueC: m_Constant(C&: C1), FalseC: m_Constant(C&: C2))) ||
3202 !match(V: BO->getOperand(i_nocapture: 1),
3203 P: m_SelectLike(C: m_Value(V&: B), TrueC: m_Constant(C&: C3), FalseC: m_Constant(C&: C4))) ||
3204 Cmp.getType() != A->getType() || Cmp.getType() != B->getType())
3205 return nullptr;
3206
3207 std::bitset<4> Table;
3208 auto ComputeTable = [&](bool First, bool Second) -> std::optional<bool> {
3209 Constant *L = First ? C1 : C2;
3210 Constant *R = Second ? C3 : C4;
3211 if (auto *Res = ConstantFoldBinaryOpOperands(Opcode: BO->getOpcode(), LHS: L, RHS: R, DL)) {
3212 auto *Val = Res->getType()->isVectorTy() ? Res->getSplatValue() : Res;
3213 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val))
3214 return ICmpInst::compare(LHS: CI->getValue(), RHS: C, Pred: Cmp.getPredicate());
3215 }
3216 return std::nullopt;
3217 };
3218
3219 for (unsigned I = 0; I < 4; ++I) {
3220 bool First = (I >> 1) & 1;
3221 bool Second = I & 1;
3222 if (auto Res = ComputeTable(First, Second))
3223 Table[I] = *Res;
3224 else
3225 return nullptr;
3226 }
3227
3228 // Synthesize optimal logic.
3229 if (auto *Cond = createLogicFromTable(Table, Op0: A, Op1: B, Builder, HasOneUse: BO->hasOneUse()))
3230 return replaceInstUsesWith(I&: Cmp, V: Cond);
3231 return nullptr;
3232}
3233
3234/// Fold icmp (add X, Y), C.
3235Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp,
3236 BinaryOperator *Add,
3237 const APInt &C) {
3238 Value *Y = Add->getOperand(i_nocapture: 1);
3239 Value *X = Add->getOperand(i_nocapture: 0);
3240 const CmpPredicate Pred = Cmp.getCmpPredicate();
3241
3242 // icmp ult (add nuw A, (lshr A, ShAmtC)), C --> icmp ult A, C
3243 // when C <= (1 << ShAmtC).
3244 const APInt *ShAmtC;
3245 Value *A;
3246 unsigned BitWidth = C.getBitWidth();
3247 if (Pred == ICmpInst::ICMP_ULT &&
3248 match(V: Add,
3249 P: m_c_NUWAdd(L: m_Value(V&: A), R: m_LShr(L: m_Deferred(V: A), R: m_APInt(Res&: ShAmtC)))) &&
3250 ShAmtC->ult(RHS: BitWidth) &&
3251 C.ule(RHS: APInt::getOneBitSet(numBits: BitWidth, BitNo: ShAmtC->getZExtValue())))
3252 return new ICmpInst(Pred, A, ConstantInt::get(Ty: A->getType(), V: C));
3253
3254 const APInt *C2;
3255 if (Cmp.isEquality() || !match(V: Y, P: m_APInt(Res&: C2)))
3256 return nullptr;
3257
3258 // Fold icmp pred (add X, C2), C.
3259 Type *Ty = Add->getType();
3260
3261 // If the add does not wrap, we can always adjust the compare by subtracting
3262 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3263 // have been canonicalized to SGT/SLT/UGT/ULT.
3264 if (Add->hasNoUnsignedWrap() &&
3265 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT)) {
3266 bool Overflow;
3267 APInt NewC = C.usub_ov(RHS: *C2, Overflow);
3268 // If there is overflow, the result must be true or false.
3269 if (!Overflow)
3270 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
3271 return new ICmpInst(Pred, X, ConstantInt::get(Ty, V: NewC));
3272 }
3273
3274 CmpInst::Predicate ChosenPred = Pred.getPreferredSignedPredicate();
3275
3276 if (Add->hasNoSignedWrap() &&
3277 (ChosenPred == ICmpInst::ICMP_SGT || ChosenPred == ICmpInst::ICMP_SLT)) {
3278 bool Overflow;
3279 APInt NewC = C.ssub_ov(RHS: *C2, Overflow);
3280 if (!Overflow)
3281 // icmp samesign ugt/ult (add nsw X, C2), C
3282 // -> icmp sgt/slt X, (C - C2)
3283 return new ICmpInst(ChosenPred, X, ConstantInt::get(Ty, V: NewC));
3284 }
3285
3286 if (ICmpInst::isUnsigned(Pred) && Add->hasNoSignedWrap() &&
3287 C.isNonNegative() && (C - *C2).isNonNegative() &&
3288 computeConstantRange(V: X, /*ForSigned=*/true, SQ: SQ.getWithInstruction(I: &Cmp))
3289 .add(Other: *C2)
3290 .isAllNonNegative())
3291 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), X,
3292 ConstantInt::get(Ty, V: C - *C2));
3293
3294 auto CR = ConstantRange::makeExactICmpRegion(Pred, Other: C).subtract(CI: *C2);
3295 const APInt &Upper = CR.getUpper();
3296 const APInt &Lower = CR.getLower();
3297 if (Cmp.isSigned()) {
3298 if (Lower.isSignMask())
3299 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, V: Upper));
3300 if (Upper.isSignMask())
3301 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, V: Lower));
3302 } else {
3303 if (Lower.isMinValue())
3304 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, V: Upper));
3305 if (Upper.isMinValue())
3306 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, V: Lower));
3307 }
3308
3309 // This set of folds is intentionally placed after folds that use no-wrapping
3310 // flags because those folds are likely better for later analysis/codegen.
3311 const APInt SMax = APInt::getSignedMaxValue(numBits: Ty->getScalarSizeInBits());
3312 const APInt SMin = APInt::getSignedMinValue(numBits: Ty->getScalarSizeInBits());
3313
3314 // Fold compare with offset to opposite sign compare if it eliminates offset:
3315 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3316 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3317 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, V: -(*C2)));
3318
3319 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3320 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3321 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, V: ~(*C2)));
3322
3323 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3324 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3325 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, V: SMax - C));
3326
3327 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3328 if (Pred == CmpInst::ICMP_SLT && C == *C2)
3329 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, V: C ^ SMax));
3330
3331 // (X + -1) <u C --> X <=u C (if X is never null)
3332 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3333 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
3334 if (llvm::isKnownNonZero(V: X, Q))
3335 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, V: C));
3336 }
3337
3338 if (!Add->hasOneUse())
3339 return nullptr;
3340
3341 // X+C <u C2 -> (X & -C2) == C
3342 // iff C & (C2-1) == 0
3343 // C2 is a power of 2
3344 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3345 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(LHS: X, RHS: -C),
3346 ConstantExpr::getNeg(C: cast<Constant>(Val: Y)));
3347
3348 // X+C2 <u C -> (X & C) == 2C
3349 // iff C == -(C2)
3350 // C2 is a power of 2
3351 if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)
3352 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(LHS: X, RHS: C),
3353 ConstantInt::get(Ty, V: C * 2));
3354
3355 // X+C >u C2 -> (X & ~C2) != C
3356 // iff C & C2 == 0
3357 // C2+1 is a power of 2
3358 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3359 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(LHS: X, RHS: ~C),
3360 ConstantExpr::getNeg(C: cast<Constant>(Val: Y)));
3361
3362 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3363 // to the ult form.
3364 // X+C2 >u C -> X+(C2-C-1) <u ~C
3365 if (Pred == ICmpInst::ICMP_UGT)
3366 return new ICmpInst(ICmpInst::ICMP_ULT,
3367 Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: *C2 - C - 1)),
3368 ConstantInt::get(Ty, V: ~C));
3369
3370 // zext(V) + C2 pred C -> V + C3 pred' C4
3371 Value *V;
3372 if (match(V: X, P: m_ZExt(Op: m_Value(V)))) {
3373 Type *NewCmpTy = V->getType();
3374 unsigned NewCmpBW = NewCmpTy->getScalarSizeInBits();
3375 if (shouldChangeType(From: Ty, To: NewCmpTy)) {
3376 ConstantRange SrcCR = CR.truncate(BitWidth: NewCmpBW, NoWrapKind: TruncInst::NoUnsignedWrap);
3377 CmpInst::Predicate EquivPred;
3378 APInt EquivInt;
3379 APInt EquivOffset;
3380
3381 SrcCR.getEquivalentICmp(Pred&: EquivPred, RHS&: EquivInt, Offset&: EquivOffset);
3382 return new ICmpInst(
3383 EquivPred,
3384 EquivOffset.isZero()
3385 ? V
3386 : Builder.CreateAdd(LHS: V, RHS: ConstantInt::get(Ty: NewCmpTy, V: EquivOffset)),
3387 ConstantInt::get(Ty: NewCmpTy, V: EquivInt));
3388 }
3389 }
3390
3391 return nullptr;
3392}
3393
3394bool InstCombinerImpl::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS,
3395 Value *&RHS, ConstantInt *&Less,
3396 ConstantInt *&Equal,
3397 ConstantInt *&Greater) {
3398 // TODO: Generalize this to work with other comparison idioms or ensure
3399 // they get canonicalized into this form.
3400
3401 // select i1 (a == b),
3402 // i32 Equal,
3403 // i32 (select i1 (a < b), i32 Less, i32 Greater)
3404 // where Equal, Less and Greater are placeholders for any three constants.
3405 CmpPredicate PredA;
3406 if (!match(V: SI->getCondition(), P: m_ICmp(Pred&: PredA, L: m_Value(V&: LHS), R: m_Value(V&: RHS))) ||
3407 !ICmpInst::isEquality(P: PredA))
3408 return false;
3409 Value *EqualVal = SI->getTrueValue();
3410 Value *UnequalVal = SI->getFalseValue();
3411 // We still can get non-canonical predicate here, so canonicalize.
3412 if (PredA == ICmpInst::ICMP_NE)
3413 std::swap(a&: EqualVal, b&: UnequalVal);
3414 if (!match(V: EqualVal, P: m_ConstantInt(CI&: Equal)))
3415 return false;
3416 CmpPredicate PredB;
3417 Value *LHS2, *RHS2;
3418 if (!match(V: UnequalVal, P: m_Select(C: m_ICmp(Pred&: PredB, L: m_Value(V&: LHS2), R: m_Value(V&: RHS2)),
3419 L: m_ConstantInt(CI&: Less), R: m_ConstantInt(CI&: Greater))))
3420 return false;
3421 // We can get predicate mismatch here, so canonicalize if possible:
3422 // First, ensure that 'LHS' match.
3423 if (LHS2 != LHS) {
3424 // x sgt y <--> y slt x
3425 std::swap(a&: LHS2, b&: RHS2);
3426 PredB = ICmpInst::getSwappedPredicate(pred: PredB);
3427 }
3428 if (LHS2 != LHS)
3429 return false;
3430 // We also need to canonicalize 'RHS'.
3431 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(Val: RHS2)) {
3432 // x sgt C-1 <--> x sge C <--> not(x slt C)
3433 auto FlippedStrictness =
3434 getFlippedStrictnessPredicateAndConstant(Pred: PredB, C: cast<Constant>(Val: RHS2));
3435 if (!FlippedStrictness)
3436 return false;
3437 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3438 "basic correctness failure");
3439 RHS2 = FlippedStrictness->second;
3440 // And kind-of perform the result swap.
3441 std::swap(a&: Less, b&: Greater);
3442 PredB = ICmpInst::ICMP_SLT;
3443 }
3444 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3445}
3446
3447Instruction *InstCombinerImpl::foldICmpSelectConstant(ICmpInst &Cmp,
3448 SelectInst *Select,
3449 ConstantInt *C) {
3450
3451 assert(C && "Cmp RHS should be a constant int!");
3452 // If we're testing a constant value against the result of a three way
3453 // comparison, the result can be expressed directly in terms of the
3454 // original values being compared. Note: We could possibly be more
3455 // aggressive here and remove the hasOneUse test. The original select is
3456 // really likely to simplify or sink when we remove a test of the result.
3457 Value *OrigLHS, *OrigRHS;
3458 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3459 if (Cmp.hasOneUse() &&
3460 matchThreeWayIntCompare(SI: Select, LHS&: OrigLHS, RHS&: OrigRHS, Less&: C1LessThan, Equal&: C2Equal,
3461 Greater&: C3GreaterThan)) {
3462 assert(C1LessThan && C2Equal && C3GreaterThan);
3463
3464 bool TrueWhenLessThan = ICmpInst::compare(
3465 LHS: C1LessThan->getValue(), RHS: C->getValue(), Pred: Cmp.getPredicate());
3466 bool TrueWhenEqual = ICmpInst::compare(LHS: C2Equal->getValue(), RHS: C->getValue(),
3467 Pred: Cmp.getPredicate());
3468 bool TrueWhenGreaterThan = ICmpInst::compare(
3469 LHS: C3GreaterThan->getValue(), RHS: C->getValue(), Pred: Cmp.getPredicate());
3470
3471 // This generates the new instruction that will replace the original Cmp
3472 // Instruction. Instead of enumerating the various combinations when
3473 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3474 // false, we rely on chaining of ORs and future passes of InstCombine to
3475 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3476
3477 // When none of the three constants satisfy the predicate for the RHS (C),
3478 // the entire original Cmp can be simplified to a false.
3479 Value *Cond = Builder.getFalse();
3480 if (TrueWhenLessThan)
3481 Cond = Builder.CreateOr(
3482 LHS: Cond, RHS: Builder.CreateICmp(P: ICmpInst::ICMP_SLT, LHS: OrigLHS, RHS: OrigRHS));
3483 if (TrueWhenEqual)
3484 Cond = Builder.CreateOr(
3485 LHS: Cond, RHS: Builder.CreateICmp(P: ICmpInst::ICMP_EQ, LHS: OrigLHS, RHS: OrigRHS));
3486 if (TrueWhenGreaterThan)
3487 Cond = Builder.CreateOr(
3488 LHS: Cond, RHS: Builder.CreateICmp(P: ICmpInst::ICMP_SGT, LHS: OrigLHS, RHS: OrigRHS));
3489
3490 return replaceInstUsesWith(I&: Cmp, V: Cond);
3491 }
3492 return nullptr;
3493}
3494
3495Instruction *InstCombinerImpl::foldICmpBitCast(ICmpInst &Cmp) {
3496 auto *Bitcast = dyn_cast<BitCastInst>(Val: Cmp.getOperand(i_nocapture: 0));
3497 if (!Bitcast)
3498 return nullptr;
3499
3500 ICmpInst::Predicate Pred = Cmp.getPredicate();
3501 Value *Op1 = Cmp.getOperand(i_nocapture: 1);
3502 Value *BCSrcOp = Bitcast->getOperand(i_nocapture: 0);
3503 Type *SrcType = Bitcast->getSrcTy();
3504 Type *DstType = Bitcast->getType();
3505
3506 // Make sure the bitcast doesn't change between scalar and vector and
3507 // doesn't change the number of vector elements.
3508 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3509 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3510 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3511 Value *X;
3512 if (match(V: BCSrcOp, P: m_SIToFP(Op: m_Value(V&: X)))) {
3513 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3514 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3515 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3516 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3517 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3518 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3519 match(V: Op1, P: m_Zero()))
3520 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: X->getType()));
3521
3522 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3523 if (Pred == ICmpInst::ICMP_SLT && match(V: Op1, P: m_One()))
3524 return new ICmpInst(Pred, X, ConstantInt::get(Ty: X->getType(), V: 1));
3525
3526 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3527 if (Pred == ICmpInst::ICMP_SGT && match(V: Op1, P: m_AllOnes()))
3528 return new ICmpInst(Pred, X,
3529 ConstantInt::getAllOnesValue(Ty: X->getType()));
3530 }
3531
3532 // Zero-equality checks are preserved through unsigned floating-point casts:
3533 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3534 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3535 if (match(V: BCSrcOp, P: m_UIToFP(Op: m_Value(V&: X))))
3536 if (Cmp.isEquality() && match(V: Op1, P: m_Zero()))
3537 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: X->getType()));
3538
3539 const APInt *C;
3540 bool TrueIfSigned;
3541 if (match(V: Op1, P: m_APInt(Res&: C)) && Bitcast->hasOneUse()) {
3542 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3543 // the FP extend/truncate because that cast does not change the sign-bit.
3544 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3545 // The sign-bit is always the most significant bit in those types.
3546 if (isSignBitCheck(Pred, RHS: *C, TrueIfSigned) &&
3547 (match(V: BCSrcOp, P: m_FPExt(Op: m_Value(V&: X))) ||
3548 match(V: BCSrcOp, P: m_FPTrunc(Op: m_Value(V&: X))))) {
3549 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3550 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3551 Type *XType = X->getType();
3552
3553 // We can't currently handle Power style floating point operations here.
3554 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3555 Type *NewType = Builder.getIntNTy(N: XType->getScalarSizeInBits());
3556 if (auto *XVTy = dyn_cast<VectorType>(Val: XType))
3557 NewType = VectorType::get(ElementType: NewType, EC: XVTy->getElementCount());
3558 Value *NewBitcast = Builder.CreateBitCast(V: X, DestTy: NewType);
3559 if (TrueIfSigned)
3560 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3561 ConstantInt::getNullValue(Ty: NewType));
3562 else
3563 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3564 ConstantInt::getAllOnesValue(Ty: NewType));
3565 }
3566 }
3567
3568 // icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)
3569 Type *FPType = SrcType->getScalarType();
3570 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3571 Kind: Attribute::NoImplicitFloat) &&
3572 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3573 FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();
3574 if (Mask & (fcInf | fcZero)) {
3575 if (Pred == ICmpInst::ICMP_NE)
3576 Mask = ~Mask;
3577 return replaceInstUsesWith(I&: Cmp,
3578 V: Builder.createIsFPClass(FPNum: BCSrcOp, Test: Mask));
3579 }
3580 }
3581 }
3582 }
3583
3584 const APInt *C;
3585 if (!match(V: Cmp.getOperand(i_nocapture: 1), P: m_APInt(Res&: C)) || !DstType->isIntegerTy() ||
3586 !SrcType->isIntOrIntVectorTy())
3587 return nullptr;
3588
3589 // If this is checking if all elements of a vector compare are set or not,
3590 // invert the casted vector equality compare and test if all compare
3591 // elements are clear or not. Compare against zero is generally easier for
3592 // analysis and codegen.
3593 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3594 // Example: are all elements equal? --> are zero elements not equal?
3595 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3596 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3597 if (Value *NotBCSrcOp =
3598 getFreelyInverted(V: BCSrcOp, WillInvertAllUses: BCSrcOp->hasOneUse(), Builder: &Builder)) {
3599 Value *Cast = Builder.CreateBitCast(V: NotBCSrcOp, DestTy: DstType);
3600 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(Ty: DstType));
3601 }
3602 }
3603
3604 // If this is checking if all elements of an extended vector are clear or not,
3605 // compare in a narrow type to eliminate the extend:
3606 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3607 Value *X;
3608 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3609 match(V: BCSrcOp, P: m_ZExtOrSExt(Op: m_Value(V&: X)))) {
3610 if (auto *VecTy = dyn_cast<FixedVectorType>(Val: X->getType())) {
3611 Type *NewType = Builder.getIntNTy(N: VecTy->getPrimitiveSizeInBits());
3612 Value *NewCast = Builder.CreateBitCast(V: X, DestTy: NewType);
3613 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(Ty: NewType));
3614 }
3615 }
3616
3617 // Folding: icmp <pred> iN X, C
3618 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3619 // and C is a splat of a K-bit pattern
3620 // and SC is a constant vector = <C', C', C', ..., C'>
3621 // Into:
3622 // %E = extractelement <M x iK> %vec, i32 C'
3623 // icmp <pred> iK %E, trunc(C)
3624 Value *Vec;
3625 ArrayRef<int> Mask;
3626 if (match(V: BCSrcOp, P: m_Shuffle(v1: m_Value(V&: Vec), v2: m_Undef(), mask: m_Mask(Mask)))) {
3627 // Check whether every element of Mask is the same constant
3628 if (all_equal(Range&: Mask)) {
3629 auto *VecTy = cast<VectorType>(Val: SrcType);
3630 auto *EltTy = cast<IntegerType>(Val: VecTy->getElementType());
3631 if (C->isSplat(SplatSizeInBits: EltTy->getBitWidth())) {
3632 // Fold the icmp based on the value of C
3633 // If C is M copies of an iK sized bit pattern,
3634 // then:
3635 // => %E = extractelement <N x iK> %vec, i64 Elem
3636 // icmp <pred> iK %SplatVal, <pattern>
3637 Value *Extract = Builder.CreateExtractElement(Vec, Idx: Mask[0]);
3638 Value *NewC = ConstantInt::get(Ty: EltTy, V: C->trunc(width: EltTy->getBitWidth()));
3639 return new ICmpInst(Pred, Extract, NewC);
3640 }
3641 }
3642 }
3643 return nullptr;
3644}
3645
3646/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3647/// where X is some kind of instruction.
3648Instruction *InstCombinerImpl::foldICmpInstWithConstant(ICmpInst &Cmp) {
3649 const APInt *C;
3650
3651 if (match(V: Cmp.getOperand(i_nocapture: 1), P: m_APInt(Res&: C))) {
3652 if (auto *BO = dyn_cast<BinaryOperator>(Val: Cmp.getOperand(i_nocapture: 0)))
3653 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, C: *C))
3654 return I;
3655
3656 if (auto *SI = dyn_cast<SelectInst>(Val: Cmp.getOperand(i_nocapture: 0)))
3657 // For now, we only support constant integers while folding the
3658 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3659 // similar to the cases handled by binary ops above.
3660 if (auto *ConstRHS = dyn_cast<ConstantInt>(Val: Cmp.getOperand(i_nocapture: 1)))
3661 if (Instruction *I = foldICmpSelectConstant(Cmp, Select: SI, C: ConstRHS))
3662 return I;
3663
3664 if (auto *TI = dyn_cast<TruncInst>(Val: Cmp.getOperand(i_nocapture: 0)))
3665 if (Instruction *I = foldICmpTruncConstant(Cmp, Trunc: TI, C: *C))
3666 return I;
3667
3668 if (auto *II = dyn_cast<IntrinsicInst>(Val: Cmp.getOperand(i_nocapture: 0)))
3669 if (Instruction *I = foldICmpIntrinsicWithConstant(ICI&: Cmp, II, C: *C))
3670 return I;
3671
3672 {
3673 // icmp slt/sgt (extractvalue (frexp X), 1), C -->
3674 // fcmp olt/oge (fabs X), 2^ExpVal
3675 // slt -> olt, ExpVal = C-1; sgt -> oge, ExpVal = C.
3676 Value *X;
3677 if (match(V: Cmp.getOperand(i_nocapture: 0),
3678 P: m_OneUse(SubPattern: m_ExtractValue<1>(
3679 V: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::frexp>(Ops: m_Value(V&: X))))))) {
3680 ICmpInst::Predicate Pred = Cmp.getPredicate();
3681 APInt Exp;
3682 FCmpInst::Predicate NewPred;
3683 bool ValidPred = true;
3684
3685 switch (Pred) {
3686 case ICmpInst::ICMP_SLT:
3687 NewPred = FCmpInst::FCMP_OLT;
3688 Exp = *C - 1;
3689 break;
3690 case ICmpInst::ICMP_SGT:
3691 NewPred = FCmpInst::FCMP_OGE;
3692 Exp = *C;
3693 break;
3694 default:
3695 ValidPred = false;
3696 break;
3697 }
3698
3699 if (ValidPred) {
3700 const fltSemantics &Sem =
3701 X->getType()->getScalarType()->getFltSemantics();
3702 int MaxExp = APFloat::semanticsMaxExponent(Sem);
3703
3704 if (!Exp.isNegative() && Exp.sle(RHS: MaxExp + 1) &&
3705 isKnownNeverInfOrNaN(V: X, SQ: SQ.getWithInstruction(I: &Cmp))) {
3706 int ExpVal = static_cast<int>(Exp.getSExtValue());
3707 APFloat CmpConst = scalbn(X: APFloat::getOne(Sem), Exp: ExpVal,
3708 RM: APFloat::rmNearestTiesToEven);
3709 Value *Fabs = Builder.CreateFAbs(V: X);
3710 return new FCmpInst(NewPred, Fabs,
3711 ConstantFP::get(Ty: X->getType(), V: CmpConst));
3712 }
3713 }
3714 }
3715 }
3716
3717 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3718 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3719 // TODO: This checks one-use, but that is not strictly necessary.
3720 Value *Cmp0 = Cmp.getOperand(i_nocapture: 0);
3721 Value *X, *Y;
3722 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3723 (match(V: Cmp0,
3724 P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::ssub_with_overflow>(
3725 Ops: m_Value(V&: X), Ops: m_Value(V&: Y)))) ||
3726 match(V: Cmp0,
3727 P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::usub_with_overflow>(
3728 Ops: m_Value(V&: X), Ops: m_Value(V&: Y))))))
3729 return new ICmpInst(Cmp.getPredicate(), X, Y);
3730 }
3731
3732 if (match(V: Cmp.getOperand(i_nocapture: 1), P: m_APIntAllowPoison(Res&: C)))
3733 return foldICmpInstWithConstantAllowPoison(Cmp, C: *C);
3734
3735 return nullptr;
3736}
3737
3738/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3739/// icmp eq/ne BO, C.
3740Instruction *InstCombinerImpl::foldICmpBinOpEqualityWithConstant(
3741 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3742 // TODO: Some of these folds could work with arbitrary constants, but this
3743 // function is limited to scalar and vector splat constants.
3744 if (!Cmp.isEquality())
3745 return nullptr;
3746
3747 ICmpInst::Predicate Pred = Cmp.getPredicate();
3748 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3749 Constant *RHS = cast<Constant>(Val: Cmp.getOperand(i_nocapture: 1));
3750 Value *BOp0 = BO->getOperand(i_nocapture: 0), *BOp1 = BO->getOperand(i_nocapture: 1);
3751
3752 switch (BO->getOpcode()) {
3753 case Instruction::SRem:
3754 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3755 if (C.isZero() && BO->hasOneUse()) {
3756 const APInt *BOC;
3757 if (match(V: BOp1, P: m_APInt(Res&: BOC)) && BOC->sgt(RHS: 1) && BOC->isPowerOf2()) {
3758 Value *NewRem = Builder.CreateURem(LHS: BOp0, RHS: BOp1, Name: BO->getName());
3759 return new ICmpInst(Pred, NewRem,
3760 Constant::getNullValue(Ty: BO->getType()));
3761 }
3762 }
3763 break;
3764 case Instruction::Add: {
3765 // (A + C2) == C --> A == (C - C2)
3766 // (A + C2) != C --> A != (C - C2)
3767 // TODO: Remove the one-use limitation? See discussion in D58633.
3768 if (Constant *C2 = dyn_cast<Constant>(Val: BOp1)) {
3769 if (BO->hasOneUse())
3770 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(C1: RHS, C2));
3771 } else if (C.isZero()) {
3772 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3773 // efficiently invertible, or if the add has just this one use.
3774 if (Value *NegVal = dyn_castNegVal(V: BOp1))
3775 return new ICmpInst(Pred, BOp0, NegVal);
3776 if (Value *NegVal = dyn_castNegVal(V: BOp0))
3777 return new ICmpInst(Pred, NegVal, BOp1);
3778 if (BO->hasOneUse()) {
3779 // (add nuw A, B) != 0 -> (or A, B) != 0
3780 if (match(V: BO, P: m_NUWAdd(L: m_Value(), R: m_Value()))) {
3781 Value *Or = Builder.CreateOr(LHS: BOp0, RHS: BOp1);
3782 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty: BO->getType()));
3783 }
3784 Value *Neg = Builder.CreateNeg(V: BOp1);
3785 Neg->takeName(V: BO);
3786 return new ICmpInst(Pred, BOp0, Neg);
3787 }
3788 }
3789 break;
3790 }
3791 case Instruction::Xor:
3792 if (Constant *BOC = dyn_cast<Constant>(Val: BOp1)) {
3793 // For the xor case, we can xor two constants together, eliminating
3794 // the explicit xor.
3795 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(C1: RHS, C2: BOC));
3796 } else if (C.isZero()) {
3797 // Replace ((xor A, B) != 0) with (A != B)
3798 return new ICmpInst(Pred, BOp0, BOp1);
3799 }
3800 break;
3801 case Instruction::Or: {
3802 const APInt *BOC;
3803 if (match(V: BOp1, P: m_APInt(Res&: BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3804 // Comparing if all bits outside of a constant mask are set?
3805 // Replace (X | C) == -1 with (X & ~C) == ~C.
3806 // This removes the -1 constant.
3807 Constant *NotBOC = ConstantExpr::getNot(C: cast<Constant>(Val: BOp1));
3808 Value *And = Builder.CreateAnd(LHS: BOp0, RHS: NotBOC);
3809 return new ICmpInst(Pred, And, NotBOC);
3810 }
3811 // (icmp eq (or (select cond, 0, NonZero), Other), 0)
3812 // -> (and cond, (icmp eq Other, 0))
3813 // (icmp ne (or (select cond, NonZero, 0), Other), 0)
3814 // -> (or cond, (icmp ne Other, 0))
3815 Value *Cond, *TV, *FV, *Other, *Sel;
3816 if (C.isZero() &&
3817 match(V: BO,
3818 P: m_OneUse(SubPattern: m_c_Or(L: m_CombineAnd(Ps: m_Value(V&: Sel),
3819 Ps: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: TV),
3820 R: m_Value(V&: FV))),
3821 R: m_Value(V&: Other)))) &&
3822 Cond->getType() == Cmp.getType()) {
3823 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
3824 // Easy case is if eq/ne matches whether 0 is trueval/falseval.
3825 if (Pred == ICmpInst::ICMP_EQ
3826 ? (match(V: TV, P: m_Zero()) && isKnownNonZero(V: FV, Q))
3827 : (match(V: FV, P: m_Zero()) && isKnownNonZero(V: TV, Q))) {
3828 Value *Cmp = Builder.CreateICmp(
3829 P: Pred, LHS: Other, RHS: Constant::getNullValue(Ty: Other->getType()));
3830 return BinaryOperator::Create(
3831 Op: Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, S1: Cmp,
3832 S2: Cond);
3833 }
3834 // Harder case is if eq/ne matches whether 0 is falseval/trueval. In this
3835 // case we need to invert the select condition so we need to be careful to
3836 // avoid creating extra instructions.
3837 // (icmp ne (or (select cond, 0, NonZero), Other), 0)
3838 // -> (or (not cond), (icmp ne Other, 0))
3839 // (icmp eq (or (select cond, NonZero, 0), Other), 0)
3840 // -> (and (not cond), (icmp eq Other, 0))
3841 //
3842 // Only do this if the inner select has one use, in which case we are
3843 // replacing `select` with `(not cond)`. Otherwise, we will create more
3844 // uses. NB: Trying to freely invert cond doesn't make sense here, as if
3845 // cond was freely invertable, the select arms would have been inverted.
3846 if (Sel->hasOneUse() &&
3847 (Pred == ICmpInst::ICMP_EQ
3848 ? (match(V: FV, P: m_Zero()) && isKnownNonZero(V: TV, Q))
3849 : (match(V: TV, P: m_Zero()) && isKnownNonZero(V: FV, Q)))) {
3850 Value *NotCond = Builder.CreateNot(V: Cond);
3851 Value *Cmp = Builder.CreateICmp(
3852 P: Pred, LHS: Other, RHS: Constant::getNullValue(Ty: Other->getType()));
3853 return BinaryOperator::Create(
3854 Op: Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, S1: Cmp,
3855 S2: NotCond);
3856 }
3857 }
3858 break;
3859 }
3860 case Instruction::UDiv:
3861 case Instruction::SDiv:
3862 if (BO->isExact()) {
3863 // div exact X, Y eq/ne 0 -> X eq/ne 0
3864 // div exact X, Y eq/ne 1 -> X eq/ne Y
3865 // div exact X, Y eq/ne C ->
3866 // if Y * C never-overflow && OneUse:
3867 // -> Y * C eq/ne X
3868 if (C.isZero())
3869 return new ICmpInst(Pred, BOp0, Constant::getNullValue(Ty: BO->getType()));
3870 else if (C.isOne())
3871 return new ICmpInst(Pred, BOp0, BOp1);
3872 else if (BO->hasOneUse()) {
3873 OverflowResult OR = computeOverflow(
3874 BinaryOp: Instruction::Mul, IsSigned: BO->getOpcode() == Instruction::SDiv, LHS: BOp1,
3875 RHS: Cmp.getOperand(i_nocapture: 1), CxtI: BO);
3876 if (OR == OverflowResult::NeverOverflows) {
3877 Value *YC =
3878 Builder.CreateMul(LHS: BOp1, RHS: ConstantInt::get(Ty: BO->getType(), V: C));
3879 return new ICmpInst(Pred, YC, BOp0);
3880 }
3881 }
3882 }
3883 if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3884 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3885 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3886 return new ICmpInst(NewPred, BOp1, BOp0);
3887 }
3888 break;
3889 default:
3890 break;
3891 }
3892 return nullptr;
3893}
3894
3895static Instruction *foldCtpopPow2Test(ICmpInst &I, IntrinsicInst *CtpopLhs,
3896 const APInt &CRhs,
3897 InstCombiner::BuilderTy &Builder,
3898 const SimplifyQuery &Q) {
3899 assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3900 "Non-ctpop intrin in ctpop fold");
3901 if (!CtpopLhs->hasOneUse())
3902 return nullptr;
3903
3904 // Power of 2 test:
3905 // isPow2OrZero : ctpop(X) u< 2
3906 // isPow2 : ctpop(X) == 1
3907 // NotPow2OrZero: ctpop(X) u> 1
3908 // NotPow2 : ctpop(X) != 1
3909 // If we know any bit of X can be folded to:
3910 // IsPow2 : X & (~Bit) == 0
3911 // NotPow2 : X & (~Bit) != 0
3912 const ICmpInst::Predicate Pred = I.getPredicate();
3913 if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3914 (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3915 Value *Op = CtpopLhs->getArgOperand(i: 0);
3916 KnownBits OpKnown = computeKnownBits(V: Op, DL: Q.DL, AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT);
3917 // No need to check for count > 1, that should be already constant folded.
3918 if (OpKnown.countMinPopulation() == 1) {
3919 Value *And = Builder.CreateAnd(
3920 LHS: Op, RHS: Constant::getIntegerValue(Ty: Op->getType(), V: ~(OpKnown.One)));
3921 return new ICmpInst(
3922 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3923 ? ICmpInst::ICMP_EQ
3924 : ICmpInst::ICMP_NE,
3925 And, Constant::getNullValue(Ty: Op->getType()));
3926 }
3927 }
3928
3929 return nullptr;
3930}
3931
3932/// Fold an equality icmp with LLVM intrinsic and constant operand.
3933Instruction *InstCombinerImpl::foldICmpEqIntrinsicWithConstant(
3934 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3935 Type *Ty = II->getType();
3936 unsigned BitWidth = C.getBitWidth();
3937 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3938
3939 switch (II->getIntrinsicID()) {
3940 case Intrinsic::abs:
3941 // abs(A) == 0 -> A == 0
3942 // abs(A) == INT_MIN -> A == INT_MIN
3943 if (C.isZero() || C.isMinSignedValue())
3944 return new ICmpInst(Pred, II->getArgOperand(i: 0), ConstantInt::get(Ty, V: C));
3945 break;
3946
3947 case Intrinsic::bswap:
3948 // bswap(A) == C -> A == bswap(C)
3949 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3950 ConstantInt::get(Ty, V: C.byteSwap()));
3951
3952 case Intrinsic::bitreverse:
3953 // bitreverse(A) == C -> A == bitreverse(C)
3954 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3955 ConstantInt::get(Ty, V: C.reverseBits()));
3956
3957 case Intrinsic::ctlz:
3958 case Intrinsic::cttz: {
3959 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3960 if (C == BitWidth)
3961 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3962 ConstantInt::getNullValue(Ty));
3963
3964 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3965 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3966 // Limit to one use to ensure we don't increase instruction count.
3967 unsigned Num = C.getLimitedValue(Limit: BitWidth);
3968 if (Num != BitWidth && II->hasOneUse()) {
3969 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3970 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: Num + 1)
3971 : APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: Num + 1);
3972 APInt Mask2 = IsTrailing
3973 ? APInt::getOneBitSet(numBits: BitWidth, BitNo: Num)
3974 : APInt::getOneBitSet(numBits: BitWidth, BitNo: BitWidth - Num - 1);
3975 return new ICmpInst(Pred, Builder.CreateAnd(LHS: II->getArgOperand(i: 0), RHS: Mask1),
3976 ConstantInt::get(Ty, V: Mask2));
3977 }
3978 break;
3979 }
3980
3981 case Intrinsic::ctpop: {
3982 // popcount(A) == 0 -> A == 0 and likewise for !=
3983 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3984 bool IsZero = C.isZero();
3985 if (IsZero || C == BitWidth)
3986 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3987 IsZero ? Constant::getNullValue(Ty)
3988 : Constant::getAllOnesValue(Ty));
3989
3990 break;
3991 }
3992
3993 case Intrinsic::fshl:
3994 case Intrinsic::fshr:
3995 if (II->getArgOperand(i: 0) == II->getArgOperand(i: 1)) {
3996 const APInt *RotAmtC;
3997 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3998 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3999 if (match(V: II->getArgOperand(i: 2), P: m_APInt(Res&: RotAmtC)))
4000 return new ICmpInst(Pred, II->getArgOperand(i: 0),
4001 II->getIntrinsicID() == Intrinsic::fshl
4002 ? ConstantInt::get(Ty, V: C.rotr(rotateAmt: *RotAmtC))
4003 : ConstantInt::get(Ty, V: C.rotl(rotateAmt: *RotAmtC)));
4004 }
4005 break;
4006
4007 case Intrinsic::umax:
4008 case Intrinsic::uadd_sat: {
4009 // uadd.sat(a, b) == 0 -> (a | b) == 0
4010 // umax(a, b) == 0 -> (a | b) == 0
4011 if (C.isZero() && II->hasOneUse()) {
4012 Value *Or = Builder.CreateOr(LHS: II->getArgOperand(i: 0), RHS: II->getArgOperand(i: 1));
4013 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
4014 }
4015 break;
4016 }
4017
4018 case Intrinsic::ssub_sat:
4019 // ssub.sat(a, b) == 0 -> a == b
4020 //
4021 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4022 // (because 1 saturates to 0). Just skip the optimization for i1.
4023 if (C.isZero() && II->getType()->getScalarSizeInBits() > 1)
4024 return new ICmpInst(Pred, II->getArgOperand(i: 0), II->getArgOperand(i: 1));
4025 break;
4026 case Intrinsic::usub_sat: {
4027 // usub.sat(a, b) == 0 -> a <= b
4028 if (C.isZero()) {
4029 ICmpInst::Predicate NewPred =
4030 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
4031 return new ICmpInst(NewPred, II->getArgOperand(i: 0), II->getArgOperand(i: 1));
4032 }
4033 break;
4034 }
4035 default:
4036 break;
4037 }
4038
4039 return nullptr;
4040}
4041
4042/// Fold an icmp with LLVM intrinsics
4043static Instruction *
4044foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp,
4045 InstCombiner::BuilderTy &Builder) {
4046 assert(Cmp.isEquality());
4047
4048 ICmpInst::Predicate Pred = Cmp.getPredicate();
4049 Value *Op0 = Cmp.getOperand(i_nocapture: 0);
4050 Value *Op1 = Cmp.getOperand(i_nocapture: 1);
4051 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Val: Op0);
4052 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Val: Op1);
4053 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
4054 return nullptr;
4055
4056 switch (IIOp0->getIntrinsicID()) {
4057 case Intrinsic::bswap:
4058 case Intrinsic::bitreverse:
4059 // If both operands are byte-swapped or bit-reversed, just compare the
4060 // original values.
4061 return new ICmpInst(Pred, IIOp0->getOperand(i_nocapture: 0), IIOp1->getOperand(i_nocapture: 0));
4062 case Intrinsic::fshl:
4063 case Intrinsic::fshr: {
4064 // If both operands are rotated by same amount, just compare the
4065 // original values.
4066 if (IIOp0->getOperand(i_nocapture: 0) != IIOp0->getOperand(i_nocapture: 1))
4067 break;
4068 if (IIOp1->getOperand(i_nocapture: 0) != IIOp1->getOperand(i_nocapture: 1))
4069 break;
4070 if (IIOp0->getOperand(i_nocapture: 2) == IIOp1->getOperand(i_nocapture: 2))
4071 return new ICmpInst(Pred, IIOp0->getOperand(i_nocapture: 0), IIOp1->getOperand(i_nocapture: 0));
4072
4073 // rotate(X, AmtX) == rotate(Y, AmtY)
4074 // -> rotate(X, AmtX - AmtY) == Y
4075 // Do this if either both rotates have one use or if only one has one use
4076 // and AmtX/AmtY are constants.
4077 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
4078 if (OneUses == 2 ||
4079 (OneUses == 1 && match(V: IIOp0->getOperand(i_nocapture: 2), P: m_ImmConstant()) &&
4080 match(V: IIOp1->getOperand(i_nocapture: 2), P: m_ImmConstant()))) {
4081 Value *SubAmt =
4082 Builder.CreateSub(LHS: IIOp0->getOperand(i_nocapture: 2), RHS: IIOp1->getOperand(i_nocapture: 2));
4083 Value *CombinedRotate = Builder.CreateIntrinsic(
4084 RetTy: Op0->getType(), ID: IIOp0->getIntrinsicID(),
4085 Args: {IIOp0->getOperand(i_nocapture: 0), IIOp0->getOperand(i_nocapture: 0), SubAmt});
4086 return new ICmpInst(Pred, IIOp1->getOperand(i_nocapture: 0), CombinedRotate);
4087 }
4088 } break;
4089 default:
4090 break;
4091 }
4092
4093 return nullptr;
4094}
4095
4096/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
4097/// where X is some kind of instruction and C is AllowPoison.
4098/// TODO: Move more folds which allow poison to this function.
4099Instruction *
4100InstCombinerImpl::foldICmpInstWithConstantAllowPoison(ICmpInst &Cmp,
4101 const APInt &C) {
4102 const ICmpInst::Predicate Pred = Cmp.getPredicate();
4103 if (auto *II = dyn_cast<IntrinsicInst>(Val: Cmp.getOperand(i_nocapture: 0))) {
4104 switch (II->getIntrinsicID()) {
4105 default:
4106 break;
4107 case Intrinsic::fshl:
4108 case Intrinsic::fshr:
4109 if (Cmp.isEquality() && II->getArgOperand(i: 0) == II->getArgOperand(i: 1)) {
4110 // (rot X, ?) == 0/-1 --> X == 0/-1
4111 if (C.isZero() || C.isAllOnes())
4112 return new ICmpInst(Pred, II->getArgOperand(i: 0), Cmp.getOperand(i_nocapture: 1));
4113 }
4114 break;
4115 }
4116 }
4117
4118 return nullptr;
4119}
4120
4121/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
4122Instruction *InstCombinerImpl::foldICmpBinOpWithConstant(ICmpInst &Cmp,
4123 BinaryOperator *BO,
4124 const APInt &C) {
4125 switch (BO->getOpcode()) {
4126 case Instruction::Xor:
4127 if (Instruction *I = foldICmpXorConstant(Cmp, Xor: BO, C))
4128 return I;
4129 break;
4130 case Instruction::And:
4131 if (Instruction *I = foldICmpAndConstant(Cmp, And: BO, C))
4132 return I;
4133 break;
4134 case Instruction::Or:
4135 if (Instruction *I = foldICmpOrConstant(Cmp, Or: BO, C))
4136 return I;
4137 break;
4138 case Instruction::Mul:
4139 if (Instruction *I = foldICmpMulConstant(Cmp, Mul: BO, C))
4140 return I;
4141 break;
4142 case Instruction::Shl:
4143 if (Instruction *I = foldICmpShlConstant(Cmp, Shl: BO, C))
4144 return I;
4145 break;
4146 case Instruction::LShr:
4147 case Instruction::AShr:
4148 if (Instruction *I = foldICmpShrConstant(Cmp, Shr: BO, C))
4149 return I;
4150 break;
4151 case Instruction::SRem:
4152 if (Instruction *I = foldICmpSRemConstant(Cmp, SRem: BO, C))
4153 return I;
4154 break;
4155 case Instruction::UDiv:
4156 if (Instruction *I = foldICmpUDivConstant(Cmp, UDiv: BO, C))
4157 return I;
4158 [[fallthrough]];
4159 case Instruction::SDiv:
4160 if (Instruction *I = foldICmpDivConstant(Cmp, Div: BO, C))
4161 return I;
4162 break;
4163 case Instruction::Sub:
4164 if (Instruction *I = foldICmpSubConstant(Cmp, Sub: BO, C))
4165 return I;
4166 break;
4167 case Instruction::Add:
4168 if (Instruction *I = foldICmpAddConstant(Cmp, Add: BO, C))
4169 return I;
4170 break;
4171 default:
4172 break;
4173 }
4174
4175 // TODO: These folds could be refactored to be part of the above calls.
4176 if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, C))
4177 return I;
4178
4179 // Fall back to handling `icmp pred (select A ? C1 : C2) binop (select B ? C3
4180 // : C4), C5` pattern, by computing a truth table of the four constant
4181 // variants.
4182 return foldICmpBinOpWithConstantViaTruthTable(Cmp, BO, C);
4183}
4184
4185static Instruction *
4186foldICmpUSubSatOrUAddSatWithConstant(CmpPredicate Pred, SaturatingInst *II,
4187 const APInt &C,
4188 InstCombiner::BuilderTy &Builder) {
4189 // This transform may end up producing more than one instruction for the
4190 // intrinsic, so limit it to one user of the intrinsic.
4191 if (!II->hasOneUse())
4192 return nullptr;
4193
4194 // Let Y = [add/sub]_sat(X, C) pred C2
4195 // SatVal = The saturating value for the operation
4196 // WillWrap = Whether or not the operation will underflow / overflow
4197 // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
4198 // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
4199 //
4200 // When (SatVal pred C2) is true, then
4201 // Y = WillWrap ? true : ((X binop C) pred C2)
4202 // => Y = WillWrap || ((X binop C) pred C2)
4203 // else
4204 // Y = WillWrap ? false : ((X binop C) pred C2)
4205 // => Y = !WillWrap ? ((X binop C) pred C2) : false
4206 // => Y = !WillWrap && ((X binop C) pred C2)
4207 Value *Op0 = II->getOperand(i_nocapture: 0);
4208 Value *Op1 = II->getOperand(i_nocapture: 1);
4209
4210 const APInt *COp1;
4211 // This transform only works when the intrinsic has an integral constant or
4212 // splat vector as the second operand.
4213 if (!match(V: Op1, P: m_APInt(Res&: COp1)))
4214 return nullptr;
4215
4216 APInt SatVal;
4217 switch (II->getIntrinsicID()) {
4218 default:
4219 llvm_unreachable(
4220 "This function only works with usub_sat and uadd_sat for now!");
4221 case Intrinsic::uadd_sat:
4222 SatVal = APInt::getAllOnes(numBits: C.getBitWidth());
4223 break;
4224 case Intrinsic::usub_sat:
4225 SatVal = APInt::getZero(numBits: C.getBitWidth());
4226 break;
4227 }
4228
4229 // Check (SatVal pred C2)
4230 bool SatValCheck = ICmpInst::compare(LHS: SatVal, RHS: C, Pred);
4231
4232 // !WillWrap.
4233 ConstantRange C1 = ConstantRange::makeExactNoWrapRegion(
4234 BinOp: II->getBinaryOp(), Other: *COp1, NoWrapKind: II->getNoWrapKind());
4235
4236 // WillWrap.
4237 if (SatValCheck)
4238 C1 = C1.inverse();
4239
4240 ConstantRange C2 = ConstantRange::makeExactICmpRegion(Pred, Other: C);
4241 if (II->getBinaryOp() == Instruction::Add)
4242 C2 = C2.sub(Other: *COp1);
4243 else
4244 C2 = C2.add(Other: *COp1);
4245
4246 Instruction::BinaryOps CombiningOp =
4247 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4248
4249 std::optional<ConstantRange> Combination;
4250 if (CombiningOp == Instruction::BinaryOps::Or)
4251 Combination = C1.exactUnionWith(CR: C2);
4252 else /* CombiningOp == Instruction::BinaryOps::And */
4253 Combination = C1.exactIntersectWith(CR: C2);
4254
4255 if (!Combination)
4256 return nullptr;
4257
4258 CmpInst::Predicate EquivPred;
4259 APInt EquivInt;
4260 APInt EquivOffset;
4261
4262 Combination->getEquivalentICmp(Pred&: EquivPred, RHS&: EquivInt, Offset&: EquivOffset);
4263
4264 return new ICmpInst(
4265 EquivPred,
4266 Builder.CreateAdd(LHS: Op0, RHS: ConstantInt::get(Ty: Op1->getType(), V: EquivOffset)),
4267 ConstantInt::get(Ty: Op1->getType(), V: EquivInt));
4268}
4269
4270static Instruction *
4271foldICmpOfCmpIntrinsicWithConstant(CmpPredicate Pred, IntrinsicInst *I,
4272 const APInt &C,
4273 InstCombiner::BuilderTy &Builder) {
4274 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4275 switch (Pred) {
4276 case ICmpInst::ICMP_EQ:
4277 case ICmpInst::ICMP_NE:
4278 if (C.isZero())
4279 NewPredicate = Pred;
4280 else if (C.isOne())
4281 NewPredicate =
4282 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
4283 else if (C.isAllOnes())
4284 NewPredicate =
4285 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
4286 break;
4287
4288 case ICmpInst::ICMP_SGT:
4289 if (C.isAllOnes())
4290 NewPredicate = ICmpInst::ICMP_UGE;
4291 else if (C.isZero())
4292 NewPredicate = ICmpInst::ICMP_UGT;
4293 break;
4294
4295 case ICmpInst::ICMP_SLT:
4296 if (C.isZero())
4297 NewPredicate = ICmpInst::ICMP_ULT;
4298 else if (C.isOne())
4299 NewPredicate = ICmpInst::ICMP_ULE;
4300 break;
4301
4302 case ICmpInst::ICMP_ULT:
4303 if (C.ugt(RHS: 1))
4304 NewPredicate = ICmpInst::ICMP_UGE;
4305 break;
4306
4307 case ICmpInst::ICMP_UGT:
4308 if (!C.isZero() && !C.isAllOnes())
4309 NewPredicate = ICmpInst::ICMP_ULT;
4310 break;
4311
4312 default:
4313 break;
4314 }
4315
4316 if (!NewPredicate)
4317 return nullptr;
4318
4319 if (I->getIntrinsicID() == Intrinsic::scmp)
4320 NewPredicate = ICmpInst::getSignedPredicate(Pred: *NewPredicate);
4321 Value *LHS = I->getOperand(i_nocapture: 0);
4322 Value *RHS = I->getOperand(i_nocapture: 1);
4323 return new ICmpInst(*NewPredicate, LHS, RHS);
4324}
4325
4326/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
4327Instruction *InstCombinerImpl::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
4328 IntrinsicInst *II,
4329 const APInt &C) {
4330 ICmpInst::Predicate Pred = Cmp.getPredicate();
4331
4332 // Handle folds that apply for any kind of icmp.
4333 switch (II->getIntrinsicID()) {
4334 default:
4335 break;
4336 case Intrinsic::uadd_sat:
4337 case Intrinsic::usub_sat:
4338 if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(
4339 Pred, II: cast<SaturatingInst>(Val: II), C, Builder))
4340 return Folded;
4341 break;
4342 case Intrinsic::ctpop: {
4343 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
4344 if (Instruction *R = foldCtpopPow2Test(I&: Cmp, CtpopLhs: II, CRhs: C, Builder, Q))
4345 return R;
4346 } break;
4347 case Intrinsic::scmp:
4348 case Intrinsic::ucmp:
4349 if (auto *Folded = foldICmpOfCmpIntrinsicWithConstant(Pred, I: II, C, Builder))
4350 return Folded;
4351 break;
4352 }
4353
4354 if (Cmp.isEquality())
4355 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
4356
4357 Type *Ty = II->getType();
4358 unsigned BitWidth = C.getBitWidth();
4359 switch (II->getIntrinsicID()) {
4360 case Intrinsic::ctpop: {
4361 // (ctpop X > BitWidth - 1) --> X == -1
4362 Value *X = II->getArgOperand(i: 0);
4363 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
4364 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_EQ, S1: X,
4365 S2: ConstantInt::getAllOnesValue(Ty));
4366 // (ctpop X < BitWidth) --> X != -1
4367 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
4368 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_NE, S1: X,
4369 S2: ConstantInt::getAllOnesValue(Ty));
4370 break;
4371 }
4372 case Intrinsic::ctlz: {
4373 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
4374 if (Pred == ICmpInst::ICMP_UGT && C.ult(RHS: BitWidth)) {
4375 unsigned Num = C.getLimitedValue();
4376 APInt Limit = APInt::getOneBitSet(numBits: BitWidth, BitNo: BitWidth - Num - 1);
4377 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_ULT,
4378 S1: II->getArgOperand(i: 0), S2: ConstantInt::get(Ty, V: Limit));
4379 }
4380
4381 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
4382 if (Pred == ICmpInst::ICMP_ULT && C.uge(RHS: 1) && C.ule(RHS: BitWidth)) {
4383 unsigned Num = C.getLimitedValue();
4384 APInt Limit = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: BitWidth - Num);
4385 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_UGT,
4386 S1: II->getArgOperand(i: 0), S2: ConstantInt::get(Ty, V: Limit));
4387 }
4388 break;
4389 }
4390 case Intrinsic::cttz: {
4391 // Limit to one use to ensure we don't increase instruction count.
4392 if (!II->hasOneUse())
4393 return nullptr;
4394
4395 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
4396 if (Pred == ICmpInst::ICMP_UGT && C.ult(RHS: BitWidth)) {
4397 APInt Mask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: C.getLimitedValue() + 1);
4398 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_EQ,
4399 S1: Builder.CreateAnd(LHS: II->getArgOperand(i: 0), RHS: Mask),
4400 S2: ConstantInt::getNullValue(Ty));
4401 }
4402
4403 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
4404 if (Pred == ICmpInst::ICMP_ULT && C.uge(RHS: 1) && C.ule(RHS: BitWidth)) {
4405 APInt Mask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: C.getLimitedValue());
4406 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_NE,
4407 S1: Builder.CreateAnd(LHS: II->getArgOperand(i: 0), RHS: Mask),
4408 S2: ConstantInt::getNullValue(Ty));
4409 }
4410 break;
4411 }
4412 case Intrinsic::ssub_sat:
4413 // ssub.sat(a, b) spred 0 -> a spred b
4414 //
4415 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4416 // (because 1 saturates to 0). Just skip the optimization for i1.
4417 if (ICmpInst::isSigned(Pred) && C.getBitWidth() > 1) {
4418 if (C.isZero())
4419 return new ICmpInst(Pred, II->getArgOperand(i: 0), II->getArgOperand(i: 1));
4420 // X s<= 0 is cannonicalized to X s< 1
4421 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
4422 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(i: 0),
4423 II->getArgOperand(i: 1));
4424 // X s>= 0 is cannonicalized to X s> -1
4425 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
4426 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(i: 0),
4427 II->getArgOperand(i: 1));
4428 }
4429 break;
4430 case Intrinsic::abs: {
4431 if (!II->hasOneUse())
4432 return nullptr;
4433
4434 Value *X = II->getArgOperand(i: 0);
4435
4436 // If C >= 0:
4437 // abs(X) u> C --> X + C u> 2 * C
4438 if (Pred == CmpInst::ICMP_UGT && C.isNonNegative()) {
4439 return new ICmpInst(ICmpInst::ICMP_UGT,
4440 Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: C)),
4441 ConstantInt::get(Ty, V: 2 * C));
4442 }
4443
4444 // If C >= 1:
4445 // abs(X) u< C --> X + (C - 1) u<= 2 * (C - 1)
4446 if (Pred == CmpInst::ICMP_ULT && C.sge(RHS: 1))
4447 return new ICmpInst(ICmpInst::ICMP_ULE,
4448 Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: C - 1)),
4449 ConstantInt::get(Ty, V: 2 * (C - 1)));
4450
4451 break;
4452 }
4453 default:
4454 break;
4455 }
4456
4457 return nullptr;
4458}
4459
4460/// Handle icmp with constant (but not simple integer constant) RHS.
4461Instruction *InstCombinerImpl::foldICmpInstWithConstantNotInt(ICmpInst &I) {
4462 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
4463 Constant *RHSC = dyn_cast<Constant>(Val: Op1);
4464 Instruction *LHSI = dyn_cast<Instruction>(Val: Op0);
4465 if (!RHSC || !LHSI)
4466 return nullptr;
4467
4468 switch (LHSI->getOpcode()) {
4469 case Instruction::IntToPtr:
4470 // icmp pred inttoptr(X), null -> icmp pred X, null pointer value
4471 if (isa<ConstantPointerNull>(Val: RHSC)) {
4472 Type *IntPtrTy = DL.getIntPtrType(RHSC->getType());
4473 if (IntPtrTy == LHSI->getOperand(i: 0)->getType()) {
4474 APInt NullPtrValue =
4475 DL.getNullPtrValue(AS: RHSC->getType()->getPointerAddressSpace());
4476 return new ICmpInst(I.getPredicate(), LHSI->getOperand(i: 0),
4477 Constant::getIntegerValue(Ty: IntPtrTy, V: NullPtrValue));
4478 }
4479 }
4480 break;
4481
4482 case Instruction::Load:
4483 // Try to optimize things like "A[i] > 4" to index computations.
4484 if (GetElementPtrInst *GEP =
4485 dyn_cast<GetElementPtrInst>(Val: LHSI->getOperand(i: 0)))
4486 if (Instruction *Res =
4487 foldCmpLoadFromIndexedGlobal(LI: cast<LoadInst>(Val: LHSI), GEP, ICI&: I))
4488 return Res;
4489 break;
4490 }
4491
4492 return nullptr;
4493}
4494
4495Instruction *InstCombinerImpl::foldSelectICmp(CmpPredicate Pred, SelectInst *SI,
4496 Value *RHS, const ICmpInst &I) {
4497 // Try to fold the comparison into the select arms, which will cause the
4498 // select to be converted into a logical and/or.
4499 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
4500 if (Value *Res = simplifyICmpInst(Pred, LHS: Op, RHS, Q: SQ))
4501 return Res;
4502 if (std::optional<bool> Impl = isImpliedCondition(
4503 LHS: SI->getCondition(), RHSPred: Pred, RHSOp0: Op, RHSOp1: RHS, DL, LHSIsTrue: SelectCondIsTrue))
4504 return ConstantInt::get(Ty: I.getType(), V: *Impl);
4505 return nullptr;
4506 };
4507
4508 ConstantInt *CI = nullptr;
4509 Value *Op1 = SimplifyOp(SI->getOperand(i_nocapture: 1), true);
4510 if (Op1)
4511 CI = dyn_cast<ConstantInt>(Val: Op1);
4512
4513 Value *Op2 = SimplifyOp(SI->getOperand(i_nocapture: 2), false);
4514 if (Op2)
4515 CI = dyn_cast<ConstantInt>(Val: Op2);
4516
4517 auto Simplifies = [&](Value *Op, unsigned Idx) {
4518 // A comparison of ucmp/scmp with a constant will fold into an icmp.
4519 const APInt *Dummy;
4520 return Op ||
4521 (isa<CmpIntrinsic>(Val: SI->getOperand(i_nocapture: Idx)) &&
4522 SI->getOperand(i_nocapture: Idx)->hasOneUse() && match(V: RHS, P: m_APInt(Res&: Dummy)));
4523 };
4524
4525 // We only want to perform this transformation if it will not lead to
4526 // additional code. This is true if either both sides of the select
4527 // fold to a constant (in which case the icmp is replaced with a select
4528 // which will usually simplify) or this is the only user of the
4529 // select (in which case we are trading a select+icmp for a simpler
4530 // select+icmp) or all uses of the select can be replaced based on
4531 // dominance information ("Global cases").
4532 bool Transform = false;
4533 if (Op1 && Op2)
4534 Transform = true;
4535 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4536 // Local case
4537 if (SI->hasOneUse())
4538 Transform = true;
4539 // Global cases
4540 else if (CI && !CI->isZero())
4541 // When Op1 is constant try replacing select with second operand.
4542 // Otherwise Op2 is constant and try replacing select with first
4543 // operand.
4544 Transform = replacedSelectWithOperand(SI, Icmp: &I, SIOpd: Op1 ? 2 : 1);
4545 }
4546 if (Transform) {
4547 if (!Op1)
4548 Op1 = Builder.CreateICmp(P: Pred, LHS: SI->getOperand(i_nocapture: 1), RHS, Name: I.getName());
4549 if (!Op2)
4550 Op2 = Builder.CreateICmp(P: Pred, LHS: SI->getOperand(i_nocapture: 2), RHS, Name: I.getName());
4551 return SelectInst::Create(C: SI->getOperand(i_nocapture: 0), S1: Op1, S2: Op2, NameStr: "", InsertBefore: nullptr,
4552 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : SI);
4553 }
4554
4555 return nullptr;
4556}
4557
4558// Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)
4559static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,
4560 unsigned Depth = 0) {
4561 if (Not ? match(V, P: m_NegatedPower2OrZero()) : match(V, P: m_LowBitMaskOrZero()))
4562 return true;
4563 if (V->getType()->getScalarSizeInBits() == 1)
4564 return true;
4565 if (Depth++ >= MaxAnalysisRecursionDepth)
4566 return false;
4567 Value *X;
4568 const Instruction *I = dyn_cast<Instruction>(Val: V);
4569 if (!I)
4570 return false;
4571 switch (I->getOpcode()) {
4572 case Instruction::ZExt:
4573 // ZExt(Mask) is a Mask.
4574 return !Not && isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4575 case Instruction::SExt:
4576 // SExt(Mask) is a Mask.
4577 // SExt(~Mask) is a ~Mask.
4578 return isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4579 case Instruction::And:
4580 case Instruction::Or:
4581 // Mask0 | Mask1 is a Mask.
4582 // Mask0 & Mask1 is a Mask.
4583 // ~Mask0 | ~Mask1 is a ~Mask.
4584 // ~Mask0 & ~Mask1 is a ~Mask.
4585 return isMaskOrZero(V: I->getOperand(i: 1), Not, Q, Depth) &&
4586 isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4587 case Instruction::Xor:
4588 if (match(V, P: m_Not(V: m_Value(V&: X))))
4589 return isMaskOrZero(V: X, Not: !Not, Q, Depth);
4590
4591 // (X ^ -X) is a ~Mask
4592 if (Not)
4593 return match(V, P: m_c_Xor(L: m_Value(V&: X), R: m_Neg(V: m_Deferred(V: X))));
4594 // (X ^ (X - 1)) is a Mask
4595 else
4596 return match(V, P: m_c_Xor(L: m_Value(V&: X), R: m_Add(L: m_Deferred(V: X), R: m_AllOnes())));
4597 case Instruction::Select:
4598 // c ? Mask0 : Mask1 is a Mask.
4599 return isMaskOrZero(V: I->getOperand(i: 1), Not, Q, Depth) &&
4600 isMaskOrZero(V: I->getOperand(i: 2), Not, Q, Depth);
4601 case Instruction::Shl:
4602 // (~Mask) << X is a ~Mask.
4603 return Not && isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4604 case Instruction::LShr:
4605 // Mask >> X is a Mask.
4606 return !Not && isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4607 case Instruction::AShr:
4608 // Mask s>> X is a Mask.
4609 // ~Mask s>> X is a ~Mask.
4610 return isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4611 case Instruction::Add:
4612 // Pow2 - 1 is a Mask.
4613 if (!Not && match(V: I->getOperand(i: 1), P: m_AllOnes()))
4614 return isKnownToBeAPowerOfTwo(V: I->getOperand(i: 0), DL: Q.DL, /*OrZero*/ true,
4615 AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT, UseInstrInfo: Depth);
4616 break;
4617 case Instruction::Sub:
4618 // -Pow2 is a ~Mask.
4619 if (Not && match(V: I->getOperand(i: 0), P: m_Zero()))
4620 return isKnownToBeAPowerOfTwo(V: I->getOperand(i: 1), DL: Q.DL, /*OrZero*/ true,
4621 AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT, UseInstrInfo: Depth);
4622 break;
4623 case Instruction::Call: {
4624 if (auto *II = dyn_cast<IntrinsicInst>(Val: I)) {
4625 switch (II->getIntrinsicID()) {
4626 // min/max(Mask0, Mask1) is a Mask.
4627 // min/max(~Mask0, ~Mask1) is a ~Mask.
4628 case Intrinsic::umax:
4629 case Intrinsic::smax:
4630 case Intrinsic::umin:
4631 case Intrinsic::smin:
4632 return isMaskOrZero(V: II->getArgOperand(i: 1), Not, Q, Depth) &&
4633 isMaskOrZero(V: II->getArgOperand(i: 0), Not, Q, Depth);
4634
4635 // In the context of masks, bitreverse(Mask) == ~Mask
4636 case Intrinsic::bitreverse:
4637 return isMaskOrZero(V: II->getArgOperand(i: 0), Not: !Not, Q, Depth);
4638 default:
4639 break;
4640 }
4641 }
4642 break;
4643 }
4644 default:
4645 break;
4646 }
4647 return false;
4648}
4649
4650/// Some comparisons can be simplified.
4651/// In this case, we are looking for comparisons that look like
4652/// a check for a lossy truncation.
4653/// Folds:
4654/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
4655/// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask
4656/// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask
4657/// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask
4658/// Where Mask is some pattern that produces all-ones in low bits:
4659/// (-1 >> y)
4660/// ((-1 << y) >> y) <- non-canonical, has extra uses
4661/// ~(-1 << y)
4662/// ((1 << y) + (-1)) <- non-canonical, has extra uses
4663/// The Mask can be a constant, too.
4664/// For some predicates, the operands are commutative.
4665/// For others, x can only be on a specific side.
4666static Value *foldICmpWithLowBitMaskedVal(CmpPredicate Pred, Value *Op0,
4667 Value *Op1, const SimplifyQuery &Q,
4668 InstCombiner &IC) {
4669
4670 ICmpInst::Predicate DstPred;
4671 switch (Pred) {
4672 case ICmpInst::Predicate::ICMP_EQ:
4673 // x & Mask == x
4674 // x & ~Mask == 0
4675 // ~x | Mask == -1
4676 // -> x u<= Mask
4677 // x & ~Mask == ~Mask
4678 // -> ~Mask u<= x
4679 DstPred = ICmpInst::Predicate::ICMP_ULE;
4680 break;
4681 case ICmpInst::Predicate::ICMP_NE:
4682 // x & Mask != x
4683 // x & ~Mask != 0
4684 // ~x | Mask != -1
4685 // -> x u> Mask
4686 // x & ~Mask != ~Mask
4687 // -> ~Mask u> x
4688 DstPred = ICmpInst::Predicate::ICMP_UGT;
4689 break;
4690 case ICmpInst::Predicate::ICMP_ULT:
4691 // x & Mask u< x
4692 // -> x u> Mask
4693 // x & ~Mask u< ~Mask
4694 // -> ~Mask u> x
4695 DstPred = ICmpInst::Predicate::ICMP_UGT;
4696 break;
4697 case ICmpInst::Predicate::ICMP_UGE:
4698 // x & Mask u>= x
4699 // -> x u<= Mask
4700 // x & ~Mask u>= ~Mask
4701 // -> ~Mask u<= x
4702 DstPred = ICmpInst::Predicate::ICMP_ULE;
4703 break;
4704 case ICmpInst::Predicate::ICMP_SLT:
4705 // x & Mask s< x [iff Mask s>= 0]
4706 // -> x s> Mask
4707 // x & ~Mask s< ~Mask [iff ~Mask != 0]
4708 // -> ~Mask s> x
4709 DstPred = ICmpInst::Predicate::ICMP_SGT;
4710 break;
4711 case ICmpInst::Predicate::ICMP_SGE:
4712 // x & Mask s>= x [iff Mask s>= 0]
4713 // -> x s<= Mask
4714 // x & ~Mask s>= ~Mask [iff ~Mask != 0]
4715 // -> ~Mask s<= x
4716 DstPred = ICmpInst::Predicate::ICMP_SLE;
4717 break;
4718 default:
4719 // We don't support sgt,sle
4720 // ult/ugt are simplified to true/false respectively.
4721 return nullptr;
4722 }
4723
4724 Value *X, *M;
4725 // Put search code in lambda for early positive returns.
4726 auto IsLowBitMask = [&]() {
4727 if (match(V: Op0, P: m_c_And(L: m_Specific(V: Op1), R: m_Value(V&: M)))) {
4728 X = Op1;
4729 // Look for: x & Mask pred x
4730 if (isMaskOrZero(V: M, /*Not=*/false, Q)) {
4731 return !ICmpInst::isSigned(Pred) ||
4732 (match(V: M, P: m_NonNegative()) || isKnownNonNegative(V: M, SQ: Q));
4733 }
4734
4735 // Look for: x & ~Mask pred ~Mask
4736 if (isMaskOrZero(V: X, /*Not=*/true, Q)) {
4737 return !ICmpInst::isSigned(Pred) || isKnownNonZero(V: X, Q);
4738 }
4739 return false;
4740 }
4741 if (ICmpInst::isEquality(P: Pred) && match(V: Op1, P: m_AllOnes()) &&
4742 match(V: Op0, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: X), R: m_Value(V&: M))))) {
4743
4744 auto Check = [&]() {
4745 // Look for: ~x | Mask == -1
4746 if (isMaskOrZero(V: M, /*Not=*/false, Q)) {
4747 if (Value *NotX =
4748 IC.getFreelyInverted(V: X, WillInvertAllUses: X->hasOneUse(), Builder: &IC.Builder)) {
4749 X = NotX;
4750 return true;
4751 }
4752 }
4753 return false;
4754 };
4755 if (Check())
4756 return true;
4757 std::swap(a&: X, b&: M);
4758 return Check();
4759 }
4760 if (ICmpInst::isEquality(P: Pred) && match(V: Op1, P: m_Zero()) &&
4761 match(V: Op0, P: m_OneUse(SubPattern: m_And(L: m_Value(V&: X), R: m_Value(V&: M))))) {
4762 auto Check = [&]() {
4763 // Look for: x & ~Mask == 0
4764 if (isMaskOrZero(V: M, /*Not=*/true, Q)) {
4765 if (Value *NotM =
4766 IC.getFreelyInverted(V: M, WillInvertAllUses: M->hasOneUse(), Builder: &IC.Builder)) {
4767 M = NotM;
4768 return true;
4769 }
4770 }
4771 return false;
4772 };
4773 if (Check())
4774 return true;
4775 std::swap(a&: X, b&: M);
4776 return Check();
4777 }
4778 return false;
4779 };
4780
4781 if (!IsLowBitMask())
4782 return nullptr;
4783
4784 return IC.Builder.CreateICmp(P: DstPred, LHS: X, RHS: M);
4785}
4786
4787/// Some comparisons can be simplified.
4788/// In this case, we are looking for comparisons that look like
4789/// a check for a lossy signed truncation.
4790/// Folds: (MaskedBits is a constant.)
4791/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4792/// Into:
4793/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4794/// Where KeptBits = bitwidth(%x) - MaskedBits
4795static Value *
4796foldICmpWithTruncSignExtendedVal(ICmpInst &I,
4797 InstCombiner::BuilderTy &Builder) {
4798 CmpPredicate SrcPred;
4799 Value *X;
4800 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4801 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4802 if (!match(V: &I, P: m_c_ICmp(Pred&: SrcPred,
4803 L: m_OneUse(SubPattern: m_AShr(L: m_Shl(L: m_Value(V&: X), R: m_APInt(Res&: C0)),
4804 R: m_APInt(Res&: C1))),
4805 R: m_Deferred(V: X))))
4806 return nullptr;
4807
4808 // Potential handling of non-splats: for each element:
4809 // * if both are undef, replace with constant 0.
4810 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4811 // * if both are not undef, and are different, bailout.
4812 // * else, only one is undef, then pick the non-undef one.
4813
4814 // The shift amount must be equal.
4815 if (*C0 != *C1)
4816 return nullptr;
4817 const APInt &MaskedBits = *C0;
4818 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4819
4820 ICmpInst::Predicate DstPred;
4821 switch (SrcPred) {
4822 case ICmpInst::Predicate::ICMP_EQ:
4823 // ((%x << MaskedBits) a>> MaskedBits) == %x
4824 // =>
4825 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4826 DstPred = ICmpInst::Predicate::ICMP_ULT;
4827 break;
4828 case ICmpInst::Predicate::ICMP_NE:
4829 // ((%x << MaskedBits) a>> MaskedBits) != %x
4830 // =>
4831 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4832 DstPred = ICmpInst::Predicate::ICMP_UGE;
4833 break;
4834 // FIXME: are more folds possible?
4835 default:
4836 return nullptr;
4837 }
4838
4839 auto *XType = X->getType();
4840 const unsigned XBitWidth = XType->getScalarSizeInBits();
4841 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4842 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4843
4844 // KeptBits = bitwidth(%x) - MaskedBits
4845 const APInt KeptBits = BitWidth - MaskedBits;
4846 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4847 // ICmpCst = (1 << KeptBits)
4848 const APInt ICmpCst = APInt(XBitWidth, 1).shl(ShiftAmt: KeptBits);
4849 assert(ICmpCst.isPowerOf2());
4850 // AddCst = (1 << (KeptBits-1))
4851 const APInt AddCst = ICmpCst.lshr(shiftAmt: 1);
4852 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4853
4854 // T0 = add %x, AddCst
4855 Value *T0 = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty: XType, V: AddCst));
4856 // T1 = T0 DstPred ICmpCst
4857 Value *T1 = Builder.CreateICmp(P: DstPred, LHS: T0, RHS: ConstantInt::get(Ty: XType, V: ICmpCst));
4858
4859 return T1;
4860}
4861
4862// Given pattern:
4863// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4864// we should move shifts to the same hand of 'and', i.e. rewrite as
4865// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4866// We are only interested in opposite logical shifts here.
4867// One of the shifts can be truncated.
4868// If we can, we want to end up creating 'lshr' shift.
4869static Value *
4870foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ,
4871 InstCombiner::BuilderTy &Builder) {
4872 if (!I.isEquality() || !match(V: I.getOperand(i_nocapture: 1), P: m_Zero()) ||
4873 !I.getOperand(i_nocapture: 0)->hasOneUse())
4874 return nullptr;
4875
4876 auto m_AnyLogicalShift = m_LogicalShift(L: m_Value(), R: m_Value());
4877
4878 // Look for an 'and' of two logical shifts, one of which may be truncated.
4879 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4880 Instruction *XShift, *MaybeTruncation, *YShift;
4881 if (!match(
4882 V: I.getOperand(i_nocapture: 0),
4883 P: m_c_And(L: m_CombineAnd(Ps: m_AnyLogicalShift, Ps: m_Instruction(I&: XShift)),
4884 R: m_CombineAnd(Ps: m_TruncOrSelf(Op: m_CombineAnd(
4885 Ps: m_AnyLogicalShift, Ps: m_Instruction(I&: YShift))),
4886 Ps: m_Instruction(I&: MaybeTruncation)))))
4887 return nullptr;
4888
4889 // We potentially looked past 'trunc', but only when matching YShift,
4890 // therefore YShift must have the widest type.
4891 Instruction *WidestShift = YShift;
4892 // Therefore XShift must have the shallowest type.
4893 // Or they both have identical types if there was no truncation.
4894 Instruction *NarrowestShift = XShift;
4895
4896 Type *WidestTy = WidestShift->getType();
4897 Type *NarrowestTy = NarrowestShift->getType();
4898 assert(NarrowestTy == I.getOperand(0)->getType() &&
4899 "We did not look past any shifts while matching XShift though.");
4900 bool HadTrunc = WidestTy != I.getOperand(i_nocapture: 0)->getType();
4901
4902 // If YShift is a 'lshr', swap the shifts around.
4903 if (match(V: YShift, P: m_LShr(L: m_Value(), R: m_Value())))
4904 std::swap(a&: XShift, b&: YShift);
4905
4906 // The shifts must be in opposite directions.
4907 auto XShiftOpcode = XShift->getOpcode();
4908 if (XShiftOpcode == YShift->getOpcode())
4909 return nullptr; // Do not care about same-direction shifts here.
4910
4911 Value *X, *XShAmt, *Y, *YShAmt;
4912 match(V: XShift, P: m_BinOp(L: m_Value(V&: X), R: m_ZExtOrSelf(Op: m_Value(V&: XShAmt))));
4913 match(V: YShift, P: m_BinOp(L: m_Value(V&: Y), R: m_ZExtOrSelf(Op: m_Value(V&: YShAmt))));
4914
4915 // If one of the values being shifted is a constant, then we will end with
4916 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4917 // however, we will need to ensure that we won't increase instruction count.
4918 if (!isa<Constant>(Val: X) && !isa<Constant>(Val: Y)) {
4919 // At least one of the hands of the 'and' should be one-use shift.
4920 if (!match(V: I.getOperand(i_nocapture: 0),
4921 P: m_c_And(L: m_OneUse(SubPattern: m_AnyLogicalShift), R: m_Value())))
4922 return nullptr;
4923 if (HadTrunc) {
4924 // Due to the 'trunc', we will need to widen X. For that either the old
4925 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4926 if (!MaybeTruncation->hasOneUse() &&
4927 !NarrowestShift->getOperand(i: 1)->hasOneUse())
4928 return nullptr;
4929 }
4930 }
4931
4932 // We have two shift amounts from two different shifts. The types of those
4933 // shift amounts may not match. If that's the case let's bailout now.
4934 if (XShAmt->getType() != YShAmt->getType())
4935 return nullptr;
4936
4937 // As input, we have the following pattern:
4938 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4939 // We want to rewrite that as:
4940 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4941 // While we know that originally (Q+K) would not overflow
4942 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
4943 // shift amounts. so it may now overflow in smaller bitwidth.
4944 // To ensure that does not happen, we need to ensure that the total maximal
4945 // shift amount is still representable in that smaller bit width.
4946 unsigned MaximalPossibleTotalShiftAmount =
4947 (WidestTy->getScalarSizeInBits() - 1) +
4948 (NarrowestTy->getScalarSizeInBits() - 1);
4949 APInt MaximalRepresentableShiftAmount =
4950 APInt::getAllOnes(numBits: XShAmt->getType()->getScalarSizeInBits());
4951 if (MaximalRepresentableShiftAmount.ult(RHS: MaximalPossibleTotalShiftAmount))
4952 return nullptr;
4953
4954 // Can we fold (XShAmt+YShAmt) ?
4955 auto *NewShAmt = dyn_cast_or_null<Constant>(
4956 Val: simplifyAddInst(LHS: XShAmt, RHS: YShAmt, /*isNSW=*/IsNSW: false,
4957 /*isNUW=*/IsNUW: false, Q: SQ.getWithInstruction(I: &I)));
4958 if (!NewShAmt)
4959 return nullptr;
4960 if (NewShAmt->getType() != WidestTy) {
4961 NewShAmt =
4962 ConstantFoldCastOperand(Opcode: Instruction::ZExt, C: NewShAmt, DestTy: WidestTy, DL: SQ.DL);
4963 if (!NewShAmt)
4964 return nullptr;
4965 }
4966 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
4967
4968 // Is the new shift amount smaller than the bit width?
4969 // FIXME: could also rely on ConstantRange.
4970 if (!match(V: NewShAmt,
4971 P: m_SpecificInt_ICMP(Predicate: ICmpInst::Predicate::ICMP_ULT,
4972 Threshold: APInt(WidestBitWidth, WidestBitWidth))))
4973 return nullptr;
4974
4975 // An extra legality check is needed if we had trunc-of-lshr.
4976 if (HadTrunc && match(V: WidestShift, P: m_LShr(L: m_Value(), R: m_Value()))) {
4977 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
4978 WidestShift]() {
4979 // It isn't obvious whether it's worth it to analyze non-constants here.
4980 // Also, let's basically give up on non-splat cases, pessimizing vectors.
4981 // If *any* of these preconditions matches we can perform the fold.
4982 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
4983 ? NewShAmt->getSplatValue()
4984 : NewShAmt;
4985 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
4986 if (NewShAmtSplat &&
4987 (NewShAmtSplat->isNullValue() ||
4988 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
4989 return true;
4990 // We consider *min* leading zeros so a single outlier
4991 // blocks the transform as opposed to allowing it.
4992 if (auto *C = dyn_cast<Constant>(Val: NarrowestShift->getOperand(i: 0))) {
4993 KnownBits Known = computeKnownBits(V: C, DL: SQ.DL);
4994 unsigned MinLeadZero = Known.countMinLeadingZeros();
4995 // If the value being shifted has at most lowest bit set we can fold.
4996 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4997 if (MaxActiveBits <= 1)
4998 return true;
4999 // Precondition: NewShAmt u<= countLeadingZeros(C)
5000 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(RHS: MinLeadZero))
5001 return true;
5002 }
5003 if (auto *C = dyn_cast<Constant>(Val: WidestShift->getOperand(i: 0))) {
5004 KnownBits Known = computeKnownBits(V: C, DL: SQ.DL);
5005 unsigned MinLeadZero = Known.countMinLeadingZeros();
5006 // If the value being shifted has at most lowest bit set we can fold.
5007 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5008 if (MaxActiveBits <= 1)
5009 return true;
5010 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
5011 if (NewShAmtSplat) {
5012 APInt AdjNewShAmt =
5013 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
5014 if (AdjNewShAmt.ule(RHS: MinLeadZero))
5015 return true;
5016 }
5017 }
5018 return false; // Can't tell if it's ok.
5019 };
5020 if (!CanFold())
5021 return nullptr;
5022 }
5023
5024 // All good, we can do this fold.
5025 X = Builder.CreateZExt(V: X, DestTy: WidestTy);
5026 Y = Builder.CreateZExt(V: Y, DestTy: WidestTy);
5027 // The shift is the same that was for X.
5028 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
5029 ? Builder.CreateLShr(LHS: X, RHS: NewShAmt)
5030 : Builder.CreateShl(LHS: X, RHS: NewShAmt);
5031 Value *T1 = Builder.CreateAnd(LHS: T0, RHS: Y);
5032 return Builder.CreateICmp(P: I.getPredicate(), LHS: T1,
5033 RHS: Constant::getNullValue(Ty: WidestTy));
5034}
5035
5036/// Fold
5037/// (-1 u/ x) u< y
5038/// ((x * y) ?/ x) != y
5039/// to
5040/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
5041/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
5042/// will mean that we are looking for the opposite answer.
5043Value *InstCombinerImpl::foldMultiplicationOverflowCheck(ICmpInst &I) {
5044 CmpPredicate Pred;
5045 Value *X, *Y;
5046 Instruction *Mul;
5047 Instruction *Div;
5048 bool NeedNegation;
5049 // Look for: (-1 u/ x) u</u>= y
5050 if (!I.isEquality() &&
5051 match(V: &I, P: m_c_ICmp(Pred,
5052 L: m_CombineAnd(Ps: m_OneUse(SubPattern: m_UDiv(L: m_AllOnes(), R: m_Value(V&: X))),
5053 Ps: m_Instruction(I&: Div)),
5054 R: m_Value(V&: Y)))) {
5055 Mul = nullptr;
5056
5057 // Are we checking that overflow does not happen, or does happen?
5058 switch (Pred) {
5059 case ICmpInst::Predicate::ICMP_ULT:
5060 NeedNegation = false;
5061 break; // OK
5062 case ICmpInst::Predicate::ICMP_UGE:
5063 NeedNegation = true;
5064 break; // OK
5065 default:
5066 return nullptr; // Wrong predicate.
5067 }
5068 } else // Look for: ((x * y) / x) !=/== y
5069 if (I.isEquality() &&
5070 match(V: &I, P: m_c_ICmp(Pred, L: m_Value(V&: Y),
5071 R: m_CombineAnd(Ps: m_OneUse(SubPattern: m_IDiv(
5072 L: m_CombineAnd(Ps: m_c_Mul(L: m_Deferred(V: Y),
5073 R: m_Value(V&: X)),
5074 Ps: m_Instruction(I&: Mul)),
5075 R: m_Deferred(V: X))),
5076 Ps: m_Instruction(I&: Div))))) {
5077 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
5078 } else
5079 return nullptr;
5080
5081 BuilderTy::InsertPointGuard Guard(Builder);
5082 // If the pattern included (x * y), we'll want to insert new instructions
5083 // right before that original multiplication so that we can replace it.
5084 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
5085 if (MulHadOtherUses)
5086 Builder.SetInsertPoint(Mul);
5087
5088 Value *Call = Builder.CreateIntrinsic(
5089 ID: Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
5090 : Intrinsic::smul_with_overflow,
5091 OverloadTypes: X->getType(), Args: {X, Y}, /*FMFSource=*/nullptr, Name: "mul");
5092
5093 // If the multiplication was used elsewhere, to ensure that we don't leave
5094 // "duplicate" instructions, replace uses of that original multiplication
5095 // with the multiplication result from the with.overflow intrinsic.
5096 if (MulHadOtherUses)
5097 replaceInstUsesWith(I&: *Mul, V: Builder.CreateExtractValue(Agg: Call, Idxs: 0, Name: "mul.val"));
5098
5099 Value *Res = Builder.CreateExtractValue(Agg: Call, Idxs: 1, Name: "mul.ov");
5100 if (NeedNegation) // This technically increases instruction count.
5101 Res = Builder.CreateNot(V: Res, Name: "mul.not.ov");
5102
5103 // If we replaced the mul, erase it. Do this after all uses of Builder,
5104 // as the mul is used as insertion point.
5105 if (MulHadOtherUses)
5106 eraseInstFromFunction(I&: *Mul);
5107
5108 return Res;
5109}
5110
5111static Instruction *foldICmpXNegX(ICmpInst &I,
5112 InstCombiner::BuilderTy &Builder) {
5113 CmpPredicate Pred;
5114 Value *X;
5115 if (match(V: &I, P: m_c_ICmp(Pred, L: m_NSWNeg(V: m_Value(V&: X)), R: m_Deferred(V: X)))) {
5116
5117 if (ICmpInst::isSigned(Pred))
5118 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5119 else if (ICmpInst::isUnsigned(Pred))
5120 Pred = ICmpInst::getSignedPredicate(Pred);
5121 // else for equality-comparisons just keep the predicate.
5122
5123 return ICmpInst::Create(Op: Instruction::ICmp, Pred, S1: X,
5124 S2: Constant::getNullValue(Ty: X->getType()), Name: I.getName());
5125 }
5126
5127 // A value is not equal to its negation unless that value is 0 or
5128 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
5129 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))) &&
5130 ICmpInst::isEquality(P: Pred)) {
5131 Type *Ty = X->getType();
5132 uint32_t BitWidth = Ty->getScalarSizeInBits();
5133 Constant *MaxSignedVal =
5134 ConstantInt::get(Ty, V: APInt::getSignedMaxValue(numBits: BitWidth));
5135 Value *And = Builder.CreateAnd(LHS: X, RHS: MaxSignedVal);
5136 Constant *Zero = Constant::getNullValue(Ty);
5137 return CmpInst::Create(Op: Instruction::ICmp, Pred, S1: And, S2: Zero);
5138 }
5139
5140 return nullptr;
5141}
5142
5143static Instruction *foldICmpAndXX(ICmpInst &I, const SimplifyQuery &Q,
5144 InstCombinerImpl &IC) {
5145 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *A;
5146 // Normalize and operand as operand 0.
5147 CmpInst::Predicate Pred = I.getPredicate();
5148 if (match(V: Op1, P: m_c_And(L: m_Specific(V: Op0), R: m_Value()))) {
5149 std::swap(a&: Op0, b&: Op1);
5150 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5151 }
5152
5153 if (!match(V: Op0, P: m_c_And(L: m_Specific(V: Op1), R: m_Value(V&: A))))
5154 return nullptr;
5155
5156 // (icmp (X & Y) u< X --> (X & Y) != X
5157 if (Pred == ICmpInst::ICMP_ULT)
5158 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5159
5160 // (icmp (X & Y) u>= X --> (X & Y) == X
5161 if (Pred == ICmpInst::ICMP_UGE)
5162 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5163
5164 if (ICmpInst::isEquality(P: Pred) && Op0->hasOneUse()) {
5165 // icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and
5166 // Y is non-constant. If Y is constant the `X & C == C` form is preferable
5167 // so don't do this fold.
5168 if (!match(V: Op1, P: m_ImmConstant()))
5169 if (auto *NotOp1 =
5170 IC.getFreelyInverted(V: Op1, WillInvertAllUses: !Op1->hasNUsesOrMore(N: 3), Builder: &IC.Builder))
5171 return new ICmpInst(Pred, IC.Builder.CreateOr(LHS: A, RHS: NotOp1),
5172 Constant::getAllOnesValue(Ty: Op1->getType()));
5173 // icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.
5174 if (auto *NotA = IC.getFreelyInverted(V: A, WillInvertAllUses: A->hasOneUse(), Builder: &IC.Builder))
5175 return new ICmpInst(Pred, IC.Builder.CreateAnd(LHS: Op1, RHS: NotA),
5176 Constant::getNullValue(Ty: Op1->getType()));
5177 }
5178
5179 if (!ICmpInst::isSigned(Pred))
5180 return nullptr;
5181
5182 KnownBits KnownY = IC.computeKnownBits(V: A, CxtI: &I);
5183 // (X & NegY) spred X --> (X & NegY) upred X
5184 if (KnownY.isNegative())
5185 return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);
5186
5187 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGT)
5188 return nullptr;
5189
5190 if (KnownY.isNonNegative())
5191 // (X & PosY) s<= X --> X s>= 0
5192 // (X & PosY) s> X --> X s< 0
5193 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
5194 Constant::getNullValue(Ty: Op1->getType()));
5195
5196 if (isKnownNegative(V: Op1, SQ: IC.getSimplifyQuery().getWithInstruction(I: &I)))
5197 // (NegX & Y) s<= NegX --> Y s< 0
5198 // (NegX & Y) s> NegX --> Y s>= 0
5199 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), A,
5200 Constant::getNullValue(Ty: A->getType()));
5201
5202 return nullptr;
5203}
5204
5205static Instruction *foldICmpOrXX(ICmpInst &I, const SimplifyQuery &Q,
5206 InstCombinerImpl &IC) {
5207 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *A;
5208
5209 // Normalize or operand as operand 0.
5210 CmpInst::Predicate Pred = I.getPredicate();
5211 if (match(V: Op1, P: m_c_Or(L: m_Specific(V: Op0), R: m_Value(V&: A)))) {
5212 std::swap(a&: Op0, b&: Op1);
5213 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5214 } else if (!match(V: Op0, P: m_c_Or(L: m_Specific(V: Op1), R: m_Value(V&: A)))) {
5215 return nullptr;
5216 }
5217
5218 // icmp (X | Y) u<= X --> (X | Y) == X
5219 if (Pred == ICmpInst::ICMP_ULE)
5220 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5221
5222 // icmp (X | Y) u> X --> (X | Y) != X
5223 if (Pred == ICmpInst::ICMP_UGT)
5224 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5225
5226 if (ICmpInst::isEquality(P: Pred) && Op0->hasOneUse()) {
5227 // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
5228 if (Value *NotOp1 = IC.getFreelyInverted(
5229 V: Op1, WillInvertAllUses: !isa<Constant>(Val: Op1) && !Op1->hasNUsesOrMore(N: 3), Builder: &IC.Builder))
5230 return new ICmpInst(Pred, IC.Builder.CreateAnd(LHS: A, RHS: NotOp1),
5231 Constant::getNullValue(Ty: Op1->getType()));
5232 // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.
5233 if (Value *NotA = IC.getFreelyInverted(V: A, WillInvertAllUses: A->hasOneUse(), Builder: &IC.Builder))
5234 return new ICmpInst(Pred, IC.Builder.CreateOr(LHS: Op1, RHS: NotA),
5235 Constant::getAllOnesValue(Ty: Op1->getType()));
5236 }
5237 return nullptr;
5238}
5239
5240static Instruction *foldICmpXorXX(ICmpInst &I, const SimplifyQuery &Q,
5241 InstCombinerImpl &IC) {
5242 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *A;
5243 // Normalize xor operand as operand 0.
5244 CmpInst::Predicate Pred = I.getPredicate();
5245 if (match(V: Op1, P: m_c_Xor(L: m_Specific(V: Op0), R: m_Value()))) {
5246 std::swap(a&: Op0, b&: Op1);
5247 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5248 }
5249 if (!match(V: Op0, P: m_c_Xor(L: m_Specific(V: Op1), R: m_Value(V&: A))))
5250 return nullptr;
5251
5252 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
5253 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
5254 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
5255 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
5256 CmpInst::Predicate PredOut = CmpInst::getStrictPredicate(pred: Pred);
5257 if (PredOut != Pred && isKnownNonZero(V: A, Q))
5258 return new ICmpInst(PredOut, Op0, Op1);
5259
5260 // These transform work when A is negative.
5261 // X s< X^A, X s<= X^A, X u> X^A, X u>= X^A --> X s< 0
5262 // X s> X^A, X s>= X^A, X u< X^A, X u<= X^A --> X s>= 0
5263 if (match(V: A, P: m_Negative())) {
5264 CmpInst::Predicate NewPred;
5265 switch (ICmpInst::getStrictPredicate(pred: Pred)) {
5266 default:
5267 return nullptr;
5268 case ICmpInst::ICMP_SLT:
5269 case ICmpInst::ICMP_UGT:
5270 NewPred = ICmpInst::ICMP_SLT;
5271 break;
5272 case ICmpInst::ICMP_SGT:
5273 case ICmpInst::ICMP_ULT:
5274 NewPred = ICmpInst::ICMP_SGE;
5275 break;
5276 }
5277 Constant *Const = Constant::getNullValue(Ty: Op0->getType());
5278 return new ICmpInst(NewPred, Op0, Const);
5279 }
5280
5281 return nullptr;
5282}
5283
5284/// Return true if X is a multiple of C.
5285/// TODO: Handle non-power-of-2 factors.
5286static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q) {
5287 if (C.isOne())
5288 return true;
5289
5290 if (!C.isPowerOf2())
5291 return false;
5292
5293 return MaskedValueIsZero(V: X, Mask: C - 1, SQ: Q);
5294}
5295
5296/// Try to fold icmp (binop), X or icmp X, (binop).
5297/// TODO: A large part of this logic is duplicated in InstSimplify's
5298/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
5299/// duplication.
5300Instruction *InstCombinerImpl::foldICmpBinOp(ICmpInst &I,
5301 const SimplifyQuery &SQ) {
5302 const SimplifyQuery Q = SQ.getWithInstruction(I: &I);
5303 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
5304
5305 // Special logic for binary operators.
5306 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Val: Op0);
5307 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Val: Op1);
5308 if (!BO0 && !BO1)
5309 return nullptr;
5310
5311 if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
5312 return NewICmp;
5313
5314 const CmpInst::Predicate Pred = I.getPredicate();
5315 Value *X;
5316
5317 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
5318 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
5319 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: Op1), R: m_Value(V&: X)))) &&
5320 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5321 return new ICmpInst(Pred, Builder.CreateNot(V: Op1), X);
5322 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
5323 if (match(V: Op1, P: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: Op0), R: m_Value(V&: X)))) &&
5324 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5325 return new ICmpInst(Pred, X, Builder.CreateNot(V: Op0));
5326
5327 {
5328 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
5329 Constant *C;
5330 if (match(V: Op0, P: m_OneUse(SubPattern: m_Add(L: m_c_Add(L: m_Specific(V: Op1), R: m_Value(V&: X)),
5331 R: m_ImmConstant(C)))) &&
5332 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
5333 Constant *C2 = ConstantExpr::getNot(C);
5334 return new ICmpInst(Pred, Builder.CreateSub(LHS: C2, RHS: X), Op1);
5335 }
5336 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
5337 if (match(V: Op1, P: m_OneUse(SubPattern: m_Add(L: m_c_Add(L: m_Specific(V: Op0), R: m_Value(V&: X)),
5338 R: m_ImmConstant(C)))) &&
5339 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
5340 Constant *C2 = ConstantExpr::getNot(C);
5341 return new ICmpInst(Pred, Op0, Builder.CreateSub(LHS: C2, RHS: X));
5342 }
5343 }
5344
5345 // (icmp eq/ne (X, -P2), INT_MIN)
5346 // -> (icmp slt/sge X, INT_MIN + P2)
5347 if (ICmpInst::isEquality(P: Pred) && BO0 &&
5348 match(V: I.getOperand(i_nocapture: 1), P: m_SignMask()) &&
5349 match(V: BO0, P: m_And(L: m_Value(), R: m_NegatedPower2OrZero()))) {
5350 // Will Constant fold.
5351 Value *NewC = Builder.CreateSub(LHS: I.getOperand(i_nocapture: 1), RHS: BO0->getOperand(i_nocapture: 1));
5352 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SLT
5353 : ICmpInst::ICMP_SGE,
5354 BO0->getOperand(i_nocapture: 0), NewC);
5355 }
5356
5357 {
5358 // Similar to above: an unsigned overflow comparison may use offset + mask:
5359 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
5360 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
5361 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
5362 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
5363 BinaryOperator *BO;
5364 const APInt *C;
5365 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
5366 match(V: Op0, P: m_And(L: m_BinOp(I&: BO), R: m_LowBitMask(V&: C))) &&
5367 match(V: BO, P: m_Add(L: m_Specific(V: Op1), R: m_SpecificIntAllowPoison(V: *C)))) {
5368 CmpInst::Predicate NewPred =
5369 Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
5370 Constant *Zero = ConstantInt::getNullValue(Ty: Op1->getType());
5371 return new ICmpInst(NewPred, Op1, Zero);
5372 }
5373
5374 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5375 match(V: Op1, P: m_And(L: m_BinOp(I&: BO), R: m_LowBitMask(V&: C))) &&
5376 match(V: BO, P: m_Add(L: m_Specific(V: Op0), R: m_SpecificIntAllowPoison(V: *C)))) {
5377 CmpInst::Predicate NewPred =
5378 Pred == ICmpInst::ICMP_UGT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
5379 Constant *Zero = ConstantInt::getNullValue(Ty: Op1->getType());
5380 return new ICmpInst(NewPred, Op0, Zero);
5381 }
5382 }
5383
5384 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
5385 bool Op0HasNUW = false, Op1HasNUW = false;
5386 bool Op0HasNSW = false, Op1HasNSW = false;
5387 // Analyze the case when either Op0 or Op1 is an add instruction.
5388 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
5389 auto hasNoWrapProblem = [](const BinaryOperator &BO, CmpInst::Predicate Pred,
5390 bool &HasNSW, bool &HasNUW) -> bool {
5391 if (isa<OverflowingBinaryOperator>(Val: BO)) {
5392 HasNUW = BO.hasNoUnsignedWrap();
5393 HasNSW = BO.hasNoSignedWrap();
5394 return ICmpInst::isEquality(P: Pred) ||
5395 (CmpInst::isUnsigned(Pred) && HasNUW) ||
5396 (CmpInst::isSigned(Pred) && HasNSW);
5397 } else if (BO.getOpcode() == Instruction::Or) {
5398 HasNUW = true;
5399 HasNSW = true;
5400 return true;
5401 } else {
5402 return false;
5403 }
5404 };
5405 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5406
5407 if (BO0) {
5408 match(V: BO0, P: m_AddLike(L: m_Value(V&: A), R: m_Value(V&: B)));
5409 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5410 }
5411 if (BO1) {
5412 match(V: BO1, P: m_AddLike(L: m_Value(V&: C), R: m_Value(V&: D)));
5413 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5414 }
5415
5416 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5417 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5418 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5419 return new ICmpInst(Pred, A == Op1 ? B : A,
5420 Constant::getNullValue(Ty: Op1->getType()));
5421
5422 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5423 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5424 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5425 return new ICmpInst(Pred, Constant::getNullValue(Ty: Op0->getType()),
5426 C == Op0 ? D : C);
5427
5428 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
5429 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
5430 NoOp1WrapProblem) {
5431 // Determine Y and Z in the form icmp (X+Y), (X+Z).
5432 Value *Y, *Z;
5433 if (A == C) {
5434 // C + B == C + D -> B == D
5435 Y = B;
5436 Z = D;
5437 } else if (A == D) {
5438 // D + B == C + D -> B == C
5439 Y = B;
5440 Z = C;
5441 } else if (B == C) {
5442 // A + C == C + D -> A == D
5443 Y = A;
5444 Z = D;
5445 } else {
5446 assert(B == D);
5447 // A + D == C + D -> A == C
5448 Y = A;
5449 Z = C;
5450 }
5451 return new ICmpInst(Pred, Y, Z);
5452 }
5453
5454 if (ICmpInst::isRelational(P: Pred)) {
5455 // Return if both X and Y is divisible by Z/-Z.
5456 // TODO: Generalize to check if (X - Y) is divisible by Z/-Z.
5457 auto ShareCommonDivisor = [&Q](Value *X, Value *Y, Value *Z,
5458 bool IsNegative) -> bool {
5459 const APInt *OffsetC;
5460 if (!match(V: Z, P: m_APInt(Res&: OffsetC)))
5461 return false;
5462
5463 // Fast path for Z == 1/-1.
5464 if (IsNegative ? OffsetC->isAllOnes() : OffsetC->isOne())
5465 return true;
5466
5467 APInt C = *OffsetC;
5468 if (IsNegative)
5469 C.negate();
5470 // Note: -INT_MIN is also negative.
5471 if (!C.isStrictlyPositive())
5472 return false;
5473
5474 return isMultipleOf(X, C, Q) && isMultipleOf(X: Y, C, Q);
5475 };
5476
5477 // TODO: The subtraction-related identities shown below also hold, but
5478 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
5479 // wouldn't happen even if they were implemented.
5480 //
5481 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5482 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5483 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5484 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5485
5486 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5487 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5488 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5489 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5490 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5491 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5492 if (A && NoOp0WrapProblem &&
5493 ShareCommonDivisor(A, Op1, B,
5494 ICmpInst::isLT(P: Pred) || ICmpInst::isGE(P: Pred)))
5495 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), A,
5496 Op1);
5497
5498 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5499 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5500 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5501 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5502 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5503 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5504 if (C && NoOp1WrapProblem &&
5505 ShareCommonDivisor(Op0, C, D,
5506 ICmpInst::isGT(P: Pred) || ICmpInst::isLE(P: Pred)))
5507 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), Op0,
5508 C);
5509 }
5510
5511 // if C1 has greater magnitude than C2:
5512 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5513 // s.t. C3 = C1 - C2
5514 //
5515 // if C2 has greater magnitude than C1:
5516 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5517 // s.t. C3 = C2 - C1
5518 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5519 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5520 const APInt *AP1, *AP2;
5521 // TODO: Support non-uniform vectors.
5522 // TODO: Allow poison passthrough if B or D's element is poison.
5523 if (match(V: B, P: m_APIntAllowPoison(Res&: AP1)) &&
5524 match(V: D, P: m_APIntAllowPoison(Res&: AP2)) &&
5525 AP1->isNegative() == AP2->isNegative()) {
5526 APInt AP1Abs = AP1->abs();
5527 APInt AP2Abs = AP2->abs();
5528 if (AP1Abs.uge(RHS: AP2Abs)) {
5529 APInt Diff = *AP1 - *AP2;
5530 Constant *C3 = Constant::getIntegerValue(Ty: BO0->getType(), V: Diff);
5531 Value *NewAdd = Builder.CreateAdd(
5532 LHS: A, RHS: C3, Name: "", HasNUW: Op0HasNUW && Diff.ule(RHS: *AP1), HasNSW: Op0HasNSW);
5533 return new ICmpInst(Pred, NewAdd, C);
5534 } else {
5535 APInt Diff = *AP2 - *AP1;
5536 Constant *C3 = Constant::getIntegerValue(Ty: BO0->getType(), V: Diff);
5537 Value *NewAdd = Builder.CreateAdd(
5538 LHS: C, RHS: C3, Name: "", HasNUW: Op1HasNUW && Diff.ule(RHS: *AP2), HasNSW: Op1HasNSW);
5539 return new ICmpInst(Pred, A, NewAdd);
5540 }
5541 }
5542 Constant *Cst1, *Cst2;
5543 if (match(V: B, P: m_ImmConstant(C&: Cst1)) && match(V: D, P: m_ImmConstant(C&: Cst2)) &&
5544 ICmpInst::isEquality(P: Pred)) {
5545 Constant *Diff = ConstantExpr::getSub(C1: Cst2, C2: Cst1);
5546 Value *NewAdd = Builder.CreateAdd(LHS: C, RHS: Diff);
5547 return new ICmpInst(Pred, A, NewAdd);
5548 }
5549 }
5550
5551 // Analyze the case when either Op0 or Op1 is a sub instruction.
5552 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5553 A = nullptr;
5554 B = nullptr;
5555 C = nullptr;
5556 D = nullptr;
5557 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5558 A = BO0->getOperand(i_nocapture: 0);
5559 B = BO0->getOperand(i_nocapture: 1);
5560 }
5561 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5562 C = BO1->getOperand(i_nocapture: 0);
5563 D = BO1->getOperand(i_nocapture: 1);
5564 }
5565
5566 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5567 if (A == Op1 && NoOp0WrapProblem)
5568 return new ICmpInst(Pred, Constant::getNullValue(Ty: Op1->getType()), B);
5569 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5570 if (C == Op0 && NoOp1WrapProblem)
5571 return new ICmpInst(Pred, D, Constant::getNullValue(Ty: Op0->getType()));
5572
5573 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5574 // (A - B) u>/u<= A --> B u>/u<= A
5575 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5576 return new ICmpInst(Pred, B, A);
5577 // C u</u>= (C - D) --> C u</u>= D
5578 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5579 return new ICmpInst(Pred, C, D);
5580 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5581 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5582 isKnownNonZero(V: B, Q))
5583 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(pred: Pred), B, A);
5584 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5585 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5586 isKnownNonZero(V: D, Q))
5587 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(pred: Pred), C, D);
5588
5589 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
5590 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
5591 return new ICmpInst(Pred, A, C);
5592
5593 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
5594 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
5595 return new ICmpInst(Pred, D, B);
5596
5597 // icmp (0-X) < cst --> x > -cst
5598 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
5599 Value *X;
5600 if (match(V: BO0, P: m_Neg(V: m_Value(V&: X))))
5601 if (Constant *RHSC = dyn_cast<Constant>(Val: Op1))
5602 if (RHSC->isNotMinSignedValue())
5603 return new ICmpInst(I.getSwappedPredicate(), X,
5604 ConstantExpr::getNeg(C: RHSC));
5605 }
5606
5607 if (Instruction *R = foldICmpXorXX(I, Q, IC&: *this))
5608 return R;
5609 if (Instruction *R = foldICmpOrXX(I, Q, IC&: *this))
5610 return R;
5611
5612 {
5613 // Try to remove shared multiplier from comparison:
5614 // X * Z pred Y * Z
5615 Value *X, *Y, *Z;
5616 if ((match(V: Op0, P: m_Mul(L: m_Value(V&: X), R: m_Value(V&: Z))) &&
5617 match(V: Op1, P: m_c_Mul(L: m_Specific(V: Z), R: m_Value(V&: Y)))) ||
5618 (match(V: Op0, P: m_Mul(L: m_Value(V&: Z), R: m_Value(V&: X))) &&
5619 match(V: Op1, P: m_c_Mul(L: m_Specific(V: Z), R: m_Value(V&: Y))))) {
5620 if (ICmpInst::isSigned(Pred)) {
5621 if (Op0HasNSW && Op1HasNSW) {
5622 KnownBits ZKnown = computeKnownBits(V: Z, CxtI: &I);
5623 if (ZKnown.isStrictlyPositive())
5624 return new ICmpInst(Pred, X, Y);
5625 if (ZKnown.isNegative())
5626 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), X, Y);
5627 Value *LessThan = simplifyICmpInst(Pred: ICmpInst::ICMP_SLT, LHS: X, RHS: Y,
5628 Q: SQ.getWithInstruction(I: &I));
5629 if (LessThan && match(V: LessThan, P: m_One()))
5630 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Z,
5631 Constant::getNullValue(Ty: Z->getType()));
5632 Value *GreaterThan = simplifyICmpInst(Pred: ICmpInst::ICMP_SGT, LHS: X, RHS: Y,
5633 Q: SQ.getWithInstruction(I: &I));
5634 if (GreaterThan && match(V: GreaterThan, P: m_One()))
5635 return new ICmpInst(Pred, Z, Constant::getNullValue(Ty: Z->getType()));
5636 }
5637 } else {
5638 bool NonZero;
5639 if (ICmpInst::isEquality(P: Pred)) {
5640 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5641 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5642 isKnownNonEqual(V1: X, V2: Y, SQ))
5643 return new ICmpInst(Pred, Z, Constant::getNullValue(Ty: Z->getType()));
5644
5645 KnownBits ZKnown = computeKnownBits(V: Z, CxtI: &I);
5646 // if Z % 2 != 0
5647 // X * Z eq/ne Y * Z -> X eq/ne Y
5648 if (ZKnown.countMaxTrailingZeros() == 0)
5649 return new ICmpInst(Pred, X, Y);
5650 NonZero = !ZKnown.One.isZero() || isKnownNonZero(V: Z, Q);
5651 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5652 // X * Z eq/ne Y * Z -> X eq/ne Y
5653 if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)
5654 return new ICmpInst(Pred, X, Y);
5655 } else
5656 NonZero = isKnownNonZero(V: Z, Q);
5657
5658 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5659 // X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
5660 if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)
5661 return new ICmpInst(Pred, X, Y);
5662 }
5663 }
5664 }
5665
5666 BinaryOperator *SRem = nullptr;
5667 // icmp (srem X, Y), Y
5668 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(i_nocapture: 1))
5669 SRem = BO0;
5670 // icmp Y, (srem X, Y)
5671 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5672 Op0 == BO1->getOperand(i_nocapture: 1))
5673 SRem = BO1;
5674 if (SRem) {
5675 // We don't check hasOneUse to avoid increasing register pressure because
5676 // the value we use is the same value this instruction was already using.
5677 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(pred: Pred) : Pred) {
5678 default:
5679 break;
5680 case ICmpInst::ICMP_EQ:
5681 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
5682 case ICmpInst::ICMP_NE:
5683 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
5684 case ICmpInst::ICMP_SGT:
5685 case ICmpInst::ICMP_SGE:
5686 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(i_nocapture: 1),
5687 Constant::getAllOnesValue(Ty: SRem->getType()));
5688 case ICmpInst::ICMP_SLT:
5689 case ICmpInst::ICMP_SLE:
5690 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(i_nocapture: 1),
5691 Constant::getNullValue(Ty: SRem->getType()));
5692 }
5693 }
5694
5695 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5696 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5697 BO0->getOperand(i_nocapture: 1) == BO1->getOperand(i_nocapture: 1)) {
5698 switch (BO0->getOpcode()) {
5699 default:
5700 break;
5701 case Instruction::Add:
5702 case Instruction::Sub:
5703 case Instruction::Xor: {
5704 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5705 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5706
5707 const APInt *C;
5708 if (match(V: BO0->getOperand(i_nocapture: 1), P: m_APInt(Res&: C))) {
5709 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5710 if (C->isSignMask()) {
5711 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5712 return new ICmpInst(NewPred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5713 }
5714
5715 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5716 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5717 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5718 NewPred = I.getSwappedPredicate(pred: NewPred);
5719 return new ICmpInst(NewPred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5720 }
5721 }
5722 break;
5723 }
5724 case Instruction::Mul: {
5725 if (!I.isEquality())
5726 break;
5727
5728 const APInt *C;
5729 if (match(V: BO0->getOperand(i_nocapture: 1), P: m_APInt(Res&: C)) && !C->isZero() &&
5730 !C->isOne()) {
5731 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5732 // Mask = -1 >> count-trailing-zeros(C).
5733 if (unsigned TZs = C->countr_zero()) {
5734 Constant *Mask = ConstantInt::get(
5735 Ty: BO0->getType(),
5736 V: APInt::getLowBitsSet(numBits: C->getBitWidth(), loBitsSet: C->getBitWidth() - TZs));
5737 Value *And1 = Builder.CreateAnd(LHS: BO0->getOperand(i_nocapture: 0), RHS: Mask);
5738 Value *And2 = Builder.CreateAnd(LHS: BO1->getOperand(i_nocapture: 0), RHS: Mask);
5739 return new ICmpInst(Pred, And1, And2);
5740 }
5741 }
5742 break;
5743 }
5744 case Instruction::UDiv:
5745 case Instruction::LShr:
5746 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
5747 break;
5748 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5749
5750 case Instruction::SDiv:
5751 if (!(I.isEquality() || match(V: BO0->getOperand(i_nocapture: 1), P: m_NonNegative())) ||
5752 !BO0->isExact() || !BO1->isExact())
5753 break;
5754 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5755
5756 case Instruction::AShr:
5757 if (!BO0->isExact() || !BO1->isExact())
5758 break;
5759 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5760
5761 case Instruction::Shl: {
5762 bool NUW = Op0HasNUW && Op1HasNUW;
5763 bool NSW = Op0HasNSW && Op1HasNSW;
5764 if (!NUW && !NSW)
5765 break;
5766 if (!NSW && I.isSigned())
5767 break;
5768 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5769 }
5770 }
5771 }
5772
5773 if (BO0) {
5774 // Transform A & (L - 1) `ult` L --> L != 0
5775 auto LSubOne = m_Add(L: m_Specific(V: Op1), R: m_AllOnes());
5776 auto BitwiseAnd = m_c_And(L: m_Value(), R: LSubOne);
5777
5778 if (match(V: BO0, P: BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5779 auto *Zero = Constant::getNullValue(Ty: BO0->getType());
5780 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5781 }
5782 }
5783
5784 // For unsigned predicates / eq / ne:
5785 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5786 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5787 if (!ICmpInst::isSigned(Pred)) {
5788 if (match(V: Op0, P: m_Shl(L: m_Specific(V: Op1), R: m_One())))
5789 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5790 Constant::getNullValue(Ty: Op1->getType()));
5791 else if (match(V: Op1, P: m_Shl(L: m_Specific(V: Op0), R: m_One())))
5792 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5793 Constant::getNullValue(Ty: Op0->getType()), Op0);
5794 }
5795
5796 if (Value *V = foldMultiplicationOverflowCheck(I))
5797 return replaceInstUsesWith(I, V);
5798
5799 if (Instruction *R = foldICmpAndXX(I, Q, IC&: *this))
5800 return R;
5801
5802 if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder))
5803 return replaceInstUsesWith(I, V);
5804
5805 if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder))
5806 return replaceInstUsesWith(I, V);
5807
5808 return nullptr;
5809}
5810
5811/// Fold icmp Pred min|max(X, Y), Z.
5812Instruction *InstCombinerImpl::foldICmpWithMinMax(Instruction &I,
5813 MinMaxIntrinsic *MinMax,
5814 Value *Z, CmpPredicate Pred) {
5815 Value *X = MinMax->getLHS();
5816 Value *Y = MinMax->getRHS();
5817 if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5818 return nullptr;
5819 if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {
5820 // Revert the transform signed pred -> unsigned pred
5821 // TODO: We can flip the signedness of predicate if both operands of icmp
5822 // are negative.
5823 if (isKnownNonNegative(V: Z, SQ: SQ.getWithInstruction(I: &I)) &&
5824 isKnownNonNegative(V: MinMax, SQ: SQ.getWithInstruction(I: &I))) {
5825 Pred = ICmpInst::getFlippedSignednessPredicate(Pred);
5826 } else
5827 return nullptr;
5828 }
5829 SimplifyQuery Q = SQ.getWithInstruction(I: &I);
5830 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5831 if (!Val)
5832 return std::nullopt;
5833 if (match(V: Val, P: m_One()))
5834 return true;
5835 if (match(V: Val, P: m_Zero()))
5836 return false;
5837 return std::nullopt;
5838 };
5839 // Remove samesign here since it is illegal to keep it when we speculatively
5840 // execute comparisons. For example, `icmp samesign ult umax(X, -46), -32`
5841 // cannot be decomposed into `(icmp samesign ult X, -46) or (icmp samesign ult
5842 // -46, -32)`. `X` is allowed to be non-negative here.
5843 Pred = Pred.dropSameSign();
5844 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, LHS: X, RHS: Z, Q));
5845 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, LHS: Y, RHS: Z, Q));
5846 if (!CmpXZ.has_value() && !CmpYZ.has_value())
5847 return nullptr;
5848 if (!CmpXZ.has_value()) {
5849 std::swap(a&: X, b&: Y);
5850 std::swap(lhs&: CmpXZ, rhs&: CmpYZ);
5851 }
5852
5853 auto FoldIntoCmpYZ = [&]() -> Instruction * {
5854 if (CmpYZ.has_value())
5855 return replaceInstUsesWith(I, V: ConstantInt::getBool(Ty: I.getType(), V: *CmpYZ));
5856 return ICmpInst::Create(Op: Instruction::ICmp, Pred, S1: Y, S2: Z);
5857 };
5858
5859 switch (Pred) {
5860 case ICmpInst::ICMP_EQ:
5861 case ICmpInst::ICMP_NE: {
5862 // If X == Z:
5863 // Expr Result
5864 // min(X, Y) == Z X <= Y
5865 // max(X, Y) == Z X >= Y
5866 // min(X, Y) != Z X > Y
5867 // max(X, Y) != Z X < Y
5868 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5869 ICmpInst::Predicate NewPred =
5870 ICmpInst::getNonStrictPredicate(pred: MinMax->getPredicate());
5871 if (Pred == ICmpInst::ICMP_NE)
5872 NewPred = ICmpInst::getInversePredicate(pred: NewPred);
5873 return ICmpInst::Create(Op: Instruction::ICmp, Pred: NewPred, S1: X, S2: Y);
5874 }
5875 // Otherwise (X != Z):
5876 ICmpInst::Predicate NewPred = MinMax->getPredicate();
5877 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred: NewPred, LHS: X, RHS: Z, Q));
5878 if (!MinMaxCmpXZ.has_value()) {
5879 std::swap(a&: X, b&: Y);
5880 std::swap(lhs&: CmpXZ, rhs&: CmpYZ);
5881 // Re-check pre-condition X != Z
5882 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5883 break;
5884 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred: NewPred, LHS: X, RHS: Z, Q));
5885 }
5886 if (!MinMaxCmpXZ.has_value())
5887 break;
5888 if (*MinMaxCmpXZ) {
5889 // Expr Fact Result
5890 // min(X, Y) == Z X < Z false
5891 // max(X, Y) == Z X > Z false
5892 // min(X, Y) != Z X < Z true
5893 // max(X, Y) != Z X > Z true
5894 return replaceInstUsesWith(
5895 I, V: ConstantInt::getBool(Ty: I.getType(), V: Pred == ICmpInst::ICMP_NE));
5896 } else {
5897 // Expr Fact Result
5898 // min(X, Y) == Z X > Z Y == Z
5899 // max(X, Y) == Z X < Z Y == Z
5900 // min(X, Y) != Z X > Z Y != Z
5901 // max(X, Y) != Z X < Z Y != Z
5902 return FoldIntoCmpYZ();
5903 }
5904 break;
5905 }
5906 case ICmpInst::ICMP_SLT:
5907 case ICmpInst::ICMP_ULT:
5908 case ICmpInst::ICMP_SLE:
5909 case ICmpInst::ICMP_ULE:
5910 case ICmpInst::ICMP_SGT:
5911 case ICmpInst::ICMP_UGT:
5912 case ICmpInst::ICMP_SGE:
5913 case ICmpInst::ICMP_UGE: {
5914 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(pred: Pred);
5915 if (*CmpXZ) {
5916 if (IsSame) {
5917 // Expr Fact Result
5918 // min(X, Y) < Z X < Z true
5919 // min(X, Y) <= Z X <= Z true
5920 // max(X, Y) > Z X > Z true
5921 // max(X, Y) >= Z X >= Z true
5922 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
5923 } else {
5924 // Expr Fact Result
5925 // max(X, Y) < Z X < Z Y < Z
5926 // max(X, Y) <= Z X <= Z Y <= Z
5927 // min(X, Y) > Z X > Z Y > Z
5928 // min(X, Y) >= Z X >= Z Y >= Z
5929 return FoldIntoCmpYZ();
5930 }
5931 } else {
5932 if (IsSame) {
5933 // Expr Fact Result
5934 // min(X, Y) < Z X >= Z Y < Z
5935 // min(X, Y) <= Z X > Z Y <= Z
5936 // max(X, Y) > Z X <= Z Y > Z
5937 // max(X, Y) >= Z X < Z Y >= Z
5938 return FoldIntoCmpYZ();
5939 } else {
5940 // Expr Fact Result
5941 // max(X, Y) < Z X >= Z false
5942 // max(X, Y) <= Z X > Z false
5943 // min(X, Y) > Z X <= Z false
5944 // min(X, Y) >= Z X < Z false
5945 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
5946 }
5947 }
5948 break;
5949 }
5950 default:
5951 break;
5952 }
5953
5954 return nullptr;
5955}
5956
5957/// Match and fold patterns like:
5958/// icmp eq/ne X, min(max(X, Lo), Hi)
5959/// which represents a range check and can be represented as a ConstantRange.
5960///
5961/// For icmp eq, build ConstantRange [Lo, Hi + 1) and convert to:
5962/// (X - Lo) u< (Hi + 1 - Lo)
5963/// For icmp ne, build ConstantRange [Hi + 1, Lo) and convert to:
5964/// (X - (Hi + 1)) u< (Lo - (Hi + 1))
5965Instruction *InstCombinerImpl::foldICmpWithClamp(ICmpInst &I, Value *X,
5966 MinMaxIntrinsic *Min) {
5967 if (!I.isEquality() || !Min->hasOneUse() || !Min->isMin())
5968 return nullptr;
5969
5970 const APInt *Lo = nullptr, *Hi = nullptr;
5971 if (Min->isSigned()) {
5972 if (!match(V: Min->getLHS(), P: m_OneUse(SubPattern: m_SMax(Op0: m_Specific(V: X), Op1: m_APInt(Res&: Lo)))) ||
5973 !match(V: Min->getRHS(), P: m_APInt(Res&: Hi)) || !Lo->slt(RHS: *Hi))
5974 return nullptr;
5975 } else {
5976 if (!match(V: Min->getLHS(), P: m_OneUse(SubPattern: m_UMax(Op0: m_Specific(V: X), Op1: m_APInt(Res&: Lo)))) ||
5977 !match(V: Min->getRHS(), P: m_APInt(Res&: Hi)) || !Lo->ult(RHS: *Hi))
5978 return nullptr;
5979 }
5980
5981 ConstantRange CR = ConstantRange::getNonEmpty(Lower: *Lo, Upper: *Hi + 1);
5982 ICmpInst::Predicate Pred;
5983 APInt C, Offset;
5984 if (I.getPredicate() == ICmpInst::ICMP_EQ)
5985 CR.getEquivalentICmp(Pred, RHS&: C, Offset);
5986 else
5987 CR.inverse().getEquivalentICmp(Pred, RHS&: C, Offset);
5988
5989 if (!Offset.isZero())
5990 X = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: Offset));
5991
5992 return replaceInstUsesWith(
5993 I, V: Builder.CreateICmp(P: Pred, LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: C)));
5994}
5995
5996// Canonicalize checking for a power-of-2-or-zero value:
5997static Instruction *foldICmpPow2Test(ICmpInst &I,
5998 InstCombiner::BuilderTy &Builder) {
5999 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
6000 const CmpInst::Predicate Pred = I.getPredicate();
6001 Value *A = nullptr;
6002 bool CheckIs;
6003 if (I.isEquality()) {
6004 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
6005 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
6006 if (!match(V: Op0, P: m_OneUse(SubPattern: m_c_And(L: m_Add(L: m_Value(V&: A), R: m_AllOnes()),
6007 R: m_Deferred(V: A)))) ||
6008 !match(V: Op1, P: m_ZeroInt()))
6009 A = nullptr;
6010
6011 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
6012 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
6013 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_And(L: m_Neg(V: m_Specific(V: Op1)), R: m_Specific(V: Op1)))))
6014 A = Op1;
6015 else if (match(V: Op1,
6016 P: m_OneUse(SubPattern: m_c_And(L: m_Neg(V: m_Specific(V: Op0)), R: m_Specific(V: Op0)))))
6017 A = Op0;
6018
6019 CheckIs = Pred == ICmpInst::ICMP_EQ;
6020 } else if (ICmpInst::isUnsigned(Pred)) {
6021 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
6022 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
6023
6024 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
6025 match(V: Op0, P: m_OneUse(SubPattern: m_c_Xor(L: m_Add(L: m_Specific(V: Op1), R: m_AllOnes()),
6026 R: m_Specific(V: Op1))))) {
6027 A = Op1;
6028 CheckIs = Pred == ICmpInst::ICMP_UGE;
6029 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
6030 match(V: Op1, P: m_OneUse(SubPattern: m_c_Xor(L: m_Add(L: m_Specific(V: Op0), R: m_AllOnes()),
6031 R: m_Specific(V: Op0))))) {
6032 A = Op0;
6033 CheckIs = Pred == ICmpInst::ICMP_ULE;
6034 }
6035 }
6036
6037 if (A) {
6038 Type *Ty = A->getType();
6039 Value *CtPop = Builder.CreateUnaryIntrinsic(ID: Intrinsic::ctpop, Op: A);
6040 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
6041 ConstantInt::get(Ty, V: 2))
6042 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
6043 ConstantInt::get(Ty, V: 1));
6044 }
6045
6046 return nullptr;
6047}
6048
6049/// Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
6050using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
6051static void collectOffsetOp(Value *V, SmallVectorImpl<OffsetOp> &Offsets,
6052 bool AllowRecursion) {
6053 Instruction *Inst = dyn_cast<Instruction>(Val: V);
6054 if (!Inst || !Inst->hasOneUse())
6055 return;
6056
6057 switch (Inst->getOpcode()) {
6058 case Instruction::Add:
6059 Offsets.emplace_back(Args: Instruction::Sub, Args: Inst->getOperand(i: 1));
6060 Offsets.emplace_back(Args: Instruction::Sub, Args: Inst->getOperand(i: 0));
6061 break;
6062 case Instruction::Sub:
6063 Offsets.emplace_back(Args: Instruction::Add, Args: Inst->getOperand(i: 1));
6064 break;
6065 case Instruction::Xor:
6066 Offsets.emplace_back(Args: Instruction::Xor, Args: Inst->getOperand(i: 1));
6067 Offsets.emplace_back(Args: Instruction::Xor, Args: Inst->getOperand(i: 0));
6068 break;
6069 case Instruction::Shl:
6070 if (Inst->hasNoSignedWrap())
6071 Offsets.emplace_back(Args: Instruction::AShr, Args: Inst->getOperand(i: 1));
6072 if (Inst->hasNoUnsignedWrap())
6073 Offsets.emplace_back(Args: Instruction::LShr, Args: Inst->getOperand(i: 1));
6074 break;
6075 case Instruction::Select:
6076 if (AllowRecursion) {
6077 collectOffsetOp(V: Inst->getOperand(i: 1), Offsets, /*AllowRecursion=*/false);
6078 collectOffsetOp(V: Inst->getOperand(i: 2), Offsets, /*AllowRecursion=*/false);
6079 }
6080 break;
6081 default:
6082 break;
6083 }
6084}
6085
6086enum class OffsetKind { Invalid, Value, Select };
6087
6088struct OffsetResult {
6089 OffsetKind Kind;
6090 Value *V0, *V1, *V2;
6091 Instruction *MDFrom;
6092
6093 static OffsetResult invalid() {
6094 return {.Kind: OffsetKind::Invalid, .V0: nullptr, .V1: nullptr, .V2: nullptr, .MDFrom: nullptr};
6095 }
6096 static OffsetResult value(Value *V) {
6097 return {.Kind: OffsetKind::Value, .V0: V, .V1: nullptr, .V2: nullptr, .MDFrom: nullptr};
6098 }
6099 static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV,
6100 Instruction *MDFrom) {
6101 return {.Kind: OffsetKind::Select, .V0: Cond, .V1: TrueV, .V2: FalseV, .MDFrom: MDFrom};
6102 }
6103 bool isValid() const { return Kind != OffsetKind::Invalid; }
6104 Value *materialize(InstCombiner::BuilderTy &Builder) const {
6105 switch (Kind) {
6106 case OffsetKind::Invalid:
6107 llvm_unreachable("Invalid offset result");
6108 case OffsetKind::Value:
6109 return V0;
6110 case OffsetKind::Select:
6111 return Builder.CreateSelect(
6112 C: V0, True: V1, False: V2, Name: "", MDFrom: ProfcheckDisableMetadataFixes ? nullptr : MDFrom);
6113 }
6114 llvm_unreachable("Unknown OffsetKind enum");
6115 }
6116};
6117
6118/// Offset both sides of an equality icmp to see if we can save some
6119/// instructions: icmp eq/ne X, Y -> icmp eq/ne X op Z, Y op Z.
6120/// Note: This operation should not introduce poison.
6121static Instruction *foldICmpEqualityWithOffset(ICmpInst &I,
6122 InstCombiner::BuilderTy &Builder,
6123 const SimplifyQuery &SQ) {
6124 assert(I.isEquality() && "Expected an equality icmp");
6125 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
6126 if (!Op0->getType()->isIntOrIntVectorTy())
6127 return nullptr;
6128
6129 SmallVector<OffsetOp, 4> OffsetOps;
6130 collectOffsetOp(V: Op0, Offsets&: OffsetOps, /*AllowRecursion=*/true);
6131 collectOffsetOp(V: Op1, Offsets&: OffsetOps, /*AllowRecursion=*/true);
6132
6133 auto ApplyOffsetImpl = [&](Value *V, unsigned BinOpc, Value *RHS) -> Value * {
6134 switch (BinOpc) {
6135 // V = shl nsw X, RHS => X = ashr V, RHS
6136 case Instruction::AShr: {
6137 const APInt *CV, *CRHS;
6138 if (!(match(V, P: m_APInt(Res&: CV)) && match(V: RHS, P: m_APInt(Res&: CRHS)) &&
6139 CV->ashr(ShiftAmt: *CRHS).shl(ShiftAmt: *CRHS) == *CV) &&
6140 !match(V, P: m_NSWShl(L: m_Value(), R: m_Specific(V: RHS))))
6141 return nullptr;
6142 break;
6143 }
6144 // V = shl nuw X, RHS => X = lshr V, RHS
6145 case Instruction::LShr: {
6146 const APInt *CV, *CRHS;
6147 if (!(match(V, P: m_APInt(Res&: CV)) && match(V: RHS, P: m_APInt(Res&: CRHS)) &&
6148 CV->lshr(ShiftAmt: *CRHS).shl(ShiftAmt: *CRHS) == *CV) &&
6149 !match(V, P: m_NUWShl(L: m_Value(), R: m_Specific(V: RHS))))
6150 return nullptr;
6151 break;
6152 }
6153 default:
6154 break;
6155 }
6156
6157 Value *Simplified = simplifyBinOp(Opcode: BinOpc, LHS: V, RHS, Q: SQ);
6158 if (!Simplified)
6159 return nullptr;
6160 // Reject constant expressions as they don't simplify things.
6161 if (isa<Constant>(Val: Simplified) && !match(V: Simplified, P: m_ImmConstant()))
6162 return nullptr;
6163 // Check if the transformation introduces poison.
6164 return impliesPoison(ValAssumedPoison: RHS, V) ? Simplified : nullptr;
6165 };
6166
6167 auto ApplyOffset = [&](Value *V, unsigned BinOpc,
6168 Value *RHS) -> OffsetResult {
6169 if (auto *Sel = dyn_cast<SelectInst>(Val: V)) {
6170 if (!Sel->hasOneUse())
6171 return OffsetResult::invalid();
6172 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc, RHS);
6173 if (!TrueVal)
6174 return OffsetResult::invalid();
6175 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc, RHS);
6176 if (!FalseVal)
6177 return OffsetResult::invalid();
6178 return OffsetResult::select(Cond: Sel->getCondition(), TrueV: TrueVal, FalseV: FalseVal, MDFrom: Sel);
6179 }
6180 if (Value *Simplified = ApplyOffsetImpl(V, BinOpc, RHS))
6181 return OffsetResult::value(V: Simplified);
6182 return OffsetResult::invalid();
6183 };
6184
6185 for (auto [BinOp, RHS] : OffsetOps) {
6186 auto BinOpc = static_cast<unsigned>(BinOp);
6187
6188 auto Op0Result = ApplyOffset(Op0, BinOpc, RHS);
6189 if (!Op0Result.isValid())
6190 continue;
6191 auto Op1Result = ApplyOffset(Op1, BinOpc, RHS);
6192 if (!Op1Result.isValid())
6193 continue;
6194
6195 Value *NewLHS = Op0Result.materialize(Builder);
6196 Value *NewRHS = Op1Result.materialize(Builder);
6197 return new ICmpInst(I.getPredicate(), NewLHS, NewRHS);
6198 }
6199
6200 return nullptr;
6201}
6202
6203Instruction *InstCombinerImpl::foldICmpEquality(ICmpInst &I) {
6204 if (!I.isEquality())
6205 return nullptr;
6206
6207 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
6208 const CmpInst::Predicate Pred = I.getPredicate();
6209 Value *A, *B, *C, *D;
6210 if (match(V: Op0, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B)))) {
6211 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6212 Value *OtherVal = A == Op1 ? B : A;
6213 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(Ty: A->getType()));
6214 }
6215
6216 if (match(V: Op1, P: m_Xor(L: m_Value(V&: C), R: m_Value(V&: D)))) {
6217 // A^c1 == C^c2 --> A == C^(c1^c2)
6218 ConstantInt *C1, *C2;
6219 if (match(V: B, P: m_ConstantInt(CI&: C1)) && match(V: D, P: m_ConstantInt(CI&: C2)) &&
6220 Op1->hasOneUse()) {
6221 Constant *NC = Builder.getInt(AI: C1->getValue() ^ C2->getValue());
6222 Value *Xor = Builder.CreateXor(LHS: C, RHS: NC);
6223 return new ICmpInst(Pred, A, Xor);
6224 }
6225
6226 // A^B == A^D -> B == D
6227 if (A == C)
6228 return new ICmpInst(Pred, B, D);
6229 if (A == D)
6230 return new ICmpInst(Pred, B, C);
6231 if (B == C)
6232 return new ICmpInst(Pred, A, D);
6233 if (B == D)
6234 return new ICmpInst(Pred, A, C);
6235 }
6236 }
6237
6238 if (match(V: Op1, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))) && (A == Op0 || B == Op0)) {
6239 // A == (A^B) -> B == 0
6240 Value *OtherVal = A == Op0 ? B : A;
6241 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(Ty: A->getType()));
6242 }
6243
6244 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6245 if (match(V: Op0, P: m_And(L: m_Value(V&: A), R: m_Value(V&: B))) &&
6246 match(V: Op1, P: m_And(L: m_Value(V&: C), R: m_Value(V&: D)))) {
6247 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
6248
6249 if (A == C) {
6250 X = B;
6251 Y = D;
6252 Z = A;
6253 } else if (A == D) {
6254 X = B;
6255 Y = C;
6256 Z = A;
6257 } else if (B == C) {
6258 X = A;
6259 Y = D;
6260 Z = B;
6261 } else if (B == D) {
6262 X = A;
6263 Y = C;
6264 Z = B;
6265 }
6266
6267 if (X) {
6268 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
6269 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
6270 // instructions.
6271 const APInt *C0, *C1;
6272 bool XorIsNegP2 = match(V: X, P: m_APInt(Res&: C0)) && match(V: Y, P: m_APInt(Res&: C1)) &&
6273 (*C0 ^ *C1).isNegatedPowerOf2();
6274
6275 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
6276 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
6277 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
6278 int UseCnt =
6279 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
6280 (int(match(V: X, P: m_ImmConstant()) && match(V: Y, P: m_ImmConstant())));
6281 if (XorIsNegP2 || UseCnt >= 2) {
6282 // Build (X^Y) & Z
6283 Op1 = Builder.CreateXor(LHS: X, RHS: Y);
6284 Op1 = Builder.CreateAnd(LHS: Op1, RHS: Z);
6285 return new ICmpInst(Pred, Op1, Constant::getNullValue(Ty: Op1->getType()));
6286 }
6287 }
6288 }
6289
6290 {
6291 // Similar to above, but specialized for constant because invert is needed:
6292 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
6293 Value *X, *Y;
6294 Constant *C;
6295 if (match(V: Op0, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: X), R: m_Constant(C)))) &&
6296 match(V: Op1, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: Y), R: m_Specific(V: C))))) {
6297 Value *Xor = Builder.CreateXor(LHS: X, RHS: Y);
6298 Value *And = Builder.CreateAnd(LHS: Xor, RHS: ConstantExpr::getNot(C));
6299 return new ICmpInst(Pred, And, Constant::getNullValue(Ty: And->getType()));
6300 }
6301 }
6302
6303 if (match(V: Op1, P: m_ZExt(Op: m_Value(V&: A))) &&
6304 (Op0->hasOneUse() || Op1->hasOneUse())) {
6305 // (B & (Pow2C-1)) == zext A --> A == trunc B
6306 // (B & (Pow2C-1)) != zext A --> A != trunc B
6307 const APInt *MaskC;
6308 if (match(V: Op0, P: m_And(L: m_Value(V&: B), R: m_LowBitMask(V&: MaskC))) &&
6309 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
6310 return new ICmpInst(Pred, A, Builder.CreateTrunc(V: B, DestTy: A->getType()));
6311 }
6312
6313 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
6314 // For lshr and ashr pairs.
6315 const APInt *AP1, *AP2;
6316 if ((match(V: Op0, P: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: A), R: m_APIntAllowPoison(Res&: AP1)))) &&
6317 match(V: Op1, P: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: B), R: m_APIntAllowPoison(Res&: AP2))))) ||
6318 (match(V: Op0, P: m_OneUse(SubPattern: m_AShr(L: m_Value(V&: A), R: m_APIntAllowPoison(Res&: AP1)))) &&
6319 match(V: Op1, P: m_OneUse(SubPattern: m_AShr(L: m_Value(V&: B), R: m_APIntAllowPoison(Res&: AP2)))))) {
6320 if (*AP1 != *AP2)
6321 return nullptr;
6322 unsigned TypeBits = AP1->getBitWidth();
6323 unsigned ShAmt = AP1->getLimitedValue(Limit: TypeBits);
6324 if (ShAmt < TypeBits && ShAmt != 0) {
6325 ICmpInst::Predicate NewPred =
6326 Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6327 Value *Xor = Builder.CreateXor(LHS: A, RHS: B, Name: I.getName() + ".unshifted");
6328 APInt CmpVal = APInt::getOneBitSet(numBits: TypeBits, BitNo: ShAmt);
6329 return new ICmpInst(NewPred, Xor, ConstantInt::get(Ty: A->getType(), V: CmpVal));
6330 }
6331 }
6332
6333 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
6334 ConstantInt *Cst1;
6335 if (match(V: Op0, P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: A), R: m_ConstantInt(CI&: Cst1)))) &&
6336 match(V: Op1, P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: B), R: m_Specific(V: Cst1))))) {
6337 unsigned TypeBits = Cst1->getBitWidth();
6338 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(Limit: TypeBits);
6339 if (ShAmt < TypeBits && ShAmt != 0) {
6340 Value *Xor = Builder.CreateXor(LHS: A, RHS: B, Name: I.getName() + ".unshifted");
6341 APInt AndVal = APInt::getLowBitsSet(numBits: TypeBits, loBitsSet: TypeBits - ShAmt);
6342 Value *And =
6343 Builder.CreateAnd(LHS: Xor, RHS: Builder.getInt(AI: AndVal), Name: I.getName() + ".mask");
6344 return new ICmpInst(Pred, And, Constant::getNullValue(Ty: Cst1->getType()));
6345 }
6346 }
6347
6348 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
6349 // "icmp (and X, mask), cst"
6350 uint64_t ShAmt = 0;
6351 if (Op0->hasOneUse() &&
6352 match(V: Op0, P: m_Trunc(Op: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: A), R: m_ConstantInt(V&: ShAmt))))) &&
6353 match(V: Op1, P: m_ConstantInt(CI&: Cst1)) &&
6354 // Only do this when A has multiple uses. This is most important to do
6355 // when it exposes other optimizations.
6356 !A->hasOneUse()) {
6357 unsigned ASize = cast<IntegerType>(Val: A->getType())->getPrimitiveSizeInBits();
6358
6359 if (ShAmt < ASize) {
6360 APInt MaskV =
6361 APInt::getLowBitsSet(numBits: ASize, loBitsSet: Op0->getType()->getPrimitiveSizeInBits());
6362 MaskV <<= ShAmt;
6363
6364 APInt CmpV = Cst1->getValue().zext(width: ASize);
6365 CmpV <<= ShAmt;
6366
6367 Value *Mask = Builder.CreateAnd(LHS: A, RHS: Builder.getInt(AI: MaskV));
6368 return new ICmpInst(Pred, Mask, Builder.getInt(AI: CmpV));
6369 }
6370 }
6371
6372 if (Instruction *ICmp = foldICmpIntrinsicWithIntrinsic(Cmp&: I, Builder))
6373 return ICmp;
6374
6375 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
6376 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
6377 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
6378 // few steps of instcombine.
6379 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6380 if (match(V: Op0, P: m_AShr(L: m_Trunc(Op: m_Value(V&: A)), R: m_SpecificInt(V: BitWidth - 1))) &&
6381 match(V: Op1, P: m_Trunc(Op: m_LShr(L: m_Specific(V: A), R: m_SpecificInt(V: BitWidth)))) &&
6382 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
6383 (I.getOperand(i_nocapture: 0)->hasOneUse() || I.getOperand(i_nocapture: 1)->hasOneUse())) {
6384 APInt C = APInt::getOneBitSet(numBits: BitWidth * 2, BitNo: BitWidth - 1);
6385 Value *Add = Builder.CreateAdd(LHS: A, RHS: ConstantInt::get(Ty: A->getType(), V: C));
6386 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
6387 : ICmpInst::ICMP_UGE,
6388 Add, ConstantInt::get(Ty: A->getType(), V: C.shl(shiftAmt: 1)));
6389 }
6390
6391 // Canonicalize:
6392 // Assume B_Pow2 != 0
6393 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
6394 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
6395 if (match(V: Op0, P: m_c_And(L: m_Specific(V: Op1), R: m_Value())) &&
6396 isKnownToBeAPowerOfTwo(V: Op1, /* OrZero */ false, CxtI: &I))
6397 return new ICmpInst(CmpInst::getInversePredicate(pred: Pred), Op0,
6398 ConstantInt::getNullValue(Ty: Op0->getType()));
6399
6400 if (match(V: Op1, P: m_c_And(L: m_Specific(V: Op0), R: m_Value())) &&
6401 isKnownToBeAPowerOfTwo(V: Op0, /* OrZero */ false, CxtI: &I))
6402 return new ICmpInst(CmpInst::getInversePredicate(pred: Pred), Op1,
6403 ConstantInt::getNullValue(Ty: Op1->getType()));
6404
6405 // Canonicalize:
6406 // icmp eq/ne X, OneUse(rotate-right(X))
6407 // -> icmp eq/ne X, rotate-left(X)
6408 // We generally try to convert rotate-right -> rotate-left, this just
6409 // canonicalizes another case.
6410 if (match(V: &I, P: m_c_ICmp(L: m_Value(V&: A),
6411 R: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::fshr>(
6412 Ops: m_Deferred(V: A), Ops: m_Deferred(V: A), Ops: m_Value(V&: B))))))
6413 return new ICmpInst(
6414 Pred, A,
6415 Builder.CreateIntrinsic(RetTy: Op0->getType(), ID: Intrinsic::fshl, Args: {A, A, B}));
6416
6417 // Canonicalize:
6418 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
6419 Constant *Cst;
6420 if (match(V: &I, P: m_c_ICmp(L: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: A), R: m_ImmConstant(C&: Cst))),
6421 R: m_CombineAnd(Ps: m_Value(V&: B), Ps: m_Unless(P: m_ImmConstant())))))
6422 return new ICmpInst(Pred, Builder.CreateXor(LHS: A, RHS: B), Cst);
6423
6424 {
6425 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6426 auto m_Matcher =
6427 m_CombineOr(Ps: m_CombineOr(Ps: m_c_Add(L: m_Value(V&: B), R: m_Deferred(V: A)),
6428 Ps: m_c_Xor(L: m_Value(V&: B), R: m_Deferred(V: A))),
6429 Ps: m_Sub(L: m_Value(V&: B), R: m_Deferred(V: A)));
6430 std::optional<bool> IsZero = std::nullopt;
6431 if (match(V: &I, P: m_c_ICmp(L: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: A), R: m_Matcher)),
6432 R: m_Deferred(V: A))))
6433 IsZero = false;
6434 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6435 else if (match(V: &I,
6436 P: m_ICmp(L: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: A), R: m_Matcher)), R: m_Zero())))
6437 IsZero = true;
6438
6439 if (IsZero && isKnownToBeAPowerOfTwo(V: A, /* OrZero */ true, CxtI: &I))
6440 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6441 // -> (icmp eq/ne (and X, P2), 0)
6442 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6443 // -> (icmp eq/ne (and X, P2), P2)
6444 return new ICmpInst(Pred, Builder.CreateAnd(LHS: B, RHS: A),
6445 *IsZero ? A
6446 : ConstantInt::getNullValue(Ty: A->getType()));
6447 }
6448
6449 if (auto *Res = foldICmpEqualityWithOffset(
6450 I, Builder, SQ: getSimplifyQuery().getWithInstruction(I: &I)))
6451 return Res;
6452
6453 return nullptr;
6454}
6455
6456Instruction *InstCombinerImpl::foldICmpWithTrunc(ICmpInst &ICmp) {
6457 ICmpInst::Predicate Pred = ICmp.getPredicate();
6458 Value *Op0 = ICmp.getOperand(i_nocapture: 0), *Op1 = ICmp.getOperand(i_nocapture: 1);
6459
6460 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6461 // The trunc masks high bits while the compare may effectively mask low bits.
6462 Value *X;
6463 const APInt *C;
6464 if (!match(V: Op0, P: m_OneUse(SubPattern: m_Trunc(Op: m_Value(V&: X)))) || !match(V: Op1, P: m_APInt(Res&: C)))
6465 return nullptr;
6466
6467 // This matches patterns corresponding to tests of the signbit as well as:
6468 // (trunc X) pred C2 --> (X & Mask) == C
6469 if (auto Res = decomposeBitTestICmp(LHS: Op0, RHS: Op1, Pred, /*LookThroughTrunc=*/true,
6470 /*AllowNonZeroC=*/true)) {
6471 Value *And = Builder.CreateAnd(LHS: Res->X, RHS: Res->Mask);
6472 Constant *C = ConstantInt::get(Ty: Res->X->getType(), V: Res->C);
6473 return new ICmpInst(Res->Pred, And, C);
6474 }
6475
6476 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6477 if (auto *II = dyn_cast<IntrinsicInst>(Val: X)) {
6478 if (II->getIntrinsicID() == Intrinsic::cttz ||
6479 II->getIntrinsicID() == Intrinsic::ctlz) {
6480 unsigned MaxRet = SrcBits;
6481 // If the "is_zero_poison" argument is set, then we know at least
6482 // one bit is set in the input, so the result is always at least one
6483 // less than the full bitwidth of that input.
6484 if (match(V: II->getArgOperand(i: 1), P: m_One()))
6485 MaxRet--;
6486
6487 // Make sure the destination is wide enough to hold the largest output of
6488 // the intrinsic.
6489 if (llvm::Log2_32(Value: MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6490 if (Instruction *I =
6491 foldICmpIntrinsicWithConstant(Cmp&: ICmp, II, C: C->zext(width: SrcBits)))
6492 return I;
6493 }
6494 }
6495
6496 return nullptr;
6497}
6498
6499Instruction *InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst &ICmp) {
6500 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6501 auto *CastOp0 = cast<CastInst>(Val: ICmp.getOperand(i_nocapture: 0));
6502 Value *X;
6503 if (!match(V: CastOp0, P: m_ZExtOrSExt(Op: m_Value(V&: X))))
6504 return nullptr;
6505
6506 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6507 bool IsSignedCmp = ICmp.isSigned();
6508
6509 // icmp Pred (ext X), (ext Y)
6510 Value *Y;
6511 if (match(V: ICmp.getOperand(i_nocapture: 1), P: m_ZExtOrSExt(Op: m_Value(V&: Y)))) {
6512 bool IsZext0 = isa<ZExtInst>(Val: ICmp.getOperand(i_nocapture: 0));
6513 bool IsZext1 = isa<ZExtInst>(Val: ICmp.getOperand(i_nocapture: 1));
6514
6515 if (IsZext0 != IsZext1) {
6516 // If X and Y and both i1
6517 // (icmp eq/ne (zext X) (sext Y))
6518 // eq -> (icmp eq (or X, Y), 0)
6519 // ne -> (icmp ne (or X, Y), 0)
6520 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(BitWidth: 1) &&
6521 Y->getType()->isIntOrIntVectorTy(BitWidth: 1))
6522 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(LHS: X, RHS: Y),
6523 Constant::getNullValue(Ty: X->getType()));
6524
6525 // If we have mismatched casts and zext has the nneg flag, we can
6526 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6527
6528 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(Val: ICmp.getOperand(i_nocapture: 0));
6529 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(Val: ICmp.getOperand(i_nocapture: 1));
6530
6531 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6532 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6533
6534 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6535 IsSignedExt = true;
6536 else
6537 return nullptr;
6538 }
6539
6540 // Not an extension from the same type?
6541 Type *XTy = X->getType(), *YTy = Y->getType();
6542 if (XTy != YTy) {
6543 // One of the casts must have one use because we are creating a new cast.
6544 if (!ICmp.getOperand(i_nocapture: 0)->hasOneUse() && !ICmp.getOperand(i_nocapture: 1)->hasOneUse())
6545 return nullptr;
6546 // Extend the narrower operand to the type of the wider operand.
6547 CastInst::CastOps CastOpcode =
6548 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6549 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6550 X = Builder.CreateCast(Op: CastOpcode, V: X, DestTy: YTy);
6551 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6552 Y = Builder.CreateCast(Op: CastOpcode, V: Y, DestTy: XTy);
6553 else
6554 return nullptr;
6555 }
6556
6557 // (zext X) == (zext Y) --> X == Y
6558 // (sext X) == (sext Y) --> X == Y
6559 if (ICmp.isEquality())
6560 return new ICmpInst(ICmp.getPredicate(), X, Y);
6561
6562 // A signed comparison of sign extended values simplifies into a
6563 // signed comparison.
6564 if (IsSignedCmp && IsSignedExt)
6565 return new ICmpInst(ICmp.getPredicate(), X, Y);
6566
6567 // The other three cases all fold into an unsigned comparison.
6568 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6569 }
6570
6571 // Below here, we are only folding a compare with constant.
6572 auto *C = dyn_cast<Constant>(Val: ICmp.getOperand(i_nocapture: 1));
6573 if (!C)
6574 return nullptr;
6575
6576 // If a lossless truncate is possible...
6577 Type *SrcTy = CastOp0->getSrcTy();
6578 Constant *Res = getLosslessInvCast(C, InvCastTo: SrcTy, CastOp: CastOp0->getOpcode(), DL);
6579 if (Res) {
6580 if (ICmp.isEquality())
6581 return new ICmpInst(ICmp.getPredicate(), X, Res);
6582
6583 // A signed comparison of sign extended values simplifies into a
6584 // signed comparison.
6585 if (IsSignedExt && IsSignedCmp)
6586 return new ICmpInst(ICmp.getPredicate(), X, Res);
6587
6588 // The other three cases all fold into an unsigned comparison.
6589 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6590 }
6591
6592 // The re-extended constant changed, partly changed (in the case of a vector),
6593 // or could not be determined to be equal (in the case of a constant
6594 // expression), so the constant cannot be represented in the shorter type.
6595 // All the cases that fold to true or false will have already been handled
6596 // by simplifyICmpInst, so only deal with the tricky case.
6597 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(Val: C))
6598 return nullptr;
6599
6600 // Is source op positive?
6601 // icmp ult (sext X), C --> icmp sgt X, -1
6602 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6603 return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(Ty: SrcTy));
6604
6605 // Is source op negative?
6606 // icmp ugt (sext X), C --> icmp slt X, 0
6607 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6608 return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(Ty: SrcTy));
6609}
6610
6611/// Handle icmp (cast x), (cast or constant).
6612Instruction *InstCombinerImpl::foldICmpWithCastOp(ICmpInst &ICmp) {
6613 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6614 // icmp compares only pointer's value.
6615 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6616 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(Val: ICmp.getOperand(i_nocapture: 0));
6617 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(Val: ICmp.getOperand(i_nocapture: 1));
6618 if (SimplifiedOp0 || SimplifiedOp1)
6619 return new ICmpInst(ICmp.getPredicate(),
6620 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(i_nocapture: 0),
6621 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(i_nocapture: 1));
6622
6623 auto *CastOp0 = dyn_cast<CastInst>(Val: ICmp.getOperand(i_nocapture: 0));
6624 Value *Op1 = ICmp.getOperand(i_nocapture: 1);
6625 if (!CastOp0)
6626 return nullptr;
6627 if (!isa<Constant>(Val: ICmp.getOperand(i_nocapture: 1)) && !isa<CastInst>(Val: ICmp.getOperand(i_nocapture: 1)))
6628 return nullptr;
6629
6630 Value *Op0Src = CastOp0->getOperand(i_nocapture: 0);
6631 Type *SrcTy = CastOp0->getSrcTy();
6632 Type *DestTy = CastOp0->getDestTy();
6633
6634 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6635 // integer type is the same size as the pointer type.
6636 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6637 unsigned IntWidth = IntTy->getScalarType()->getIntegerBitWidth();
6638 unsigned IndexWidth = DL.getAddressSizeInBits(Ty: PtrTy);
6639 unsigned PtrWidth = DL.getPointerTypeSizeInBits(PtrTy);
6640 // For ptrtoint/inttoptr, we must check that IntWidth == IndexWidth and also
6641 // IndexWidth == PtrWidth to (not) handle non-integral pointers.
6642 return IntWidth == IndexWidth && IndexWidth == PtrWidth;
6643 };
6644 if (isa<PtrToIntInst, PtrToAddrInst>(Val: CastOp0)) {
6645 bool HasPtrToInt = isa<PtrToIntInst>(Val: CastOp0);
6646 Value *NewOp1 = nullptr;
6647 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(Val: Op1)) {
6648 NewOp1 = PtrToIntOp1->getOperand(i_nocapture: 0);
6649 HasPtrToInt = true;
6650 } else if (auto *PtrToAddrOp1 = dyn_cast<PtrToAddrOperator>(Val: Op1)) {
6651 NewOp1 = PtrToAddrOp1->getOperand(i_nocapture: 0);
6652 } else if (auto *RHSC = dyn_cast<Constant>(Val: Op1)) {
6653 NewOp1 = ConstantExpr::getIntToPtr(C: RHSC, Ty: SrcTy);
6654 }
6655
6656 // For ptrtoaddr, IntWidth == IndexWidth is implied and we don't need to
6657 // check PtrWidth.
6658 if ((!HasPtrToInt || CompatibleSizes(SrcTy, DestTy)) &&
6659 (NewOp1 && NewOp1->getType() == Op0Src->getType()))
6660 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6661 }
6662
6663 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6664 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6665 CompatibleSizes(DestTy, SrcTy)) {
6666 Value *NewOp1 = nullptr;
6667 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(Val: Op1)) {
6668 Value *IntSrc = IntToPtrOp1->getOperand(i_nocapture: 0);
6669 if (IntSrc->getType() == Op0Src->getType())
6670 NewOp1 = IntToPtrOp1->getOperand(i_nocapture: 0);
6671 } else if (auto *RHSC = dyn_cast<Constant>(Val: Op1)) {
6672 NewOp1 = ConstantFoldConstant(C: ConstantExpr::getPtrToInt(C: RHSC, Ty: SrcTy), DL);
6673 }
6674
6675 if (NewOp1)
6676 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6677 }
6678
6679 if (Instruction *R = foldICmpWithTrunc(ICmp))
6680 return R;
6681
6682 return foldICmpWithZextOrSext(ICmp);
6683}
6684
6685static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS,
6686 bool IsSigned) {
6687 switch (BinaryOp) {
6688 default:
6689 llvm_unreachable("Unsupported binary op");
6690 case Instruction::Add:
6691 case Instruction::Sub:
6692 return match(V: RHS, P: m_Zero());
6693 case Instruction::Mul:
6694 return !(RHS->getType()->isIntOrIntVectorTy(BitWidth: 1) && IsSigned) &&
6695 match(V: RHS, P: m_One());
6696 }
6697}
6698
6699OverflowResult
6700InstCombinerImpl::computeOverflow(Instruction::BinaryOps BinaryOp,
6701 bool IsSigned, Value *LHS, Value *RHS,
6702 Instruction *CxtI) const {
6703 switch (BinaryOp) {
6704 default:
6705 llvm_unreachable("Unsupported binary op");
6706 case Instruction::Add:
6707 if (IsSigned)
6708 return computeOverflowForSignedAdd(LHS, RHS, CxtI);
6709 else
6710 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
6711 case Instruction::Sub:
6712 if (IsSigned)
6713 return computeOverflowForSignedSub(LHS, RHS, CxtI);
6714 else
6715 return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
6716 case Instruction::Mul:
6717 if (IsSigned)
6718 return computeOverflowForSignedMul(LHS, RHS, CxtI);
6719 else
6720 return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
6721 }
6722}
6723
6724bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6725 bool IsSigned, Value *LHS,
6726 Value *RHS, Instruction &OrigI,
6727 Value *&Result,
6728 Constant *&Overflow) {
6729 if (OrigI.isCommutative() && isa<Constant>(Val: LHS) && !isa<Constant>(Val: RHS))
6730 std::swap(a&: LHS, b&: RHS);
6731
6732 // If the overflow check was an add followed by a compare, the insertion point
6733 // may be pointing to the compare. We want to insert the new instructions
6734 // before the add in case there are uses of the add between the add and the
6735 // compare.
6736 Builder.SetInsertPoint(&OrigI);
6737
6738 Type *OverflowTy = Type::getInt1Ty(C&: LHS->getContext());
6739 if (auto *LHSTy = dyn_cast<VectorType>(Val: LHS->getType()))
6740 OverflowTy = VectorType::get(ElementType: OverflowTy, EC: LHSTy->getElementCount());
6741
6742 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6743 Result = LHS;
6744 Overflow = ConstantInt::getFalse(Ty: OverflowTy);
6745 return true;
6746 }
6747
6748 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, CxtI: &OrigI)) {
6749 case OverflowResult::MayOverflow:
6750 return false;
6751 case OverflowResult::AlwaysOverflowsLow:
6752 case OverflowResult::AlwaysOverflowsHigh:
6753 Result = Builder.CreateBinOp(Opc: BinaryOp, LHS, RHS);
6754 Result->takeName(V: &OrigI);
6755 Overflow = ConstantInt::getTrue(Ty: OverflowTy);
6756 return true;
6757 case OverflowResult::NeverOverflows:
6758 Result = Builder.CreateBinOp(Opc: BinaryOp, LHS, RHS);
6759 Result->takeName(V: &OrigI);
6760 Overflow = ConstantInt::getFalse(Ty: OverflowTy);
6761 if (auto *Inst = dyn_cast<Instruction>(Val: Result)) {
6762 if (IsSigned)
6763 Inst->setHasNoSignedWrap();
6764 else
6765 Inst->setHasNoUnsignedWrap();
6766 }
6767 return true;
6768 }
6769
6770 llvm_unreachable("Unexpected overflow result");
6771}
6772
6773/// Recognize and process idiom involving test for multiplication
6774/// overflow.
6775///
6776/// The caller has matched a pattern of the form:
6777/// I = cmp u (mul(zext A, zext B), V
6778/// The function checks if this is a test for overflow and if so replaces
6779/// multiplication with call to 'mul.with.overflow' intrinsic.
6780///
6781/// \param I Compare instruction.
6782/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
6783/// the compare instruction. Must be of integer type.
6784/// \param OtherVal The other argument of compare instruction.
6785/// \returns Instruction which must replace the compare instruction, NULL if no
6786/// replacement required.
6787static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,
6788 const APInt *OtherVal,
6789 InstCombinerImpl &IC) {
6790 // Don't bother doing this transformation for pointers, don't do it for
6791 // vectors.
6792 if (!isa<IntegerType>(Val: MulVal->getType()))
6793 return nullptr;
6794
6795 auto *MulInstr = dyn_cast<Instruction>(Val: MulVal);
6796 if (!MulInstr)
6797 return nullptr;
6798 assert(MulInstr->getOpcode() == Instruction::Mul);
6799
6800 auto *LHS = cast<ZExtInst>(Val: MulInstr->getOperand(i: 0)),
6801 *RHS = cast<ZExtInst>(Val: MulInstr->getOperand(i: 1));
6802 assert(LHS->getOpcode() == Instruction::ZExt);
6803 assert(RHS->getOpcode() == Instruction::ZExt);
6804 Value *A = LHS->getOperand(i_nocapture: 0), *B = RHS->getOperand(i_nocapture: 0);
6805
6806 // Calculate type and width of the result produced by mul.with.overflow.
6807 Type *TyA = A->getType(), *TyB = B->getType();
6808 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6809 WidthB = TyB->getPrimitiveSizeInBits();
6810 unsigned MulWidth;
6811 Type *MulType;
6812 if (WidthB > WidthA) {
6813 MulWidth = WidthB;
6814 MulType = TyB;
6815 } else {
6816 MulWidth = WidthA;
6817 MulType = TyA;
6818 }
6819
6820 // In order to replace the original mul with a narrower mul.with.overflow,
6821 // all uses must ignore upper bits of the product. The number of used low
6822 // bits must be not greater than the width of mul.with.overflow.
6823 if (MulVal->hasNUsesOrMore(N: 2))
6824 for (User *U : MulVal->users()) {
6825 if (U == &I)
6826 continue;
6827 if (TruncInst *TI = dyn_cast<TruncInst>(Val: U)) {
6828 // Check if truncation ignores bits above MulWidth.
6829 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
6830 if (TruncWidth > MulWidth)
6831 return nullptr;
6832 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: U)) {
6833 // Check if AND ignores bits above MulWidth.
6834 if (BO->getOpcode() != Instruction::And)
6835 return nullptr;
6836 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: BO->getOperand(i_nocapture: 1))) {
6837 const APInt &CVal = CI->getValue();
6838 if (CVal.getBitWidth() - CVal.countl_zero() > MulWidth)
6839 return nullptr;
6840 } else {
6841 // In this case we could have the operand of the binary operation
6842 // being defined in another block, and performing the replacement
6843 // could break the dominance relation.
6844 return nullptr;
6845 }
6846 } else {
6847 // Other uses prohibit this transformation.
6848 return nullptr;
6849 }
6850 }
6851
6852 // Recognize patterns
6853 switch (I.getPredicate()) {
6854 case ICmpInst::ICMP_UGT: {
6855 // Recognize pattern:
6856 // mulval = mul(zext A, zext B)
6857 // cmp ugt mulval, max
6858 APInt MaxVal = APInt::getMaxValue(numBits: MulWidth);
6859 MaxVal = MaxVal.zext(width: OtherVal->getBitWidth());
6860 if (MaxVal.eq(RHS: *OtherVal))
6861 break; // Recognized
6862 return nullptr;
6863 }
6864
6865 case ICmpInst::ICMP_ULT: {
6866 // Recognize pattern:
6867 // mulval = mul(zext A, zext B)
6868 // cmp ule mulval, max + 1
6869 APInt MaxVal = APInt::getOneBitSet(numBits: OtherVal->getBitWidth(), BitNo: MulWidth);
6870 if (MaxVal.eq(RHS: *OtherVal))
6871 break; // Recognized
6872 return nullptr;
6873 }
6874
6875 default:
6876 return nullptr;
6877 }
6878
6879 InstCombiner::BuilderTy &Builder = IC.Builder;
6880 Builder.SetInsertPoint(MulInstr);
6881
6882 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
6883 Value *MulA = A, *MulB = B;
6884 if (WidthA < MulWidth)
6885 MulA = Builder.CreateZExt(V: A, DestTy: MulType);
6886 if (WidthB < MulWidth)
6887 MulB = Builder.CreateZExt(V: B, DestTy: MulType);
6888 Value *Call =
6889 Builder.CreateIntrinsic(ID: Intrinsic::umul_with_overflow, OverloadTypes: MulType,
6890 Args: {MulA, MulB}, /*FMFSource=*/nullptr, Name: "umul");
6891 IC.addToWorklist(I: MulInstr);
6892
6893 // If there are uses of mul result other than the comparison, we know that
6894 // they are truncation or binary AND. Change them to use result of
6895 // mul.with.overflow and adjust properly mask/size.
6896 if (MulVal->hasNUsesOrMore(N: 2)) {
6897 Value *Mul = Builder.CreateExtractValue(Agg: Call, Idxs: 0, Name: "umul.value");
6898 for (User *U : make_early_inc_range(Range: MulVal->users())) {
6899 if (U == &I)
6900 continue;
6901 if (TruncInst *TI = dyn_cast<TruncInst>(Val: U)) {
6902 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
6903 IC.replaceInstUsesWith(I&: *TI, V: Mul);
6904 else
6905 TI->setOperand(i_nocapture: 0, Val_nocapture: Mul);
6906 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: U)) {
6907 assert(BO->getOpcode() == Instruction::And);
6908 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
6909 ConstantInt *CI = cast<ConstantInt>(Val: BO->getOperand(i_nocapture: 1));
6910 APInt ShortMask = CI->getValue().trunc(width: MulWidth);
6911 Value *ShortAnd = Builder.CreateAnd(LHS: Mul, RHS: ShortMask);
6912 Value *Zext = Builder.CreateZExt(V: ShortAnd, DestTy: BO->getType());
6913 IC.replaceInstUsesWith(I&: *BO, V: Zext);
6914 } else {
6915 llvm_unreachable("Unexpected Binary operation");
6916 }
6917 IC.addToWorklist(I: cast<Instruction>(Val: U));
6918 }
6919 }
6920
6921 // The original icmp gets replaced with the overflow value, maybe inverted
6922 // depending on predicate.
6923 if (I.getPredicate() == ICmpInst::ICMP_ULT) {
6924 Value *Res = Builder.CreateExtractValue(Agg: Call, Idxs: 1);
6925 return BinaryOperator::CreateNot(Op: Res);
6926 }
6927
6928 return ExtractValueInst::Create(Agg: Call, Idxs: 1);
6929}
6930
6931/// When performing a comparison against a constant, it is possible that not all
6932/// the bits in the LHS are demanded. This helper method computes the mask that
6933/// IS demanded.
6934static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) {
6935 const APInt *RHS;
6936 if (!match(V: I.getOperand(i_nocapture: 1), P: m_APInt(Res&: RHS)))
6937 return APInt::getAllOnes(numBits: BitWidth);
6938
6939 // If this is a normal comparison, it demands all bits. If it is a sign bit
6940 // comparison, it only demands the sign bit.
6941 bool UnusedBit;
6942 if (isSignBitCheck(Pred: I.getPredicate(), RHS: *RHS, TrueIfSigned&: UnusedBit))
6943 return APInt::getSignMask(BitWidth);
6944
6945 switch (I.getPredicate()) {
6946 // For a UGT comparison, we don't care about any bits that
6947 // correspond to the trailing ones of the comparand. The value of these
6948 // bits doesn't impact the outcome of the comparison, because any value
6949 // greater than the RHS must differ in a bit higher than these due to carry.
6950 case ICmpInst::ICMP_UGT:
6951 return APInt::getBitsSetFrom(numBits: BitWidth, loBit: RHS->countr_one());
6952
6953 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
6954 // Any value less than the RHS must differ in a higher bit because of carries.
6955 case ICmpInst::ICMP_ULT:
6956 return APInt::getBitsSetFrom(numBits: BitWidth, loBit: RHS->countr_zero());
6957
6958 default:
6959 return APInt::getAllOnes(numBits: BitWidth);
6960 }
6961}
6962
6963/// Check that one use is in the same block as the definition and all
6964/// other uses are in blocks dominated by a given block.
6965///
6966/// \param DI Definition
6967/// \param UI Use
6968/// \param DB Block that must dominate all uses of \p DI outside
6969/// the parent block
6970/// \return true when \p UI is the only use of \p DI in the parent block
6971/// and all other uses of \p DI are in blocks dominated by \p DB.
6972///
6973bool InstCombinerImpl::dominatesAllUses(const Instruction *DI,
6974 const Instruction *UI,
6975 const BasicBlock *DB) const {
6976 assert(DI && UI && "Instruction not defined\n");
6977 // Ignore incomplete definitions.
6978 if (!DI->getParent())
6979 return false;
6980 // DI and UI must be in the same block.
6981 if (DI->getParent() != UI->getParent())
6982 return false;
6983 // Protect from self-referencing blocks.
6984 if (DI->getParent() == DB)
6985 return false;
6986 for (const User *U : DI->users()) {
6987 auto *Usr = cast<Instruction>(Val: U);
6988 if (Usr != UI && !DT.dominates(A: DB, B: Usr->getParent()))
6989 return false;
6990 }
6991 return true;
6992}
6993
6994/// Return true when the instruction sequence within a block is select-cmp-br.
6995static bool isChainSelectCmpBranch(const SelectInst *SI) {
6996 const BasicBlock *BB = SI->getParent();
6997 if (!BB)
6998 return false;
6999 auto *BI = dyn_cast_or_null<CondBrInst>(Val: BB->getTerminator());
7000 if (!BI)
7001 return false;
7002 auto *IC = dyn_cast<ICmpInst>(Val: BI->getCondition());
7003 if (!IC || (IC->getOperand(i_nocapture: 0) != SI && IC->getOperand(i_nocapture: 1) != SI))
7004 return false;
7005 return true;
7006}
7007
7008/// True when a select result is replaced by one of its operands
7009/// in select-icmp sequence. This will eventually result in the elimination
7010/// of the select.
7011///
7012/// \param SI Select instruction
7013/// \param Icmp Compare instruction
7014/// \param SIOpd Operand that replaces the select
7015///
7016/// Notes:
7017/// - The replacement is global and requires dominator information
7018/// - The caller is responsible for the actual replacement
7019///
7020/// Example:
7021///
7022/// entry:
7023/// %4 = select i1 %3, %C* %0, %C* null
7024/// %5 = icmp eq %C* %4, null
7025/// br i1 %5, label %9, label %7
7026/// ...
7027/// ; <label>:7 ; preds = %entry
7028/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
7029/// ...
7030///
7031/// can be transformed to
7032///
7033/// %5 = icmp eq %C* %0, null
7034/// %6 = select i1 %3, i1 %5, i1 true
7035/// br i1 %6, label %9, label %7
7036/// ...
7037/// ; <label>:7 ; preds = %entry
7038/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
7039///
7040/// Similar when the first operand of the select is a constant or/and
7041/// the compare is for not equal rather than equal.
7042///
7043/// NOTE: The function is only called when the select and compare constants
7044/// are equal, the optimization can work only for EQ predicates. This is not a
7045/// major restriction since a NE compare should be 'normalized' to an equal
7046/// compare, which usually happens in the combiner and test case
7047/// select-cmp-br.ll checks for it.
7048bool InstCombinerImpl::replacedSelectWithOperand(SelectInst *SI,
7049 const ICmpInst *Icmp,
7050 const unsigned SIOpd) {
7051 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
7052 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
7053 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(Idx: 1);
7054 // The check for the single predecessor is not the best that can be
7055 // done. But it protects efficiently against cases like when SI's
7056 // home block has two successors, Succ and Succ1, and Succ1 predecessor
7057 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
7058 // replaced can be reached on either path. So the uniqueness check
7059 // guarantees that the path all uses of SI (outside SI's parent) are on
7060 // is disjoint from all other paths out of SI. But that information
7061 // is more expensive to compute, and the trade-off here is in favor
7062 // of compile-time. It should also be noticed that we check for a single
7063 // predecessor and not only uniqueness. This to handle the situation when
7064 // Succ and Succ1 points to the same basic block.
7065 if (Succ->getSinglePredecessor() && dominatesAllUses(DI: SI, UI: Icmp, DB: Succ)) {
7066 NumSel++;
7067 SI->replaceUsesOutsideBlock(V: SI->getOperand(i_nocapture: SIOpd), BB: SI->getParent());
7068 return true;
7069 }
7070 }
7071 return false;
7072}
7073
7074/// Try to fold the comparison based on range information we can get by checking
7075/// whether bits are known to be zero or one in the inputs.
7076Instruction *InstCombinerImpl::foldICmpUsingKnownBits(ICmpInst &I) {
7077 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
7078 Type *Ty = Op0->getType();
7079 ICmpInst::Predicate Pred = I.getPredicate();
7080
7081 // Get scalar or pointer size.
7082 unsigned BitWidth = Ty->isIntOrIntVectorTy()
7083 ? Ty->getScalarSizeInBits()
7084 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
7085
7086 if (!BitWidth)
7087 return nullptr;
7088
7089 KnownBits Op0Known(BitWidth);
7090 KnownBits Op1Known(BitWidth);
7091
7092 {
7093 // Don't use dominating conditions when folding icmp using known bits. This
7094 // may convert signed into unsigned predicates in ways that other passes
7095 // (especially IndVarSimplify) may not be able to reliably undo.
7096 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(I: &I);
7097 if (SimplifyDemandedBits(I: &I, Op: 0, DemandedMask: getDemandedBitsLHSMask(I, BitWidth),
7098 Known&: Op0Known, Q))
7099 return &I;
7100
7101 if (SimplifyDemandedBits(I: &I, Op: 1, DemandedMask: APInt::getAllOnes(numBits: BitWidth), Known&: Op1Known, Q))
7102 return &I;
7103 }
7104
7105 // If an unsigned samesign comparison is not poison, both operands have the
7106 // same sign bit. Propagate a known sign bit between the temporary KnownBits
7107 // values so the existing range folds can use that constraint.
7108 if (I.hasSameSign() && I.isUnsigned()) {
7109 auto PropagateSignBit = [](const KnownBits &From, KnownBits &To) {
7110 if (To.isNegative() || To.isNonNegative())
7111 return;
7112 if (From.isNegative())
7113 To.makeNegative();
7114 else if (From.isNonNegative())
7115 To.makeNonNegative();
7116 };
7117 PropagateSignBit(Op0Known, Op1Known);
7118 PropagateSignBit(Op1Known, Op0Known);
7119 }
7120
7121 if (!isa<Constant>(Val: Op0) && Op0Known.isConstant())
7122 return new ICmpInst(
7123 Pred, ConstantExpr::getIntegerValue(Ty, V: Op0Known.getConstant()), Op1);
7124 if (!isa<Constant>(Val: Op1) && Op1Known.isConstant())
7125 return new ICmpInst(
7126 Pred, Op0, ConstantExpr::getIntegerValue(Ty, V: Op1Known.getConstant()));
7127
7128 if (std::optional<bool> Res = ICmpInst::compare(LHS: Op0Known, RHS: Op1Known, Pred))
7129 return replaceInstUsesWith(I, V: ConstantInt::getBool(Ty: I.getType(), V: *Res));
7130
7131 // Given the known and unknown bits, compute a range that the LHS could be
7132 // in. Compute the Min, Max and RHS values based on the known bits. For the
7133 // EQ and NE we use unsigned values.
7134 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
7135 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
7136 if (I.isSigned()) {
7137 Op0Min = Op0Known.getSignedMinValue();
7138 Op0Max = Op0Known.getSignedMaxValue();
7139 Op1Min = Op1Known.getSignedMinValue();
7140 Op1Max = Op1Known.getSignedMaxValue();
7141 } else {
7142 Op0Min = Op0Known.getMinValue();
7143 Op0Max = Op0Known.getMaxValue();
7144 Op1Min = Op1Known.getMinValue();
7145 Op1Max = Op1Known.getMaxValue();
7146 }
7147
7148 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
7149 // min/max canonical compare with some other compare. That could lead to
7150 // conflict with select canonicalization and infinite looping.
7151 // FIXME: This constraint may go away if min/max intrinsics are canonical.
7152 auto isMinMaxCmp = [&](Instruction &Cmp) {
7153 if (!Cmp.hasOneUse())
7154 return false;
7155 Value *A, *B;
7156 SelectPatternFlavor SPF = matchSelectPattern(V: Cmp.user_back(), LHS&: A, RHS&: B).Flavor;
7157 if (!SelectPatternResult::isMinOrMax(SPF))
7158 return false;
7159 return match(V: Op0, P: m_MaxOrMin(Op0: m_Value(), Op1: m_Value())) ||
7160 match(V: Op1, P: m_MaxOrMin(Op0: m_Value(), Op1: m_Value()));
7161 };
7162 if (!isMinMaxCmp(I)) {
7163 switch (Pred) {
7164 default:
7165 break;
7166 case ICmpInst::ICMP_ULT: {
7167 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
7168 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7169 const APInt *CmpC;
7170 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7171 // A <u C -> A == C-1 if min(A)+1 == C
7172 if (*CmpC == Op0Min + 1)
7173 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7174 ConstantInt::get(Ty: Op1->getType(), V: *CmpC - 1));
7175 // X <u C --> X == 0, if the number of zero bits in the bottom of X
7176 // exceeds the log2 of C.
7177 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
7178 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7179 Constant::getNullValue(Ty: Op1->getType()));
7180 }
7181 break;
7182 }
7183 case ICmpInst::ICMP_UGT: {
7184 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
7185 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7186 const APInt *CmpC;
7187 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7188 // A >u C -> A == C+1 if max(a)-1 == C
7189 if (*CmpC == Op0Max - 1)
7190 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7191 ConstantInt::get(Ty: Op1->getType(), V: *CmpC + 1));
7192 // X >u C --> X != 0, if the number of zero bits in the bottom of X
7193 // exceeds the log2 of C.
7194 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
7195 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
7196 Constant::getNullValue(Ty: Op1->getType()));
7197 }
7198 break;
7199 }
7200 case ICmpInst::ICMP_SLT: {
7201 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
7202 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7203 const APInt *CmpC;
7204 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7205 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
7206 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7207 ConstantInt::get(Ty: Op1->getType(), V: *CmpC - 1));
7208 }
7209 break;
7210 }
7211 case ICmpInst::ICMP_SGT: {
7212 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
7213 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7214 const APInt *CmpC;
7215 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7216 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
7217 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7218 ConstantInt::get(Ty: Op1->getType(), V: *CmpC + 1));
7219 }
7220 break;
7221 }
7222 }
7223 }
7224
7225 // Based on the range information we know about the LHS, see if we can
7226 // simplify this comparison. For example, (x&4) < 8 is always true.
7227 switch (Pred) {
7228 default:
7229 break;
7230 case ICmpInst::ICMP_EQ:
7231 case ICmpInst::ICMP_NE: {
7232 // If all bits are known zero except for one, then we know at most one bit
7233 // is set. If the comparison is against zero, then this is a check to see if
7234 // *that* bit is set.
7235 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
7236 if (Op1Known.isZero()) {
7237 // If the LHS is an AND with the same constant, look through it.
7238 Value *LHS = nullptr;
7239 const APInt *LHSC;
7240 if (!match(V: Op0, P: m_And(L: m_Value(V&: LHS), R: m_APInt(Res&: LHSC))) ||
7241 *LHSC != Op0KnownZeroInverted)
7242 LHS = Op0;
7243
7244 Value *X;
7245 const APInt *C1;
7246 if (match(V: LHS, P: m_Shl(L: m_Power2(V&: C1), R: m_Value(V&: X)))) {
7247 Type *XTy = X->getType();
7248 unsigned Log2C1 = C1->countr_zero();
7249 APInt C2 = Op0KnownZeroInverted;
7250 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
7251 if (C2Pow2.isPowerOf2()) {
7252 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
7253 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
7254 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
7255 unsigned Log2C2 = C2Pow2.countr_zero();
7256 auto *CmpC = ConstantInt::get(Ty: XTy, V: Log2C2 - Log2C1);
7257 auto NewPred =
7258 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
7259 return new ICmpInst(NewPred, X, CmpC);
7260 }
7261 }
7262 }
7263
7264 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
7265 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
7266 (Op0Known & Op1Known) == Op0Known)
7267 return new ICmpInst(CmpInst::getInversePredicate(pred: Pred), Op0,
7268 ConstantInt::getNullValue(Ty: Op1->getType()));
7269 break;
7270 }
7271 case ICmpInst::ICMP_SGE:
7272 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
7273 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7274 break;
7275 case ICmpInst::ICMP_SLE:
7276 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
7277 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7278 break;
7279 case ICmpInst::ICMP_UGE:
7280 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
7281 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7282 break;
7283 case ICmpInst::ICMP_ULE:
7284 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
7285 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7286 break;
7287 }
7288
7289 // Turn a signed comparison into an unsigned one if both operands are known to
7290 // have the same sign. Set samesign if possible (except for equality
7291 // predicates).
7292 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
7293 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
7294 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
7295 I.setPredicate(I.getUnsignedPredicate());
7296 I.setSameSign();
7297 return &I;
7298 }
7299
7300 return nullptr;
7301}
7302
7303/// If one operand of an icmp is effectively a bool (value range of {0,1}),
7304/// then try to reduce patterns based on that limit.
7305Instruction *InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst &I) {
7306 Value *X, *Y;
7307 CmpPredicate Pred;
7308
7309 // X must be 0 and bool must be true for "ULT":
7310 // X <u (zext i1 Y) --> (X == 0) & Y
7311 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))))) &&
7312 Y->getType()->isIntOrIntVectorTy(BitWidth: 1) && Pred == ICmpInst::ICMP_ULT)
7313 return BinaryOperator::CreateAnd(V1: Builder.CreateIsNull(Arg: X), V2: Y);
7314
7315 // X must be 0 or bool must be true for "ULE":
7316 // X <=u (sext i1 Y) --> (X == 0) | Y
7317 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))))) &&
7318 Y->getType()->isIntOrIntVectorTy(BitWidth: 1) && Pred == ICmpInst::ICMP_ULE)
7319 return BinaryOperator::CreateOr(V1: Builder.CreateIsNull(Arg: X), V2: Y);
7320
7321 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
7322 CmpPredicate Pred1, Pred2;
7323 const APInt *C;
7324 Instruction *ExtI;
7325 if (match(V: &I, P: m_c_ICmp(Pred&: Pred1, L: m_Value(V&: X),
7326 R: m_CombineAnd(Ps: m_Instruction(I&: ExtI),
7327 Ps: m_ZExtOrSExt(Op: m_ICmp(Pred&: Pred2, L: m_Deferred(V: X),
7328 R: m_APInt(Res&: C)))))) &&
7329 ICmpInst::isEquality(P: Pred1) && ICmpInst::isEquality(P: Pred2)) {
7330 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
7331 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(i: 0)->hasOneUse();
7332 auto CreateRangeCheck = [&] {
7333 Value *CmpV1 =
7334 Builder.CreateICmp(P: Pred1, LHS: X, RHS: Constant::getNullValue(Ty: X->getType()));
7335 Value *CmpV2 = Builder.CreateICmp(
7336 P: Pred1, LHS: X, RHS: ConstantInt::getSigned(Ty: X->getType(), V: IsSExt ? -1 : 1));
7337 return BinaryOperator::Create(
7338 Op: Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
7339 S1: CmpV1, S2: CmpV2);
7340 };
7341 if (C->isZero()) {
7342 if (Pred2 == ICmpInst::ICMP_EQ) {
7343 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
7344 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
7345 return replaceInstUsesWith(
7346 I, V: ConstantInt::getBool(Ty: I.getType(), V: Pred1 == ICmpInst::ICMP_NE));
7347 } else if (!IsSExt || HasOneUse) {
7348 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
7349 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
7350 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
7351 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X != -1
7352 return CreateRangeCheck();
7353 }
7354 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
7355 if (Pred2 == ICmpInst::ICMP_NE) {
7356 // icmp eq X, (zext (icmp ne X, 1)) --> false
7357 // icmp ne X, (zext (icmp ne X, 1)) --> true
7358 // icmp eq X, (sext (icmp ne X, -1)) --> false
7359 // icmp ne X, (sext (icmp ne X, -1)) --> true
7360 return replaceInstUsesWith(
7361 I, V: ConstantInt::getBool(Ty: I.getType(), V: Pred1 == ICmpInst::ICMP_NE));
7362 } else if (!IsSExt || HasOneUse) {
7363 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
7364 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
7365 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
7366 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
7367 return CreateRangeCheck();
7368 }
7369 } else {
7370 // when C != 0 && C != 1:
7371 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
7372 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
7373 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
7374 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
7375 // when C != 0 && C != -1:
7376 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
7377 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
7378 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
7379 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
7380 return ICmpInst::Create(
7381 Op: Instruction::ICmp, Pred: Pred1, S1: X,
7382 S2: ConstantInt::getSigned(Ty: X->getType(), V: Pred2 == ICmpInst::ICMP_NE
7383 ? (IsSExt ? -1 : 1)
7384 : 0));
7385 }
7386 }
7387
7388 return nullptr;
7389}
7390
7391/// If we have an icmp le or icmp ge instruction with a constant operand, turn
7392/// it into the appropriate icmp lt or icmp gt instruction. This transform
7393/// allows them to be folded in visitICmpInst.
7394static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
7395 CmpPredicate Pred = I.getCmpPredicate();
7396 if (ICmpInst::isEquality(P: Pred) || !ICmpInst::isIntPredicate(P: Pred) ||
7397 InstCombiner::isCanonicalPredicate(Pred))
7398 return nullptr;
7399
7400 Value *Op0 = I.getOperand(i_nocapture: 0);
7401 Value *Op1 = I.getOperand(i_nocapture: 1);
7402 auto *Op1C = dyn_cast<Constant>(Val: Op1);
7403 if (!Op1C)
7404 return nullptr;
7405
7406 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, C: Op1C);
7407 if (!FlippedStrictness)
7408 return nullptr;
7409
7410 auto *NewCmp =
7411 new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7412 NewCmp->setSameSign(FlippedStrictness->first.hasSameSign());
7413 return NewCmp;
7414}
7415
7416/// If we have a comparison with a non-canonical predicate, if we can update
7417/// all the users, invert the predicate and adjust all the users.
7418CmpInst *InstCombinerImpl::canonicalizeICmpPredicate(CmpInst &I) {
7419 // Is the predicate already canonical?
7420 CmpInst::Predicate Pred = I.getPredicate();
7421 if (InstCombiner::isCanonicalPredicate(Pred))
7422 return nullptr;
7423
7424 // Can all users be adjusted to predicate inversion?
7425 if (!InstCombiner::canFreelyInvertAllUsersOf(V: &I, /*IgnoredUser=*/nullptr))
7426 return nullptr;
7427
7428 // Ok, we can canonicalize comparison!
7429 // Let's first invert the comparison's predicate.
7430 I.setPredicate(CmpInst::getInversePredicate(pred: Pred));
7431 I.setName(I.getName() + ".not");
7432
7433 // And, adapt users.
7434 freelyInvertAllUsersOf(V: &I);
7435
7436 return &I;
7437}
7438
7439/// Integer compare with boolean values can always be turned into bitwise ops.
7440static Instruction *canonicalizeICmpBool(ICmpInst &I,
7441 InstCombiner::BuilderTy &Builder) {
7442 Value *A = I.getOperand(i_nocapture: 0), *B = I.getOperand(i_nocapture: 1);
7443 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
7444
7445 // A boolean compared to true/false can be simplified to Op0/true/false in
7446 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
7447 // Cases not handled by InstSimplify are always 'not' of Op0.
7448 if (match(V: B, P: m_Zero())) {
7449 switch (I.getPredicate()) {
7450 case CmpInst::ICMP_EQ: // A == 0 -> !A
7451 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
7452 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7453 return BinaryOperator::CreateNot(Op: A);
7454 default:
7455 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7456 }
7457 } else if (match(V: B, P: m_One())) {
7458 switch (I.getPredicate()) {
7459 case CmpInst::ICMP_NE: // A != 1 -> !A
7460 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7461 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7462 return BinaryOperator::CreateNot(Op: A);
7463 default:
7464 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7465 }
7466 }
7467
7468 switch (I.getPredicate()) {
7469 default:
7470 llvm_unreachable("Invalid icmp instruction!");
7471 case ICmpInst::ICMP_EQ:
7472 // icmp eq i1 A, B -> ~(A ^ B)
7473 return BinaryOperator::CreateNot(Op: Builder.CreateXor(LHS: A, RHS: B));
7474
7475 case ICmpInst::ICMP_NE:
7476 // icmp ne i1 A, B -> A ^ B
7477 return BinaryOperator::CreateXor(V1: A, V2: B);
7478
7479 case ICmpInst::ICMP_UGT:
7480 // icmp ugt -> icmp ult
7481 std::swap(a&: A, b&: B);
7482 [[fallthrough]];
7483 case ICmpInst::ICMP_ULT:
7484 // icmp ult i1 A, B -> ~A & B
7485 return BinaryOperator::CreateAnd(V1: Builder.CreateNot(V: A), V2: B);
7486
7487 case ICmpInst::ICMP_SGT:
7488 // icmp sgt -> icmp slt
7489 std::swap(a&: A, b&: B);
7490 [[fallthrough]];
7491 case ICmpInst::ICMP_SLT:
7492 // icmp slt i1 A, B -> A & ~B
7493 return BinaryOperator::CreateAnd(V1: Builder.CreateNot(V: B), V2: A);
7494
7495 case ICmpInst::ICMP_UGE:
7496 // icmp uge -> icmp ule
7497 std::swap(a&: A, b&: B);
7498 [[fallthrough]];
7499 case ICmpInst::ICMP_ULE:
7500 // icmp ule i1 A, B -> ~A | B
7501 return BinaryOperator::CreateOr(V1: Builder.CreateNot(V: A), V2: B);
7502
7503 case ICmpInst::ICMP_SGE:
7504 // icmp sge -> icmp sle
7505 std::swap(a&: A, b&: B);
7506 [[fallthrough]];
7507 case ICmpInst::ICMP_SLE:
7508 // icmp sle i1 A, B -> A | ~B
7509 return BinaryOperator::CreateOr(V1: Builder.CreateNot(V: B), V2: A);
7510 }
7511}
7512
7513// Transform pattern like:
7514// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7515// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7516// Into:
7517// (X l>> Y) != 0
7518// (X l>> Y) == 0
7519static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp,
7520 InstCombiner::BuilderTy &Builder) {
7521 CmpPredicate Pred, NewPred;
7522 Value *X, *Y;
7523 if (match(V: &Cmp,
7524 P: m_c_ICmp(Pred, L: m_OneUse(SubPattern: m_Shl(L: m_One(), R: m_Value(V&: Y))), R: m_Value(V&: X)))) {
7525 switch (Pred) {
7526 case ICmpInst::ICMP_ULE:
7527 NewPred = ICmpInst::ICMP_NE;
7528 break;
7529 case ICmpInst::ICMP_UGT:
7530 NewPred = ICmpInst::ICMP_EQ;
7531 break;
7532 default:
7533 return nullptr;
7534 }
7535 } else if (match(V: &Cmp, P: m_c_ICmp(Pred,
7536 L: m_OneUse(SubPattern: m_CombineOr(
7537 Ps: m_Not(V: m_Shl(L: m_AllOnes(), R: m_Value(V&: Y))),
7538 Ps: m_Add(L: m_Shl(L: m_One(), R: m_Value(V&: Y)),
7539 R: m_AllOnes()))),
7540 R: m_Value(V&: X)))) {
7541 // The variant with 'add' is not canonical, (the variant with 'not' is)
7542 // we only get it because it has extra uses, and can't be canonicalized,
7543
7544 switch (Pred) {
7545 case ICmpInst::ICMP_ULT:
7546 NewPred = ICmpInst::ICMP_NE;
7547 break;
7548 case ICmpInst::ICMP_UGE:
7549 NewPred = ICmpInst::ICMP_EQ;
7550 break;
7551 default:
7552 return nullptr;
7553 }
7554 } else
7555 return nullptr;
7556
7557 Value *NewX = Builder.CreateLShr(LHS: X, RHS: Y, Name: X->getName() + ".highbits");
7558 Constant *Zero = Constant::getNullValue(Ty: NewX->getType());
7559 return CmpInst::Create(Op: Instruction::ICmp, Pred: NewPred, S1: NewX, S2: Zero);
7560}
7561
7562static Instruction *foldVectorCmp(CmpInst &Cmp,
7563 InstCombiner::BuilderTy &Builder) {
7564 const CmpInst::Predicate Pred = Cmp.getPredicate();
7565 Value *LHS = Cmp.getOperand(i_nocapture: 0), *RHS = Cmp.getOperand(i_nocapture: 1);
7566 Value *V1, *V2;
7567
7568 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7569 Value *V = Builder.CreateCmp(Pred, LHS: X, RHS: Y, Name: Cmp.getName());
7570 if (auto *I = dyn_cast<Instruction>(Val: V))
7571 I->copyIRFlags(V: &Cmp);
7572 Module *M = Cmp.getModule();
7573 Function *F = Intrinsic::getOrInsertDeclaration(
7574 M, id: Intrinsic::vector_reverse, OverloadTys: V->getType());
7575 return CallInst::Create(Func: F, Args: V);
7576 };
7577
7578 if (match(V: LHS, P: m_VecReverse(Op0: m_Value(V&: V1)))) {
7579 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7580 if (match(V: RHS, P: m_VecReverse(Op0: m_Value(V&: V2))) &&
7581 (LHS->hasOneUse() || RHS->hasOneUse()))
7582 return createCmpReverse(Pred, V1, V2);
7583
7584 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7585 if (LHS->hasOneUse() && isSplatValue(V: RHS))
7586 return createCmpReverse(Pred, V1, RHS);
7587 }
7588 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7589 else if (isSplatValue(V: LHS) && match(V: RHS, P: m_OneUse(SubPattern: m_VecReverse(Op0: m_Value(V&: V2)))))
7590 return createCmpReverse(Pred, LHS, V2);
7591
7592 ArrayRef<int> M;
7593 if (!match(V: LHS, P: m_Shuffle(v1: m_Value(V&: V1), v2: m_Undef(), mask: m_Mask(M))))
7594 return nullptr;
7595
7596 // If both arguments of the cmp are shuffles that use the same mask and
7597 // shuffle within a single vector, move the shuffle after the cmp:
7598 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7599 Type *V1Ty = V1->getType();
7600 if (match(V: RHS, P: m_Shuffle(v1: m_Value(V&: V2), v2: m_Undef(), mask: m_SpecificMask(M))) &&
7601 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7602 Value *NewCmp = Builder.CreateCmp(Pred, LHS: V1, RHS: V2);
7603 return new ShuffleVectorInst(NewCmp, M);
7604 }
7605
7606 // Try to canonicalize compare with splatted operand and splat constant.
7607 // TODO: We could generalize this for more than splats. See/use the code in
7608 // InstCombiner::foldVectorBinop().
7609 Constant *C;
7610 if (!LHS->hasOneUse() || !match(V: RHS, P: m_Constant(C)))
7611 return nullptr;
7612
7613 // Length-changing splats are ok, so adjust the constants as needed:
7614 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7615 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7616 int MaskSplatIndex;
7617 if (ScalarC && match(Mask: M, P: m_SplatOrPoisonMask(MaskSplatIndex))) {
7618 // We allow poison in matching, but this transform removes it for safety.
7619 // Demanded elements analysis should be able to recover some/all of that.
7620 C = ConstantVector::getSplat(EC: cast<VectorType>(Val: V1Ty)->getElementCount(),
7621 Elt: ScalarC);
7622 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7623 Value *NewCmp = Builder.CreateCmp(Pred, LHS: V1, RHS: C);
7624 return new ShuffleVectorInst(NewCmp, NewM);
7625 }
7626
7627 return nullptr;
7628}
7629
7630// extract(uadd.with.overflow(A, B), 0) ult A
7631// -> extract(uadd.with.overflow(A, B), 1)
7632static Instruction *foldICmpOfUAddOv(ICmpInst &I) {
7633 CmpInst::Predicate Pred = I.getPredicate();
7634 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
7635
7636 Value *UAddOv;
7637 Value *A, *B;
7638 auto UAddOvResultPat = m_ExtractValue<0>(
7639 V: m_Intrinsic<Intrinsic::uadd_with_overflow>(Ops: m_Value(V&: A), Ops: m_Value(V&: B)));
7640 if (match(V: Op0, P: UAddOvResultPat) &&
7641 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7642 (Pred == ICmpInst::ICMP_EQ && match(V: Op1, P: m_ZeroInt()) &&
7643 (match(V: A, P: m_One()) || match(V: B, P: m_One()))) ||
7644 (Pred == ICmpInst::ICMP_NE && match(V: Op1, P: m_AllOnes()) &&
7645 (match(V: A, P: m_AllOnes()) || match(V: B, P: m_AllOnes())))))
7646 // extract(uadd.with.overflow(A, B), 0) < A
7647 // extract(uadd.with.overflow(A, 1), 0) == 0
7648 // extract(uadd.with.overflow(A, -1), 0) != -1
7649 UAddOv = cast<ExtractValueInst>(Val: Op0)->getAggregateOperand();
7650 else if (match(V: Op1, P: UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7651 (Op0 == A || Op0 == B))
7652 // A > extract(uadd.with.overflow(A, B), 0)
7653 UAddOv = cast<ExtractValueInst>(Val: Op1)->getAggregateOperand();
7654 else
7655 return nullptr;
7656
7657 return ExtractValueInst::Create(Agg: UAddOv, Idxs: 1);
7658}
7659
7660static Instruction *foldICmpInvariantGroup(ICmpInst &I) {
7661 if (!I.getOperand(i_nocapture: 0)->getType()->isPointerTy() ||
7662 NullPointerIsDefined(
7663 F: I.getParent()->getParent(),
7664 AS: I.getOperand(i_nocapture: 0)->getType()->getPointerAddressSpace())) {
7665 return nullptr;
7666 }
7667 Instruction *Op;
7668 if (match(V: I.getOperand(i_nocapture: 0), P: m_Instruction(I&: Op)) &&
7669 match(V: I.getOperand(i_nocapture: 1), P: m_Zero()) &&
7670 Op->isLaunderOrStripInvariantGroup()) {
7671 return ICmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(),
7672 S1: Op->getOperand(i: 0), S2: I.getOperand(i_nocapture: 1));
7673 }
7674 return nullptr;
7675}
7676
7677static Instruction *foldICmpOfVectorReduce(ICmpInst &I, const DataLayout &DL,
7678 IRBuilderBase &Builder) {
7679 if (!ICmpInst::isEquality(P: I.getPredicate()))
7680 return nullptr;
7681
7682 // The caller puts constants after non-constants.
7683 Value *Op = I.getOperand(i_nocapture: 0);
7684 Value *Const = I.getOperand(i_nocapture: 1);
7685
7686 // For Cond an equality condition, fold
7687 //
7688 // icmp (eq|ne) (vreduce_(or|and) Op), (Zero|AllOnes) ->
7689 // icmp (eq|ne) Op, (Zero|AllOnes)
7690 //
7691 // with a bitcast.
7692 Value *Vec;
7693 if ((match(V: Const, P: m_ZeroInt()) &&
7694 match(V: Op, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_or>(
7695 Ops: m_Value(V&: Vec))))) ||
7696 (match(V: Const, P: m_AllOnes()) &&
7697 match(V: Op, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_and>(
7698 Ops: m_Value(V&: Vec)))))) {
7699 auto *VecTy = dyn_cast<FixedVectorType>(Val: Vec->getType());
7700 if (!VecTy)
7701 return nullptr;
7702 Type *VecEltTy = VecTy->getElementType();
7703 unsigned ScalarBW =
7704 DL.getTypeSizeInBits(Ty: VecEltTy) * VecTy->getNumElements();
7705 if (!DL.fitsInLegalInteger(Width: ScalarBW))
7706 return nullptr;
7707 Type *ScalarTy = IntegerType::get(C&: I.getContext(), NumBits: ScalarBW);
7708 Value *NewConst = match(V: Const, P: m_ZeroInt())
7709 ? ConstantInt::get(Ty: ScalarTy, V: 0)
7710 : ConstantInt::getAllOnesValue(Ty: ScalarTy);
7711 return CmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(),
7712 S1: Builder.CreateBitCast(V: Vec, DestTy: ScalarTy), S2: NewConst);
7713 }
7714 return nullptr;
7715}
7716
7717/// This function folds patterns produced by lowering of reduce idioms, such as
7718/// llvm.vector.reduce.and which are lowered into instruction chains. This code
7719/// attempts to generate fewer number of scalar comparisons instead of vector
7720/// comparisons when possible.
7721static Instruction *foldReductionIdiom(ICmpInst &I,
7722 InstCombiner::BuilderTy &Builder,
7723 const DataLayout &DL) {
7724 if (I.getType()->isVectorTy())
7725 return nullptr;
7726 CmpPredicate OuterPred, InnerPred;
7727 Value *LHS, *RHS;
7728
7729 // Match lowering of @llvm.vector.reduce.and. Turn
7730 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7731 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7732 /// %res = icmp <pred> i8 %scalar_ne, 0
7733 ///
7734 /// into
7735 ///
7736 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7737 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7738 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7739 ///
7740 /// for <pred> in {ne, eq}.
7741 if (!match(V: &I, P: m_ICmp(Pred&: OuterPred,
7742 L: m_OneUse(SubPattern: m_BitCast(Op: m_OneUse(
7743 SubPattern: m_ICmp(Pred&: InnerPred, L: m_Value(V&: LHS), R: m_Value(V&: RHS))))),
7744 R: m_Zero())))
7745 return nullptr;
7746 auto *LHSTy = dyn_cast<FixedVectorType>(Val: LHS->getType());
7747 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7748 return nullptr;
7749 unsigned NumBits =
7750 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7751 // TODO: Relax this to "not wider than max legal integer type"?
7752 if (!DL.isLegalInteger(Width: NumBits))
7753 return nullptr;
7754
7755 if (ICmpInst::isEquality(P: OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7756 auto *ScalarTy = Builder.getIntNTy(N: NumBits);
7757 LHS = Builder.CreateBitCast(V: LHS, DestTy: ScalarTy, Name: LHS->getName() + ".scalar");
7758 RHS = Builder.CreateBitCast(V: RHS, DestTy: ScalarTy, Name: RHS->getName() + ".scalar");
7759 return ICmpInst::Create(Op: Instruction::ICmp, Pred: OuterPred, S1: LHS, S2: RHS,
7760 Name: I.getName());
7761 }
7762
7763 return nullptr;
7764}
7765
7766// This helper will be called with icmp operands in both orders.
7767Instruction *InstCombinerImpl::foldICmpCommutative(CmpPredicate Pred,
7768 Value *Op0, Value *Op1,
7769 ICmpInst &CxtI) {
7770 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7771 if (auto *GEP = dyn_cast<GEPOperator>(Val: Op0))
7772 if (Instruction *NI = foldGEPICmp(GEPLHS: GEP, RHS: Op1, Cond: Pred, I&: CxtI))
7773 return NI;
7774
7775 if (auto *SI = dyn_cast<SelectInst>(Val: Op0))
7776 if (Instruction *NI = foldSelectICmp(Pred, SI, RHS: Op1, I: CxtI))
7777 return NI;
7778
7779 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Val: Op0)) {
7780 if (Instruction *Res = foldICmpWithMinMax(I&: CxtI, MinMax, Z: Op1, Pred))
7781 return Res;
7782
7783 if (Instruction *Res = foldICmpWithClamp(I&: CxtI, X: Op1, Min: MinMax))
7784 return Res;
7785 }
7786
7787 {
7788 Value *X;
7789 const APInt *C;
7790 // icmp X+Cst, X
7791 if (match(V: Op0, P: m_Add(L: m_Value(V&: X), R: m_APInt(Res&: C))) && Op1 == X)
7792 return foldICmpAddOpConst(X, C: *C, Pred);
7793 }
7794
7795 // abs(X) >= X --> true
7796 // abs(X) u<= X --> true
7797 // abs(X) < X --> false
7798 // abs(X) u> X --> false
7799 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7800 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7801 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7802 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7803 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7804 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7805 {
7806 Value *X;
7807 Constant *C;
7808 if (match(V: Op0, P: m_Intrinsic<Intrinsic::abs>(Ops: m_Value(V&: X), Ops: m_Constant(C))) &&
7809 match(V: Op1, P: m_Specific(V: X))) {
7810 Value *NullValue = Constant::getNullValue(Ty: X->getType());
7811 Value *AllOnesValue = Constant::getAllOnesValue(Ty: X->getType());
7812 const APInt SMin =
7813 APInt::getSignedMinValue(numBits: X->getType()->getScalarSizeInBits());
7814 bool IsIntMinPosion = C->isAllOnesValue();
7815 switch (Pred) {
7816 case CmpInst::ICMP_ULE:
7817 case CmpInst::ICMP_SGE:
7818 return replaceInstUsesWith(I&: CxtI, V: ConstantInt::getTrue(Ty: CxtI.getType()));
7819 case CmpInst::ICMP_UGT:
7820 case CmpInst::ICMP_SLT:
7821 return replaceInstUsesWith(I&: CxtI, V: ConstantInt::getFalse(Ty: CxtI.getType()));
7822 case CmpInst::ICMP_UGE:
7823 case CmpInst::ICMP_SLE:
7824 case CmpInst::ICMP_EQ: {
7825 return replaceInstUsesWith(
7826 I&: CxtI, V: IsIntMinPosion
7827 ? Builder.CreateICmpSGT(LHS: X, RHS: AllOnesValue)
7828 : Builder.CreateICmpULT(
7829 LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: SMin + 1)));
7830 }
7831 case CmpInst::ICMP_ULT:
7832 case CmpInst::ICMP_SGT:
7833 case CmpInst::ICMP_NE: {
7834 return replaceInstUsesWith(
7835 I&: CxtI, V: IsIntMinPosion
7836 ? Builder.CreateICmpSLT(LHS: X, RHS: NullValue)
7837 : Builder.CreateICmpUGT(
7838 LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: SMin)));
7839 }
7840 default:
7841 llvm_unreachable("Invalid predicate!");
7842 }
7843 }
7844 }
7845
7846 const SimplifyQuery Q = SQ.getWithInstruction(I: &CxtI);
7847 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, IC&: *this))
7848 return replaceInstUsesWith(I&: CxtI, V);
7849
7850 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
7851 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(RHS: 1); };
7852 {
7853 if (match(V: Op0, P: m_UDiv(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckUGT1)))) {
7854 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7855 Constant::getNullValue(Ty: Op1->getType()));
7856 }
7857
7858 if (!ICmpInst::isUnsigned(Pred) &&
7859 match(V: Op0, P: m_SDiv(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckUGT1)))) {
7860 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7861 Constant::getNullValue(Ty: Op1->getType()));
7862 }
7863 }
7864
7865 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
7866 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
7867 {
7868 if (match(V: Op0, P: m_LShr(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckNE0)))) {
7869 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7870 Constant::getNullValue(Ty: Op1->getType()));
7871 }
7872
7873 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
7874 match(V: Op0, P: m_AShr(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckNE0)))) {
7875 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7876 Constant::getNullValue(Ty: Op1->getType()));
7877 }
7878 }
7879
7880 // icmp (shl nsw/nuw X, L), (add nsw/nuw (shl nsw/nuw Y, L), K)
7881 // -> icmp X, (add nsw/nuw Y, K >> L)
7882 // We use AShr for nsw and LShr for nuw to safely peel off the shift.
7883 Value *X;
7884 uint64_t ShAmt;
7885 if (match(V: Op0, P: m_NUWShl(L: m_Value(V&: X), R: m_ConstantInt(V&: ShAmt))) &&
7886 !CxtI.isSigned()) {
7887 if (ShAmt >= X->getType()->getScalarSizeInBits())
7888 return nullptr;
7889 if (canEvaluateShifted(V: Op1, NumBits: ShAmt, /*IsLeftShift=*/false,
7890 Semantics: ShiftSemantics::Unsigned, CxtI: &CxtI)) {
7891 Value *NewOp1 = getShiftedValue(V: Op1, NumBits: ShAmt, /*IsLeftShift=*/false,
7892 Semantics: ShiftSemantics::Unsigned);
7893 return new ICmpInst(Pred, X, NewOp1);
7894 }
7895 }
7896
7897 if (match(V: Op0, P: m_NSWShl(L: m_Value(V&: X), R: m_ConstantInt(V&: ShAmt))) &&
7898 !CxtI.isUnsigned()) {
7899 if (ShAmt >= X->getType()->getScalarSizeInBits())
7900 return nullptr;
7901 if (canEvaluateShifted(V: Op1, NumBits: ShAmt, /*IsLeftShift=*/false,
7902 Semantics: ShiftSemantics::Signed, CxtI: &CxtI)) {
7903 Value *NewOp1 = getShiftedValue(V: Op1, NumBits: ShAmt, /*IsLeftShift=*/false,
7904 Semantics: ShiftSemantics::Signed);
7905 return new ICmpInst(Pred, X, NewOp1);
7906 }
7907 }
7908 return nullptr;
7909}
7910
7911Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {
7912 bool Changed = false;
7913 const SimplifyQuery Q = SQ.getWithInstruction(I: &I);
7914 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
7915 unsigned Op0Cplxity = getComplexity(V: Op0);
7916 unsigned Op1Cplxity = getComplexity(V: Op1);
7917
7918 /// Orders the operands of the compare so that they are listed from most
7919 /// complex to least complex. This puts constants before unary operators,
7920 /// before binary operators.
7921 if (Op0Cplxity < Op1Cplxity) {
7922 I.swapOperands();
7923 std::swap(a&: Op0, b&: Op1);
7924 Changed = true;
7925 }
7926
7927 if (Value *V = simplifyICmpInst(Pred: I.getCmpPredicate(), LHS: Op0, RHS: Op1, Q))
7928 return replaceInstUsesWith(I, V);
7929
7930 // Comparing -val or val with non-zero is the same as just comparing val
7931 // ie, abs(val) != 0 -> val != 0
7932 if (I.getPredicate() == ICmpInst::ICMP_NE && match(V: Op1, P: m_Zero())) {
7933 Value *Cond, *SelectTrue, *SelectFalse;
7934 if (match(V: Op0, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: SelectTrue),
7935 R: m_Value(V&: SelectFalse)))) {
7936 if (Value *V = dyn_castNegVal(V: SelectTrue)) {
7937 if (V == SelectFalse)
7938 return CmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(), S1: V, S2: Op1);
7939 } else if (Value *V = dyn_castNegVal(V: SelectFalse)) {
7940 if (V == SelectTrue)
7941 return CmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(), S1: V, S2: Op1);
7942 }
7943 }
7944 }
7945
7946 if (Instruction *Res = foldICmpTruncWithTruncOrExt(Cmp&: I, Q))
7947 return Res;
7948
7949 if (Op0->getType()->isIntOrIntVectorTy(BitWidth: 1))
7950 if (Instruction *Res = canonicalizeICmpBool(I, Builder))
7951 return Res;
7952
7953 if (Instruction *Res = canonicalizeCmpWithConstant(I))
7954 return Res;
7955
7956 if (Instruction *Res = canonicalizeICmpPredicate(I))
7957 return Res;
7958
7959 if (Instruction *Res = foldICmpWithConstant(Cmp&: I))
7960 return Res;
7961
7962 if (Instruction *Res = foldICmpWithDominatingICmp(Cmp&: I))
7963 return Res;
7964
7965 if (Instruction *Res = foldICmpUsingBoolRange(I))
7966 return Res;
7967
7968 if (Instruction *Res = foldICmpUsingKnownBits(I))
7969 return Res;
7970
7971 if (Instruction *Res = foldIsMultipleOfAPowerOfTwo(Cmp&: I))
7972 return Res;
7973
7974 // Test if the ICmpInst instruction is used exclusively by a select as
7975 // part of a minimum or maximum operation. If so, refrain from doing
7976 // any other folding. This helps out other analyses which understand
7977 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
7978 // and CodeGen. And in this case, at least one of the comparison
7979 // operands has at least one user besides the compare (the select),
7980 // which would often largely negate the benefit of folding anyway.
7981 //
7982 // Do the same for the other patterns recognized by matchSelectPattern.
7983 if (I.hasOneUse())
7984 if (SelectInst *SI = dyn_cast<SelectInst>(Val: I.user_back())) {
7985 Value *A, *B;
7986 SelectPatternResult SPR = matchSelectPattern(V: SI, LHS&: A, RHS&: B);
7987 if (SPR.Flavor != SPF_UNKNOWN)
7988 return nullptr;
7989 }
7990
7991 // Do this after checking for min/max to prevent infinite looping.
7992 if (Instruction *Res = foldICmpWithZero(Cmp&: I))
7993 return Res;
7994
7995 Value *X;
7996 const APInt *C;
7997 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
7998 match(V: Op0, P: m_UMax(Op0: m_Value(V&: X), Op1: m_APInt(Res&: C))) &&
7999 match(V: Op1, P: m_Not(V: m_Specific(V: X)))) {
8000 if (C->isNonNegative())
8001 return new ICmpInst(ICmpInst::ICMP_SLT, X,
8002 Constant::getNullValue(Ty: X->getType()));
8003 return new ICmpInst(ICmpInst::ICMP_UGT, X,
8004 ConstantInt::get(Ty: X->getType(), V: ~*C));
8005 }
8006
8007 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
8008 match(V: Op0, P: m_UMax(Op0: m_Value(V&: X), Op1: m_APInt(Res&: C))) &&
8009 match(V: Op1, P: m_Not(V: m_Specific(V: X)))) {
8010 if (C->isNonNegative())
8011 return new ICmpInst(ICmpInst::ICMP_SGT, X,
8012 Constant::getAllOnesValue(Ty: X->getType()));
8013 return new ICmpInst(ICmpInst::ICMP_ULT, X,
8014 ConstantInt::get(Ty: X->getType(), V: ~*C));
8015 }
8016
8017 // FIXME: We only do this after checking for min/max to prevent infinite
8018 // looping caused by a reverse canonicalization of these patterns for min/max.
8019 // FIXME: The organization of folds is a mess. These would naturally go into
8020 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
8021 // down here after the min/max restriction.
8022 ICmpInst::Predicate Pred = I.getPredicate();
8023 if (match(V: Op1, P: m_APInt(Res&: C))) {
8024 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
8025 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
8026 Constant *Zero = Constant::getNullValue(Ty: Op0->getType());
8027 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
8028 }
8029
8030 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
8031 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
8032 Constant *AllOnes = Constant::getAllOnesValue(Ty: Op0->getType());
8033 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
8034 }
8035 }
8036
8037 // The folds in here may rely on wrapping flags and special constants, so
8038 // they can break up min/max idioms in some cases but not seemingly similar
8039 // patterns.
8040 // FIXME: It may be possible to enhance select folding to make this
8041 // unnecessary. It may also be moot if we canonicalize to min/max
8042 // intrinsics.
8043 if (Instruction *Res = foldICmpBinOp(I, SQ: Q))
8044 return Res;
8045
8046 if (Instruction *Res = foldICmpInstWithConstant(Cmp&: I))
8047 return Res;
8048
8049 // Try to match comparison as a sign bit test. Intentionally do this after
8050 // foldICmpInstWithConstant() to potentially let other folds to happen first.
8051 if (Instruction *New = foldSignBitTest(I))
8052 return New;
8053
8054 if (auto *PN = dyn_cast<PHINode>(Val: Op0))
8055 if (Instruction *NV = foldOpIntoPhi(I, PN))
8056 return NV;
8057 if (auto *PN = dyn_cast<PHINode>(Val: Op1))
8058 if (Instruction *NV = foldOpIntoPhi(I, PN))
8059 return NV;
8060
8061 if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
8062 return Res;
8063
8064 if (Instruction *Res = foldICmpCommutative(Pred: I.getCmpPredicate(), Op0, Op1, CxtI&: I))
8065 return Res;
8066 if (Instruction *Res =
8067 foldICmpCommutative(Pred: I.getSwappedCmpPredicate(), Op0: Op1, Op1: Op0, CxtI&: I))
8068 return Res;
8069
8070 if (I.isCommutative()) {
8071 if (auto Pair = matchSymmetricPair(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1))) {
8072 replaceOperand(I, OpNum: 0, V: Pair->first);
8073 replaceOperand(I, OpNum: 1, V: Pair->second);
8074 return &I;
8075 }
8076 }
8077
8078 // Fold icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8079 // when all select arms are constants, via truth table.
8080 if (Instruction *R = foldCmpSelectOfConstants(I))
8081 return R;
8082
8083 // In case of a comparison with two select instructions having the same
8084 // condition, check whether one of the resulting branches can be simplified.
8085 // If so, just compare the other branch and select the appropriate result.
8086 // For example:
8087 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
8088 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
8089 // %cmp2 = icmp slt i32 %tmp2, %tmp1
8090 // The icmp will result false for the false value of selects and the result
8091 // will depend upon the comparison of true values of selects if %cmp is
8092 // true. Thus, transform this into:
8093 // %cmp = icmp slt i32 %y, %z
8094 // %sel = select i1 %cond, i1 %cmp, i1 false
8095 // This handles similar cases to transform.
8096 {
8097 Value *Cond, *A, *B, *C, *D;
8098 if (match(V: Op0, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: A), R: m_Value(V&: B))) &&
8099 match(V: Op1, P: m_Select(C: m_Specific(V: Cond), L: m_Value(V&: C), R: m_Value(V&: D))) &&
8100 (Op0->hasOneUse() || Op1->hasOneUse())) {
8101 // Check whether comparison of TrueValues can be simplified
8102 if (Value *Res = simplifyICmpInst(Pred, LHS: A, RHS: C, Q: SQ)) {
8103 Value *NewICMP = Builder.CreateICmp(P: Pred, LHS: B, RHS: D);
8104 return SelectInst::Create(
8105 C: Cond, S1: Res, S2: NewICMP, /*NameStr=*/"", /*InsertBefore=*/nullptr,
8106 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : cast<Instruction>(Val: Op0));
8107 }
8108 // Check whether comparison of FalseValues can be simplified
8109 if (Value *Res = simplifyICmpInst(Pred, LHS: B, RHS: D, Q: SQ)) {
8110 Value *NewICMP = Builder.CreateICmp(P: Pred, LHS: A, RHS: C);
8111 return SelectInst::Create(
8112 C: Cond, S1: NewICMP, S2: Res, /*NameStr=*/"", /*InsertBefore=*/nullptr,
8113 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : cast<Instruction>(Val: Op0));
8114 }
8115 }
8116 }
8117
8118 // icmp slt (sub nsw x, y), (add nsw x, y) --> icmp sgt y, 0
8119 // icmp ult (sub nuw x, y), (add nuw x, y) --> icmp ugt y, 0
8120 // icmp eq (sub nsw/nuw x, y), (add nsw/nuw x, y) --> icmp eq y, 0
8121 {
8122 Value *A, *B;
8123 CmpPredicate CmpPred;
8124 if (match(V: &I, P: m_c_ICmp(Pred&: CmpPred, L: m_Sub(L: m_Value(V&: A), R: m_Value(V&: B)),
8125 R: m_c_Add(L: m_Deferred(V: A), R: m_Deferred(V: B))))) {
8126 auto *I0 = cast<OverflowingBinaryOperator>(Val: Op0);
8127 auto *I1 = cast<OverflowingBinaryOperator>(Val: Op1);
8128 bool I0NUW = I0->hasNoUnsignedWrap();
8129 bool I1NUW = I1->hasNoUnsignedWrap();
8130 bool I0NSW = I0->hasNoSignedWrap();
8131 bool I1NSW = I1->hasNoSignedWrap();
8132 if ((ICmpInst::isUnsigned(Pred) && I0NUW && I1NUW) ||
8133 (ICmpInst::isSigned(Pred) && I0NSW && I1NSW) ||
8134 (ICmpInst::isEquality(P: Pred) &&
8135 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
8136 return new ICmpInst(CmpPredicate::getSwapped(P: CmpPred), B,
8137 ConstantInt::get(Ty: Op0->getType(), V: 0));
8138 }
8139 }
8140 }
8141
8142 // Try to optimize equality comparisons against alloca-based pointers.
8143 if (Op0->getType()->isPointerTy() && I.isEquality()) {
8144 assert(Op1->getType()->isPointerTy() &&
8145 "Comparing pointer with non-pointer?");
8146 if (auto *Alloca = dyn_cast<AllocaInst>(Val: getUnderlyingObject(V: Op0)))
8147 if (foldAllocaCmp(Alloca))
8148 return nullptr;
8149 if (auto *Alloca = dyn_cast<AllocaInst>(Val: getUnderlyingObject(V: Op1)))
8150 if (foldAllocaCmp(Alloca))
8151 return nullptr;
8152 }
8153
8154 if (Instruction *Res = foldICmpBitCast(Cmp&: I))
8155 return Res;
8156
8157 // TODO: Hoist this above the min/max bailout.
8158 if (Instruction *R = foldICmpWithCastOp(ICmp&: I))
8159 return R;
8160
8161 {
8162 Value *X, *Y;
8163 // Transform (X & ~Y) == 0 --> (X & Y) != 0
8164 // and (X & ~Y) != 0 --> (X & Y) == 0
8165 // if A is a power of 2.
8166 if (match(V: Op0, P: m_And(L: m_Value(V&: X), R: m_Not(V: m_Value(V&: Y)))) &&
8167 match(V: Op1, P: m_Zero()) && isKnownToBeAPowerOfTwo(V: X, OrZero: false, CxtI: &I) &&
8168 I.isEquality())
8169 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(LHS: X, RHS: Y),
8170 Op1);
8171
8172 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
8173 if (Op0->getType()->isIntOrIntVectorTy()) {
8174 bool ConsumesOp0, ConsumesOp1;
8175 if (isFreeToInvert(V: Op0, WillInvertAllUses: Op0->hasOneUse(), DoesConsume&: ConsumesOp0) &&
8176 isFreeToInvert(V: Op1, WillInvertAllUses: Op1->hasOneUse(), DoesConsume&: ConsumesOp1) &&
8177 (ConsumesOp0 || ConsumesOp1)) {
8178 Value *InvOp0 = getFreelyInverted(V: Op0, WillInvertAllUses: Op0->hasOneUse(), Builder: &Builder);
8179 Value *InvOp1 = getFreelyInverted(V: Op1, WillInvertAllUses: Op1->hasOneUse(), Builder: &Builder);
8180 assert(InvOp0 && InvOp1 &&
8181 "Mismatch between isFreeToInvert and getFreelyInverted");
8182 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
8183 }
8184 }
8185
8186 Instruction *AddI = nullptr;
8187 if (match(V: &I, P: m_UAddWithOverflow(L: m_Value(V&: X), R: m_Value(V&: Y),
8188 S: m_Instruction(I&: AddI))) &&
8189 isa<IntegerType>(Val: X->getType())) {
8190 Value *Result;
8191 Constant *Overflow;
8192 // m_UAddWithOverflow can match patterns that do not include an explicit
8193 // "add" instruction, so check the opcode of the matched op.
8194 if (AddI->getOpcode() == Instruction::Add &&
8195 OptimizeOverflowCheck(BinaryOp: Instruction::Add, /*Signed*/ IsSigned: false, LHS: X, RHS: Y, OrigI&: *AddI,
8196 Result, Overflow)) {
8197 replaceInstUsesWith(I&: *AddI, V: Result);
8198 eraseInstFromFunction(I&: *AddI);
8199 return replaceInstUsesWith(I, V: Overflow);
8200 }
8201 }
8202
8203 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
8204 if (match(V: Op0, P: m_NUWMul(L: m_ZExt(Op: m_Value(V&: X)), R: m_ZExt(Op: m_Value(V&: Y)))) &&
8205 match(V: Op1, P: m_APInt(Res&: C))) {
8206 if (Instruction *R = processUMulZExtIdiom(I, MulVal: Op0, OtherVal: C, IC&: *this))
8207 return R;
8208 }
8209
8210 // Signbit test folds
8211 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
8212 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
8213 Instruction *ExtI;
8214 if ((I.isUnsigned() || I.isEquality()) &&
8215 match(V: Op1,
8216 P: m_CombineAnd(Ps: m_Instruction(I&: ExtI), Ps: m_ZExtOrSExt(Op: m_Value(V&: Y)))) &&
8217 Y->getType()->getScalarSizeInBits() == 1 &&
8218 (Op0->hasOneUse() || Op1->hasOneUse())) {
8219 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
8220 Instruction *ShiftI;
8221 if (match(V: Op0, P: m_CombineAnd(Ps: m_Instruction(I&: ShiftI),
8222 Ps: m_Shr(L: m_Value(V&: X), R: m_SpecificIntAllowPoison(
8223 V: OpWidth - 1))))) {
8224 unsigned ExtOpc = ExtI->getOpcode();
8225 unsigned ShiftOpc = ShiftI->getOpcode();
8226 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
8227 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
8228 Value *SLTZero =
8229 Builder.CreateICmpSLT(LHS: X, RHS: Constant::getNullValue(Ty: X->getType()));
8230 Value *Cmp = Builder.CreateICmp(P: Pred, LHS: SLTZero, RHS: Y, Name: I.getName());
8231 return replaceInstUsesWith(I, V: Cmp);
8232 }
8233 }
8234 }
8235 }
8236
8237 if (Instruction *Res = foldICmpEquality(I))
8238 return Res;
8239
8240 if (Instruction *Res = foldICmpPow2Test(I, Builder))
8241 return Res;
8242
8243 if (Instruction *Res = foldICmpOfUAddOv(I))
8244 return Res;
8245
8246 if (Instruction *Res = foldICmpOfVectorReduce(I, DL, Builder))
8247 return Res;
8248
8249 // The 'cmpxchg' instruction returns an aggregate containing the old value and
8250 // an i1 which indicates whether or not we successfully did the swap.
8251 //
8252 // Replace comparisons between the old value and the expected value with the
8253 // indicator that 'cmpxchg' returns.
8254 //
8255 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
8256 // spuriously fail. In those cases, the old value may equal the expected
8257 // value but it is possible for the swap to not occur.
8258 if (I.getPredicate() == ICmpInst::ICMP_EQ)
8259 if (auto *EVI = dyn_cast<ExtractValueInst>(Val: Op0))
8260 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(Val: EVI->getAggregateOperand()))
8261 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
8262 !ACXI->isWeak())
8263 return ExtractValueInst::Create(Agg: ACXI, Idxs: 1);
8264
8265 if (Instruction *Res = foldICmpWithHighBitMask(Cmp&: I, Builder))
8266 return Res;
8267
8268 if (I.getType()->isVectorTy())
8269 if (Instruction *Res = foldVectorCmp(Cmp&: I, Builder))
8270 return Res;
8271
8272 if (Instruction *Res = foldICmpInvariantGroup(I))
8273 return Res;
8274
8275 if (Instruction *Res = foldReductionIdiom(I, Builder, DL))
8276 return Res;
8277
8278 {
8279 Value *A;
8280 const APInt *C1, *C2;
8281 ICmpInst::Predicate Pred = I.getPredicate();
8282 if (ICmpInst::isEquality(P: Pred)) {
8283 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
8284 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
8285 if (match(V: Op0, P: m_And(L: m_SExt(Op: m_Value(V&: A)), R: m_APInt(Res&: C1))) &&
8286 match(V: Op1, P: m_APInt(Res&: C2))) {
8287 Type *InputTy = A->getType();
8288 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
8289 // c2 must be non-negative at the bitwidth of a.
8290 if (C2->getActiveBits() < InputBitWidth) {
8291 APInt TruncC1 = C1->trunc(width: InputBitWidth);
8292 // Check if there are 1s in C1 high bits of size InputBitWidth.
8293 if (C1->uge(RHS: APInt::getOneBitSet(numBits: C1->getBitWidth(), BitNo: InputBitWidth)))
8294 TruncC1.setBit(InputBitWidth - 1);
8295 Value *AndInst = Builder.CreateAnd(LHS: A, RHS: TruncC1);
8296 return new ICmpInst(
8297 Pred, AndInst,
8298 ConstantInt::get(Ty: InputTy, V: C2->trunc(width: InputBitWidth)));
8299 }
8300 }
8301 }
8302 }
8303
8304 return Changed ? &I : nullptr;
8305}
8306
8307/// Fold fcmp ([us]itofp x, cst) if possible.
8308Instruction *InstCombinerImpl::foldFCmpIntToFPConst(FCmpInst &I,
8309 Instruction *LHSI,
8310 Constant *RHSC) {
8311 const APFloat *RHS;
8312 if (!match(V: RHSC, P: m_APFloat(Res&: RHS)))
8313 return nullptr;
8314
8315 // Get the width of the mantissa. We don't want to hack on conversions that
8316 // might lose information from the integer, e.g. "i64 -> float"
8317 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8318 if (MantissaWidth == -1)
8319 return nullptr; // Unknown.
8320
8321 Type *IntTy = LHSI->getOperand(i: 0)->getType();
8322 unsigned IntWidth = IntTy->getScalarSizeInBits();
8323 bool LHSUnsigned = isa<UIToFPInst>(Val: LHSI);
8324
8325 if (I.isEquality()) {
8326 FCmpInst::Predicate P = I.getPredicate();
8327 bool IsExact = false;
8328 APSInt RHSCvt(IntWidth, LHSUnsigned);
8329 RHS->convertToInteger(Result&: RHSCvt, RM: APFloat::rmNearestTiesToEven, IsExact: &IsExact);
8330
8331 // If the floating point constant isn't an integer value, we know if we will
8332 // ever compare equal / not equal to it.
8333 if (!IsExact) {
8334 // TODO: Can never be -0.0 and other non-representable values
8335 APFloat RHSRoundInt(*RHS);
8336 RHSRoundInt.roundToIntegral(RM: APFloat::rmNearestTiesToEven);
8337 if (*RHS != RHSRoundInt) {
8338 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
8339 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8340
8341 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
8342 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8343 }
8344 }
8345
8346 // TODO: If the constant is exactly representable, is it always OK to do
8347 // equality compares as integer?
8348 }
8349
8350 // Check to see that the input is converted from an integer type that is small
8351 // enough that preserves all bits. TODO: check here for "known" sign bits.
8352 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
8353
8354 // Following test does NOT adjust IntWidth downwards for signed inputs,
8355 // because the most negative value still requires all the mantissa bits
8356 // to distinguish it from one less than that value.
8357 if ((int)IntWidth > MantissaWidth) {
8358 // Conversion would lose accuracy. Check if loss can impact comparison.
8359 int Exp = ilogb(Arg: *RHS);
8360 if (Exp == APFloat::IEK_Inf) {
8361 int MaxExponent = ilogb(Arg: APFloat::getLargest(Sem: RHS->getSemantics()));
8362 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
8363 // Conversion could create infinity.
8364 return nullptr;
8365 } else {
8366 // Note that if RHS is zero or NaN, then Exp is negative
8367 // and first condition is trivially false.
8368 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
8369 // Conversion could affect comparison.
8370 return nullptr;
8371 }
8372 }
8373
8374 // Otherwise, we can potentially simplify the comparison. We know that it
8375 // will always come through as an integer value and we know the constant is
8376 // not a NAN (it would have been previously simplified).
8377 assert(!RHS->isNaN() && "NaN comparison not already folded!");
8378
8379 ICmpInst::Predicate Pred;
8380 switch (I.getPredicate()) {
8381 default:
8382 llvm_unreachable("Unexpected predicate!");
8383 case FCmpInst::FCMP_UEQ:
8384 case FCmpInst::FCMP_OEQ:
8385 Pred = ICmpInst::ICMP_EQ;
8386 break;
8387 case FCmpInst::FCMP_UGT:
8388 case FCmpInst::FCMP_OGT:
8389 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
8390 break;
8391 case FCmpInst::FCMP_UGE:
8392 case FCmpInst::FCMP_OGE:
8393 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
8394 break;
8395 case FCmpInst::FCMP_ULT:
8396 case FCmpInst::FCMP_OLT:
8397 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
8398 break;
8399 case FCmpInst::FCMP_ULE:
8400 case FCmpInst::FCMP_OLE:
8401 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
8402 break;
8403 case FCmpInst::FCMP_UNE:
8404 case FCmpInst::FCMP_ONE:
8405 Pred = ICmpInst::ICMP_NE;
8406 break;
8407 case FCmpInst::FCMP_ORD:
8408 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8409 case FCmpInst::FCMP_UNO:
8410 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8411 }
8412
8413 // Now we know that the APFloat is a normal number, zero or inf.
8414
8415 // See if the FP constant is too large for the integer. For example,
8416 // comparing an i8 to 300.0.
8417 if (!LHSUnsigned) {
8418 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
8419 // and large values.
8420 APFloat SMax(RHS->getSemantics());
8421 SMax.convertFromAPInt(Input: APInt::getSignedMaxValue(numBits: IntWidth), IsSigned: true,
8422 RM: APFloat::rmNearestTiesToEven);
8423 if (SMax < *RHS) { // smax < 13123.0
8424 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
8425 Pred == ICmpInst::ICMP_SLE)
8426 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8427 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8428 }
8429 } else {
8430 // If the RHS value is > UnsignedMax, fold the comparison. This handles
8431 // +INF and large values.
8432 APFloat UMax(RHS->getSemantics());
8433 UMax.convertFromAPInt(Input: APInt::getMaxValue(numBits: IntWidth), IsSigned: false,
8434 RM: APFloat::rmNearestTiesToEven);
8435 if (UMax < *RHS) { // umax < 13123.0
8436 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
8437 Pred == ICmpInst::ICMP_ULE)
8438 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8439 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8440 }
8441 }
8442
8443 if (!LHSUnsigned) {
8444 // See if the RHS value is < SignedMin.
8445 APFloat SMin(RHS->getSemantics());
8446 SMin.convertFromAPInt(Input: APInt::getSignedMinValue(numBits: IntWidth), IsSigned: true,
8447 RM: APFloat::rmNearestTiesToEven);
8448 if (SMin > *RHS) { // smin > 12312.0
8449 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
8450 Pred == ICmpInst::ICMP_SGE)
8451 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8452 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8453 }
8454 } else {
8455 // See if the RHS value is < UnsignedMin.
8456 APFloat UMin(RHS->getSemantics());
8457 UMin.convertFromAPInt(Input: APInt::getMinValue(numBits: IntWidth), IsSigned: false,
8458 RM: APFloat::rmNearestTiesToEven);
8459 if (UMin > *RHS) { // umin > 12312.0
8460 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
8461 Pred == ICmpInst::ICMP_UGE)
8462 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8463 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8464 }
8465 }
8466
8467 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
8468 // [0, UMAX], but it may still be fractional. Check whether this is the case
8469 // using the IsExact flag.
8470 // Don't do this for zero, because -0.0 is not fractional.
8471 APSInt RHSInt(IntWidth, LHSUnsigned);
8472 bool IsExact;
8473 RHS->convertToInteger(Result&: RHSInt, RM: APFloat::rmTowardZero, IsExact: &IsExact);
8474 if (!RHS->isZero()) {
8475 if (!IsExact) {
8476 // If we had a comparison against a fractional value, we have to adjust
8477 // the compare predicate and sometimes the value. RHSC is rounded towards
8478 // zero at this point.
8479 switch (Pred) {
8480 default:
8481 llvm_unreachable("Unexpected integer comparison!");
8482 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
8483 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8484 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
8485 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8486 case ICmpInst::ICMP_ULE:
8487 // (float)int <= 4.4 --> int <= 4
8488 // (float)int <= -4.4 --> false
8489 if (RHS->isNegative())
8490 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8491 break;
8492 case ICmpInst::ICMP_SLE:
8493 // (float)int <= 4.4 --> int <= 4
8494 // (float)int <= -4.4 --> int < -4
8495 if (RHS->isNegative())
8496 Pred = ICmpInst::ICMP_SLT;
8497 break;
8498 case ICmpInst::ICMP_ULT:
8499 // (float)int < -4.4 --> false
8500 // (float)int < 4.4 --> int <= 4
8501 if (RHS->isNegative())
8502 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8503 Pred = ICmpInst::ICMP_ULE;
8504 break;
8505 case ICmpInst::ICMP_SLT:
8506 // (float)int < -4.4 --> int < -4
8507 // (float)int < 4.4 --> int <= 4
8508 if (!RHS->isNegative())
8509 Pred = ICmpInst::ICMP_SLE;
8510 break;
8511 case ICmpInst::ICMP_UGT:
8512 // (float)int > 4.4 --> int > 4
8513 // (float)int > -4.4 --> true
8514 if (RHS->isNegative())
8515 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8516 break;
8517 case ICmpInst::ICMP_SGT:
8518 // (float)int > 4.4 --> int > 4
8519 // (float)int > -4.4 --> int >= -4
8520 if (RHS->isNegative())
8521 Pred = ICmpInst::ICMP_SGE;
8522 break;
8523 case ICmpInst::ICMP_UGE:
8524 // (float)int >= -4.4 --> true
8525 // (float)int >= 4.4 --> int > 4
8526 if (RHS->isNegative())
8527 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8528 Pred = ICmpInst::ICMP_UGT;
8529 break;
8530 case ICmpInst::ICMP_SGE:
8531 // (float)int >= -4.4 --> int >= -4
8532 // (float)int >= 4.4 --> int > 4
8533 if (!RHS->isNegative())
8534 Pred = ICmpInst::ICMP_SGT;
8535 break;
8536 }
8537 }
8538 }
8539
8540 // Lower this FP comparison into an appropriate integer version of the
8541 // comparison.
8542 return new ICmpInst(Pred, LHSI->getOperand(i: 0),
8543 ConstantInt::get(Ty: LHSI->getOperand(i: 0)->getType(), V: RHSInt));
8544}
8545
8546/// Fold fcmp/icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8547/// where all true/false values are constants that allow the compare to be
8548/// constant-folded for every combination of C1 and C2.
8549/// We compute a 4-entry truth table and use createLogicFromTable to
8550/// synthesize a boolean expression of C1 and C2.
8551Instruction *InstCombinerImpl::foldCmpSelectOfConstants(CmpInst &I) {
8552 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
8553 Value *C1, *C2;
8554 Constant *TV1, *FV1, *TV2, *FV2;
8555
8556 if (!match(V: Op0, P: m_Select(C: m_Value(V&: C1), L: m_Constant(C&: TV1), R: m_Constant(C&: FV1))) ||
8557 !match(V: Op1, P: m_Select(C: m_Value(V&: C2), L: m_Constant(C&: TV2), R: m_Constant(C&: FV2))))
8558 return nullptr;
8559
8560 if (I.getType() != C1->getType() || I.getType() != C2->getType())
8561 return nullptr;
8562
8563 unsigned Pred = I.getPredicate();
8564 const DataLayout &DL = I.getDataLayout();
8565
8566 Constant *Res00 = ConstantFoldCompareInstOperands(Predicate: Pred, LHS: FV1, RHS: FV2, DL);
8567 Constant *Res01 = ConstantFoldCompareInstOperands(Predicate: Pred, LHS: FV1, RHS: TV2, DL);
8568 Constant *Res10 = ConstantFoldCompareInstOperands(Predicate: Pred, LHS: TV1, RHS: FV2, DL);
8569 Constant *Res11 = ConstantFoldCompareInstOperands(Predicate: Pred, LHS: TV1, RHS: TV2, DL);
8570
8571 if (!Res00 || !Res01 || !Res10 || !Res11)
8572 return nullptr;
8573
8574 if ((!Res00->isNullValue() && !Res00->isAllOnesValue()) ||
8575 (!Res01->isNullValue() && !Res01->isAllOnesValue()) ||
8576 (!Res10->isNullValue() && !Res10->isAllOnesValue()) ||
8577 (!Res11->isNullValue() && !Res11->isAllOnesValue()))
8578 return nullptr;
8579
8580 std::bitset<4> Table;
8581 if (!Res00->isNullValue())
8582 Table.set(position: 0);
8583 if (!Res01->isNullValue())
8584 Table.set(position: 1);
8585 if (!Res10->isNullValue())
8586 Table.set(position: 2);
8587 if (!Res11->isNullValue())
8588 Table.set(position: 3);
8589
8590 Value *Res = createLogicFromTable(Table, Op0: C1, Op1: C2, Builder,
8591 HasOneUse: Op0->hasOneUse() && Op1->hasOneUse());
8592 if (!Res)
8593 return nullptr;
8594 return replaceInstUsesWith(I, V: Res);
8595}
8596
8597/// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
8598static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI,
8599 Constant *RHSC) {
8600 // When C is not 0.0 and infinities are not allowed:
8601 // (C / X) < 0.0 is a sign-bit test of X
8602 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
8603 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
8604 //
8605 // Proof:
8606 // Multiply (C / X) < 0.0 by X * X / C.
8607 // - X is non zero, if it is the flag 'ninf' is violated.
8608 // - C defines the sign of X * X * C. Thus it also defines whether to swap
8609 // the predicate. C is also non zero by definition.
8610 //
8611 // Thus X * X / C is non zero and the transformation is valid. [qed]
8612
8613 FCmpInst::Predicate Pred = I.getPredicate();
8614
8615 // Check that predicates are valid.
8616 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
8617 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
8618 return nullptr;
8619
8620 // Check that RHS operand is zero.
8621 if (!match(V: RHSC, P: m_AnyZeroFP()))
8622 return nullptr;
8623
8624 // Check fastmath flags ('ninf').
8625 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
8626 return nullptr;
8627
8628 // Check the properties of the dividend. It must not be zero to avoid a
8629 // division by zero (see Proof).
8630 const APFloat *C;
8631 if (!match(V: LHSI->getOperand(i: 0), P: m_APFloat(Res&: C)))
8632 return nullptr;
8633
8634 if (C->isZero())
8635 return nullptr;
8636
8637 // Get swapped predicate if necessary.
8638 if (C->isNegative())
8639 Pred = I.getSwappedPredicate();
8640
8641 return new FCmpInst(Pred, LHSI->getOperand(i: 1), RHSC, "", &I);
8642}
8643
8644// Transform 'fptrunc(x) cmp C' to 'x cmp ext(C)' if possible.
8645// Patterns include:
8646// fptrunc(x) < C --> x < ext(C)
8647// fptrunc(x) <= C --> x <= ext(C)
8648// fptrunc(x) > C --> x > ext(C)
8649// fptrunc(x) >= C --> x >= ext(C)
8650// fptrunc(x) ord/uno C --> x ord/uno 0
8651// where 'ext(C)' is the extension of 'C' to the type of 'x' with a small bias
8652// due to precision loss.
8653static Instruction *foldFCmpFpTrunc(FCmpInst &I, const Instruction &FPTrunc,
8654 const Constant &C) {
8655 FCmpInst::Predicate Pred = I.getPredicate();
8656 Type *DestType = FPTrunc.getOperand(i: 0)->getType();
8657
8658 const APFloat *CValue;
8659 // TODO: support vec
8660 if (!match(V: &C, P: m_APFloat(Res&: CValue)))
8661 return nullptr;
8662
8663 // Handle ord/uno
8664 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) {
8665 assert(!CValue->isNaN() &&
8666 "X ord/uno NaN should be folded away by simplifyFCmpInst()");
8667 return new FCmpInst(Pred, FPTrunc.getOperand(i: 0),
8668 ConstantFP::getZero(Ty: DestType), "", &I);
8669 }
8670
8671 // Handle <, >, <=, >=
8672 bool RoundDown = false;
8673
8674 if (Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE ||
8675 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT)
8676 RoundDown = true;
8677 else if (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT ||
8678 Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)
8679 RoundDown = false;
8680 else
8681 return nullptr;
8682
8683 if (CValue->isNaN() || CValue->isInfinity())
8684 return nullptr;
8685
8686 auto ConvertFltSema = [](const APFloat &Src, const fltSemantics &Sema) {
8687 bool LosesInfo;
8688 APFloat Dest = Src;
8689 Dest.convert(ToSemantics: Sema, RM: APFloat::rmNearestTiesToEven, losesInfo: &LosesInfo);
8690 return Dest;
8691 };
8692
8693 auto NextValue = [](const APFloat &Value, bool RoundDown) {
8694 APFloat NextValue = Value;
8695 NextValue.next(nextDown: RoundDown);
8696 return NextValue;
8697 };
8698
8699 APFloat NextCValue = NextValue(*CValue, RoundDown);
8700
8701 const fltSemantics &DestFltSema =
8702 DestType->getScalarType()->getFltSemantics();
8703
8704 APFloat ExtCValue = ConvertFltSema(*CValue, DestFltSema);
8705 APFloat ExtNextCValue = ConvertFltSema(NextCValue, DestFltSema);
8706
8707 // When 'NextCValue' is infinity, use an imaged 'NextCValue' that equals
8708 // 'CValue + bias' to avoid the infinity after conversion. The bias is
8709 // estimated as 'CValue - PrevCValue', where 'PrevCValue' is the previous
8710 // value of 'CValue'.
8711 if (NextCValue.isInfinity()) {
8712 APFloat PrevCValue = NextValue(*CValue, !RoundDown);
8713 APFloat Bias = ConvertFltSema(*CValue - PrevCValue, DestFltSema);
8714
8715 ExtNextCValue = ExtCValue + Bias;
8716 }
8717
8718 APFloat ExtMidValue =
8719 scalbn(X: ExtCValue + ExtNextCValue, Exp: -1, RM: APFloat::rmNearestTiesToEven);
8720
8721 const fltSemantics &SrcFltSema =
8722 C.getType()->getScalarType()->getFltSemantics();
8723
8724 // 'MidValue' might be rounded to 'NextCValue'. Correct it here.
8725 APFloat MidValue = ConvertFltSema(ExtMidValue, SrcFltSema);
8726 if (MidValue != *CValue)
8727 ExtMidValue.next(nextDown: !RoundDown);
8728
8729 // Check whether 'ExtMidValue' is a valid result since the assumption on
8730 // imaged 'NextCValue' might not hold for new float types.
8731 // ppc_fp128 can't pass here when converting from max float because of
8732 // APFloat implementation.
8733 if (NextCValue.isInfinity()) {
8734 // ExtMidValue --- narrowed ---> Finite
8735 if (ConvertFltSema(ExtMidValue, SrcFltSema).isInfinity())
8736 return nullptr;
8737
8738 // NextExtMidValue --- narrowed ---> Infinity
8739 APFloat NextExtMidValue = NextValue(ExtMidValue, RoundDown);
8740 if (ConvertFltSema(NextExtMidValue, SrcFltSema).isFinite())
8741 return nullptr;
8742 }
8743
8744 return new FCmpInst(Pred, FPTrunc.getOperand(i: 0),
8745 ConstantFP::get(Ty: DestType, V: ExtMidValue), "", &I);
8746}
8747
8748/// Optimize fabs(X) compared with zero.
8749static Instruction *foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
8750 Value *X;
8751 if (!match(V: I.getOperand(i_nocapture: 0), P: m_FAbs(Op0: m_Value(V&: X))))
8752 return nullptr;
8753
8754 const APFloat *C;
8755 if (!match(V: I.getOperand(i_nocapture: 1), P: m_APFloat(Res&: C)))
8756 return nullptr;
8757
8758 if (!C->isPosZero()) {
8759 if (!C->isSmallestNormalized())
8760 return nullptr;
8761
8762 const Function *F = I.getFunction();
8763 DenormalMode Mode = F->getDenormalMode(FPType: C->getSemantics());
8764 if (Mode.Input == DenormalMode::PreserveSign ||
8765 Mode.Input == DenormalMode::PositiveZero) {
8766
8767 auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8768 Constant *Zero = ConstantFP::getZero(Ty: X->getType());
8769 return new FCmpInst(P, X, Zero, "", I);
8770 };
8771
8772 switch (I.getPredicate()) {
8773 case FCmpInst::FCMP_OLT:
8774 // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
8775 return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
8776 case FCmpInst::FCMP_UGE:
8777 // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
8778 return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
8779 case FCmpInst::FCMP_OGE:
8780 // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
8781 return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
8782 case FCmpInst::FCMP_ULT:
8783 // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
8784 return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
8785 default:
8786 break;
8787 }
8788 }
8789
8790 return nullptr;
8791 }
8792
8793 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8794 I->setPredicate(P);
8795 return IC.replaceOperand(I&: *I, OpNum: 0, V: X);
8796 };
8797
8798 switch (I.getPredicate()) {
8799 case FCmpInst::FCMP_UGE:
8800 case FCmpInst::FCMP_OLT:
8801 // fabs(X) >= 0.0 --> true
8802 // fabs(X) < 0.0 --> false
8803 llvm_unreachable("fcmp should have simplified");
8804
8805 case FCmpInst::FCMP_OGT:
8806 // fabs(X) > 0.0 --> X != 0.0
8807 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
8808
8809 case FCmpInst::FCMP_UGT:
8810 // fabs(X) u> 0.0 --> X u!= 0.0
8811 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
8812
8813 case FCmpInst::FCMP_OLE:
8814 // fabs(X) <= 0.0 --> X == 0.0
8815 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
8816
8817 case FCmpInst::FCMP_ULE:
8818 // fabs(X) u<= 0.0 --> X u== 0.0
8819 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
8820
8821 case FCmpInst::FCMP_OGE:
8822 // fabs(X) >= 0.0 --> !isnan(X)
8823 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8824 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
8825
8826 case FCmpInst::FCMP_ULT:
8827 // fabs(X) u< 0.0 --> isnan(X)
8828 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8829 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
8830
8831 case FCmpInst::FCMP_OEQ:
8832 case FCmpInst::FCMP_UEQ:
8833 case FCmpInst::FCMP_ONE:
8834 case FCmpInst::FCMP_UNE:
8835 case FCmpInst::FCMP_ORD:
8836 case FCmpInst::FCMP_UNO:
8837 // Look through the fabs() because it doesn't change anything but the sign.
8838 // fabs(X) == 0.0 --> X == 0.0,
8839 // fabs(X) != 0.0 --> X != 0.0
8840 // isnan(fabs(X)) --> isnan(X)
8841 // !isnan(fabs(X) --> !isnan(X)
8842 return replacePredAndOp0(&I, I.getPredicate(), X);
8843
8844 default:
8845 return nullptr;
8846 }
8847}
8848
8849/// Optimize sqrt(X) compared with zero.
8850static Instruction *foldSqrtWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
8851 Value *X;
8852 if (!match(V: I.getOperand(i_nocapture: 0), P: m_Sqrt(Op0: m_Value(V&: X))))
8853 return nullptr;
8854
8855 if (!match(V: I.getOperand(i_nocapture: 1), P: m_PosZeroFP()))
8856 return nullptr;
8857
8858 auto ReplacePredAndOp0 = [&](FCmpInst::Predicate P) {
8859 I.setPredicate(P);
8860 return IC.replaceOperand(I, OpNum: 0, V: X);
8861 };
8862
8863 // Clear ninf flag if sqrt doesn't have it.
8864 if (!cast<Instruction>(Val: I.getOperand(i_nocapture: 0))->hasNoInfs())
8865 I.setHasNoInfs(false);
8866
8867 switch (I.getPredicate()) {
8868 case FCmpInst::FCMP_OLT:
8869 case FCmpInst::FCMP_UGE:
8870 // sqrt(X) < 0.0 --> false
8871 // sqrt(X) u>= 0.0 --> true
8872 llvm_unreachable("fcmp should have simplified");
8873 case FCmpInst::FCMP_ULT:
8874 case FCmpInst::FCMP_ULE:
8875 case FCmpInst::FCMP_OGT:
8876 case FCmpInst::FCMP_OGE:
8877 case FCmpInst::FCMP_OEQ:
8878 case FCmpInst::FCMP_UNE:
8879 // sqrt(X) u< 0.0 --> X u< 0.0
8880 // sqrt(X) u<= 0.0 --> X u<= 0.0
8881 // sqrt(X) > 0.0 --> X > 0.0
8882 // sqrt(X) >= 0.0 --> X >= 0.0
8883 // sqrt(X) == 0.0 --> X == 0.0
8884 // sqrt(X) u!= 0.0 --> X u!= 0.0
8885 return IC.replaceOperand(I, OpNum: 0, V: X);
8886
8887 case FCmpInst::FCMP_OLE:
8888 // sqrt(X) <= 0.0 --> X == 0.0
8889 return ReplacePredAndOp0(FCmpInst::FCMP_OEQ);
8890 case FCmpInst::FCMP_UGT:
8891 // sqrt(X) u> 0.0 --> X u!= 0.0
8892 return ReplacePredAndOp0(FCmpInst::FCMP_UNE);
8893 case FCmpInst::FCMP_UEQ:
8894 // sqrt(X) u== 0.0 --> X u<= 0.0
8895 return ReplacePredAndOp0(FCmpInst::FCMP_ULE);
8896 case FCmpInst::FCMP_ONE:
8897 // sqrt(X) != 0.0 --> X > 0.0
8898 return ReplacePredAndOp0(FCmpInst::FCMP_OGT);
8899 case FCmpInst::FCMP_ORD:
8900 // !isnan(sqrt(X)) --> X >= 0.0
8901 return ReplacePredAndOp0(FCmpInst::FCMP_OGE);
8902 case FCmpInst::FCMP_UNO:
8903 // isnan(sqrt(X)) --> X u< 0.0
8904 return ReplacePredAndOp0(FCmpInst::FCMP_ULT);
8905 default:
8906 llvm_unreachable("Unexpected predicate!");
8907 }
8908}
8909
8910static Instruction *foldFCmpFNegCommonOp(FCmpInst &I) {
8911 CmpInst::Predicate Pred = I.getPredicate();
8912 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
8913
8914 // Canonicalize fneg as Op1.
8915 if (match(V: Op0, P: m_FNeg(X: m_Value())) && !match(V: Op1, P: m_FNeg(X: m_Value()))) {
8916 std::swap(a&: Op0, b&: Op1);
8917 Pred = I.getSwappedPredicate();
8918 }
8919
8920 if (!match(V: Op1, P: m_FNeg(X: m_Specific(V: Op0))))
8921 return nullptr;
8922
8923 // Replace the negated operand with 0.0:
8924 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
8925 Constant *Zero = ConstantFP::getZero(Ty: Op0->getType());
8926 return new FCmpInst(Pred, Op0, Zero, "", &I);
8927}
8928
8929static Instruction *foldFCmpFSubIntoFCmp(FCmpInst &I, Instruction *LHSI,
8930 Constant *RHSC, InstCombinerImpl &CI) {
8931 const CmpInst::Predicate Pred = I.getPredicate();
8932 Value *X = LHSI->getOperand(i: 0);
8933 Value *Y = LHSI->getOperand(i: 1);
8934 switch (Pred) {
8935 default:
8936 break;
8937 case FCmpInst::FCMP_UGT:
8938 case FCmpInst::FCMP_ULT:
8939 case FCmpInst::FCMP_UNE:
8940 case FCmpInst::FCMP_OEQ:
8941 case FCmpInst::FCMP_OGE:
8942 case FCmpInst::FCMP_OLE:
8943 // The optimization is not valid if X and Y are infinities of the same
8944 // sign, i.e. the inf - inf = nan case. If the fsub has the ninf or nnan
8945 // flag then we can assume we do not have that case. Otherwise we might be
8946 // able to prove that either X or Y is not infinity.
8947 if (!LHSI->hasNoNaNs() && !LHSI->hasNoInfs() &&
8948 !isKnownNeverInfinity(V: Y,
8949 SQ: CI.getSimplifyQuery().getWithInstruction(I: &I)) &&
8950 !isKnownNeverInfinity(V: X, SQ: CI.getSimplifyQuery().getWithInstruction(I: &I)))
8951 break;
8952
8953 [[fallthrough]];
8954 case FCmpInst::FCMP_OGT:
8955 case FCmpInst::FCMP_OLT:
8956 case FCmpInst::FCMP_ONE:
8957 case FCmpInst::FCMP_UEQ:
8958 case FCmpInst::FCMP_UGE:
8959 case FCmpInst::FCMP_ULE:
8960 // fcmp pred (x - y), 0 --> fcmp pred x, y
8961 if (match(V: RHSC, P: m_AnyZeroFP()) &&
8962 I.getFunction()->getDenormalMode(
8963 FPType: LHSI->getType()->getScalarType()->getFltSemantics()) ==
8964 DenormalMode::getIEEE()) {
8965 CI.replaceOperand(I, OpNum: 0, V: X);
8966 CI.replaceOperand(I, OpNum: 1, V: Y);
8967 I.setHasNoInfs(LHSI->hasNoInfs());
8968 if (LHSI->hasNoNaNs())
8969 I.setHasNoNaNs(true);
8970 return &I;
8971 }
8972 // fcmp `pred (C - Y), C` -> `fcmp swap(pred), Y, 0`
8973 // where C and Y can't be arbitrary floating-point values.
8974 // For example, with `C = 1.0f` and `Y = 0x1p-149`, `1.0f - Y` rounds back
8975 // to `1.0f`, so the source compare is false while the rewritten compare is
8976 // true.
8977 // We need to make sure (C - Y) never rounds back to C
8978 const APFloat *C;
8979 Value *IntSrc;
8980 if (match(V: RHSC, P: m_APFloat(Res&: C)) &&
8981 match(V: LHSI, P: m_FSub(L: m_Specific(V: RHSC), R: m_IToFP(Op: m_Value(V&: IntSrc)))) &&
8982 C->isNormal()) {
8983 // Requirements on C and Y:
8984 // 1. C is finite, nonzero, normal.
8985 // 2. C shouldn't be too large, that is, ULP(C) <= 1.
8986 // 3. Y must be the form of `[su]itofp`, so the finite nonzero result of Y
8987 // must be integer-valued with an absolute value of at least 1;
8988 // as long as the step size near C does not exceed 1,
8989 // C - Y cannot be rounded back to C when Y != 0.
8990 // 4. If Y = 0, `fcmp pred (C - 0), C` are equivalent to `fcmp swap(pred)
8991 // 0, 0` for ordered and unordered predicates as long as C is finite and
8992 // nonzero.
8993 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8994 if (MantissaWidth != -1 && ilogb(Arg: *C) < MantissaWidth) {
8995 Constant *ZeroC = ConstantFP::getZero(Ty: LHSI->getType());
8996 I.setPredicate(I.getSwappedPredicate());
8997 CI.replaceOperand(I, OpNum: 0, V: Y);
8998 CI.replaceOperand(I, OpNum: 1, V: ZeroC);
8999 return &I;
9000 }
9001 }
9002 break;
9003 }
9004
9005 return nullptr;
9006}
9007
9008/// Fold: fabs(uitofp(a) - uitofp(b)) pred C --> a == b
9009/// where 'pred' is olt, ult, ogt, ugt, oge or uge and C is a positive, Non-NaN
9010/// float when the uitofp casts are exact and C is in the valid range.
9011///
9012/// Since exact uitofp means distinct integers map to distinct floats, the only
9013/// values fabs(uitofp(a) - uitofp(b)) can take are {0.0, 1.0, 2.0, ...}.
9014/// There are no values in the open interval (0, 1), so:
9015/// fabs(...) < C where 0 < C <= 1.0 --> a == b (strict lt: C=1.0 ok)
9016// fabs(..) >= C where C >= 1.0 -> a != b
9017///
9018/// The same logic applies to sitofp.
9019static Instruction *foldFCmpFAbsFSubIntToFP(FCmpInst &I, InstCombinerImpl &IC) {
9020 Value *FAbsArg;
9021 if (!match(V: I.getOperand(i_nocapture: 0), P: m_FAbs(Op0: m_Value(V&: FAbsArg))))
9022 return nullptr;
9023
9024 const APFloat *C;
9025 if (!match(V: I.getOperand(i_nocapture: 1), P: PatternMatch::m_FiniteNonZero(V&: C)))
9026 return nullptr;
9027
9028 FCmpInst::Predicate Pred = I.getPredicate();
9029 bool IsStrictLt = Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT;
9030 bool IsLe = Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE;
9031 bool IsStrictGt = Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT;
9032 bool IsGe = Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
9033 if (!IsStrictLt && !IsStrictGt && !IsGe)
9034 return nullptr;
9035
9036 APFloat One = APFloat::getOne(Sem: C->getSemantics());
9037 APFloat::cmpResult Cmp = C->compare(RHS: One);
9038
9039 // For strict-lt (olt/ult): C must be in (0, 1.0] -- C == 1.0 is fine since
9040 // the next possible value after 0.0 is 1.0, and < 1.0 excludes it.
9041 if (IsStrictLt && Cmp == APFloat::cmpGreaterThan)
9042 return nullptr;
9043 if (IsGe && Cmp == APFloat::cmpGreaterThan)
9044 return nullptr;
9045 if (IsLe && Cmp != APFloat::cmpGreaterThan)
9046 return nullptr;
9047 if (IsStrictGt && Cmp != APFloat::cmpLessThan)
9048 return nullptr;
9049
9050 // Match: fsub(uitofp(A), uitofp(B)) where both casts are uitofp or sitofp
9051 Value *A, *B;
9052 bool IsSigned;
9053 if (match(V: FAbsArg, P: m_FSub(L: m_UIToFP(Op: m_Value(V&: A)), R: m_UIToFP(Op: m_Value(V&: B))))) {
9054 IsSigned = false;
9055 } else if (match(V: FAbsArg,
9056 P: m_FSub(L: m_SIToFP(Op: m_Value(V&: A)), R: m_SIToFP(Op: m_Value(V&: B))))) {
9057 IsSigned = true;
9058 } else {
9059 return nullptr;
9060 }
9061
9062 // A and B must have the same integer type
9063 if (A->getType() != B->getType())
9064 return nullptr;
9065
9066 Type *FPTy = FAbsArg->getType();
9067 if (!IC.canBeCastedExactlyIntToFP(V: A, FPTy, IsSigned, CxtI: &I) ||
9068 !IC.canBeCastedExactlyIntToFP(V: B, FPTy, IsSigned, CxtI: &I))
9069 return nullptr;
9070 ICmpInst::Predicate ResultPred =
9071 IsStrictLt || IsLe ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9072 return new ICmpInst(ResultPred, A, B);
9073}
9074
9075static Instruction *foldFCmpWithFloorAndCeil(FCmpInst &I,
9076 InstCombinerImpl &IC) {
9077 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
9078 Type *OpType = LHS->getType();
9079 CmpInst::Predicate Pred = I.getPredicate();
9080
9081 bool FloorX = match(V: LHS, P: m_Intrinsic<Intrinsic::floor>(Ops: m_Specific(V: RHS)));
9082 bool CeilX = match(V: LHS, P: m_Intrinsic<Intrinsic::ceil>(Ops: m_Specific(V: RHS)));
9083
9084 if (!FloorX && !CeilX) {
9085 if ((FloorX = match(V: RHS, P: m_Intrinsic<Intrinsic::floor>(Ops: m_Specific(V: LHS)))) ||
9086 (CeilX = match(V: RHS, P: m_Intrinsic<Intrinsic::ceil>(Ops: m_Specific(V: LHS))))) {
9087 std::swap(a&: LHS, b&: RHS);
9088 Pred = I.getSwappedPredicate();
9089 }
9090 }
9091
9092 if ((FloorX || CeilX) && FCmpInst::isCommutative(Pred) && LHS->hasOneUse()) {
9093 // fcmp pred floor(x), x => fcmp pred trunc(x), x
9094 // fcmp pred ceil(x), x => fcmp pred trunc(x), x
9095 // where pred is oeq, one, ord, ueq, une, uno.
9096 Value *TruncX = IC.Builder.CreateUnaryIntrinsic(ID: Intrinsic::trunc, Op: RHS);
9097 return new FCmpInst(Pred, TruncX, RHS, "", &I);
9098 }
9099
9100 switch (Pred) {
9101 case FCmpInst::FCMP_OLE:
9102 // fcmp ole floor(x), x => fcmp ord x, 0
9103 if (FloorX)
9104 return new FCmpInst(FCmpInst::FCMP_ORD, RHS, ConstantFP::getZero(Ty: OpType),
9105 "", &I);
9106 break;
9107 case FCmpInst::FCMP_OGT:
9108 // fcmp ogt floor(x), x => false
9109 if (FloorX)
9110 return IC.replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
9111 break;
9112 case FCmpInst::FCMP_OGE:
9113 // fcmp oge ceil(x), x => fcmp ord x, 0
9114 if (CeilX)
9115 return new FCmpInst(FCmpInst::FCMP_ORD, RHS, ConstantFP::getZero(Ty: OpType),
9116 "", &I);
9117 break;
9118 case FCmpInst::FCMP_OLT:
9119 // fcmp olt ceil(x), x => false
9120 if (CeilX)
9121 return IC.replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
9122 break;
9123 case FCmpInst::FCMP_ULE:
9124 // fcmp ule floor(x), x => true
9125 if (FloorX)
9126 return IC.replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
9127 break;
9128 case FCmpInst::FCMP_UGT:
9129 // fcmp ugt floor(x), x => fcmp uno x, 0
9130 if (FloorX)
9131 return new FCmpInst(FCmpInst::FCMP_UNO, RHS, ConstantFP::getZero(Ty: OpType),
9132 "", &I);
9133 break;
9134 case FCmpInst::FCMP_UGE:
9135 // fcmp uge ceil(x), x => true
9136 if (CeilX)
9137 return IC.replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
9138 break;
9139 case FCmpInst::FCMP_ULT:
9140 // fcmp ult ceil(x), x => fcmp uno x, 0
9141 if (CeilX)
9142 return new FCmpInst(FCmpInst::FCMP_UNO, RHS, ConstantFP::getZero(Ty: OpType),
9143 "", &I);
9144 break;
9145 default:
9146 break;
9147 }
9148
9149 return nullptr;
9150}
9151
9152/// Returns true if a select that implements a min/max is redundant and
9153/// select result can be replaced with its non-constant operand, e.g.,
9154/// select ( (si/ui-to-fp A) <= C ), C, (si/ui-to-fp A)
9155/// where C is the FP constant equal to the minimum integer value
9156/// representable by A.
9157static bool isMinMaxCmpSelectEliminable(SelectPatternFlavor Flavor, Value *A,
9158 Value *B) {
9159 const APFloat *APF;
9160 if (!match(V: B, P: m_APFloat(Res&: APF)))
9161 return false;
9162
9163 auto *I = dyn_cast<Instruction>(Val: A);
9164 if (!I || !(I->getOpcode() == Instruction::SIToFP ||
9165 I->getOpcode() == Instruction::UIToFP))
9166 return false;
9167
9168 bool IsUnsigned = I->getOpcode() == Instruction::UIToFP;
9169 unsigned BitWidth = I->getOperand(i: 0)->getType()->getScalarSizeInBits();
9170 APSInt IntBoundary = (Flavor == SPF_FMAXNUM)
9171 ? APSInt::getMinValue(numBits: BitWidth, Unsigned: IsUnsigned)
9172 : APSInt::getMaxValue(numBits: BitWidth, Unsigned: IsUnsigned);
9173 APSInt ConvertedInt(BitWidth, IsUnsigned);
9174 bool IsExact;
9175 APFloat::opStatus Status =
9176 APF->convertToInteger(Result&: ConvertedInt, RM: APFloat::rmTowardZero, IsExact: &IsExact);
9177 return Status == APFloat::opOK && IsExact && ConvertedInt == IntBoundary;
9178}
9179
9180Instruction *InstCombinerImpl::visitFCmpInst(FCmpInst &I) {
9181 bool Changed = false;
9182
9183 /// Orders the operands of the compare so that they are listed from most
9184 /// complex to least complex. This puts constants before unary operators,
9185 /// before binary operators.
9186 if (getComplexity(V: I.getOperand(i_nocapture: 0)) < getComplexity(V: I.getOperand(i_nocapture: 1))) {
9187 I.swapOperands();
9188 Changed = true;
9189 }
9190
9191 const CmpInst::Predicate Pred = I.getPredicate();
9192 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
9193 if (Value *V = simplifyFCmpInst(Predicate: Pred, LHS: Op0, RHS: Op1, FMF: I.getFastMathFlags(),
9194 Q: SQ.getWithInstruction(I: &I)))
9195 return replaceInstUsesWith(I, V);
9196
9197 // Simplify 'fcmp pred X, X'
9198 Type *OpType = Op0->getType();
9199 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
9200 if (Op0 == Op1) {
9201 switch (Pred) {
9202 default:
9203 break;
9204 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
9205 case FCmpInst::FCMP_ULT: // True if unordered or less than
9206 case FCmpInst::FCMP_UGT: // True if unordered or greater than
9207 case FCmpInst::FCMP_UNE: // True if unordered or not equal
9208 // Canonicalize these to be 'fcmp uno %X, 0.0'.
9209 I.setPredicate(FCmpInst::FCMP_UNO);
9210 I.setOperand(i_nocapture: 1, Val_nocapture: Constant::getNullValue(Ty: OpType));
9211 return &I;
9212
9213 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
9214 case FCmpInst::FCMP_OEQ: // True if ordered and equal
9215 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
9216 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
9217 // Canonicalize these to be 'fcmp ord %X, 0.0'.
9218 I.setPredicate(FCmpInst::FCMP_ORD);
9219 I.setOperand(i_nocapture: 1, Val_nocapture: Constant::getNullValue(Ty: OpType));
9220 return &I;
9221 }
9222 }
9223
9224 if (I.isCommutative()) {
9225 if (auto Pair = matchSymmetricPair(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1))) {
9226 replaceOperand(I, OpNum: 0, V: Pair->first);
9227 replaceOperand(I, OpNum: 1, V: Pair->second);
9228 return &I;
9229 }
9230 }
9231
9232 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
9233 // then canonicalize the operand to 0.0.
9234 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
9235 if (!match(V: Op0, P: m_PosZeroFP()) &&
9236 isKnownNeverNaN(V: Op0, SQ: getSimplifyQuery().getWithInstruction(I: &I)))
9237 return replaceOperand(I, OpNum: 0, V: ConstantFP::getZero(Ty: OpType));
9238
9239 if (!match(V: Op1, P: m_PosZeroFP()) &&
9240 isKnownNeverNaN(V: Op1, SQ: getSimplifyQuery().getWithInstruction(I: &I)))
9241 return replaceOperand(I, OpNum: 1, V: ConstantFP::getZero(Ty: OpType));
9242 }
9243
9244 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
9245 Value *X, *Y;
9246 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: X))) && match(V: Op1, P: m_FNeg(X: m_Value(V&: Y))))
9247 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
9248
9249 if (Instruction *R = foldFCmpFNegCommonOp(I))
9250 return R;
9251
9252 // Test if the FCmpInst instruction is used exclusively by a select as
9253 // part of a minimum or maximum operation. If so, refrain from doing
9254 // any other folding. This helps out other analyses which understand
9255 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
9256 // and CodeGen. And in this case, at least one of the comparison
9257 // operands has at least one user besides the compare (the select),
9258 // which would often largely negate the benefit of folding anyway.
9259 if (I.hasOneUse())
9260 if (SelectInst *SI = dyn_cast<SelectInst>(Val: I.user_back())) {
9261 Value *A, *B;
9262 SelectPatternResult SPR = matchSelectPattern(V: SI, LHS&: A, RHS&: B);
9263 bool IsRedundantMinMaxClamp =
9264 (SPR.Flavor == SPF_FMAXNUM || SPR.Flavor == SPF_FMINNUM) &&
9265 isMinMaxCmpSelectEliminable(Flavor: SPR.Flavor, A, B);
9266 if (SPR.Flavor != SPF_UNKNOWN && !IsRedundantMinMaxClamp)
9267 return nullptr;
9268 }
9269
9270 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
9271 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
9272 if (match(V: Op1, P: m_AnyZeroFP()) && !match(V: Op1, P: m_PosZeroFP()))
9273 return replaceOperand(I, OpNum: 1, V: ConstantFP::getZero(Ty: OpType));
9274
9275 // Canonicalize:
9276 // fcmp olt X, +inf -> fcmp one X, +inf
9277 // fcmp ole X, +inf -> fcmp ord X, 0
9278 // fcmp ogt X, +inf -> false
9279 // fcmp oge X, +inf -> fcmp oeq X, +inf
9280 // fcmp ult X, +inf -> fcmp une X, +inf
9281 // fcmp ule X, +inf -> true
9282 // fcmp ugt X, +inf -> fcmp uno X, 0
9283 // fcmp uge X, +inf -> fcmp ueq X, +inf
9284 // fcmp olt X, -inf -> false
9285 // fcmp ole X, -inf -> fcmp oeq X, -inf
9286 // fcmp ogt X, -inf -> fcmp one X, -inf
9287 // fcmp oge X, -inf -> fcmp ord X, 0
9288 // fcmp ult X, -inf -> fcmp uno X, 0
9289 // fcmp ule X, -inf -> fcmp ueq X, -inf
9290 // fcmp ugt X, -inf -> fcmp une X, -inf
9291 // fcmp uge X, -inf -> true
9292 const APFloat *C;
9293 if (match(V: Op1, P: m_APFloat(Res&: C)) && C->isInfinity()) {
9294 switch (C->isNegative() ? FCmpInst::getSwappedPredicate(pred: Pred) : Pred) {
9295 default:
9296 break;
9297 case FCmpInst::FCMP_ORD:
9298 case FCmpInst::FCMP_UNO:
9299 case FCmpInst::FCMP_TRUE:
9300 case FCmpInst::FCMP_FALSE:
9301 case FCmpInst::FCMP_OGT:
9302 case FCmpInst::FCMP_ULE:
9303 llvm_unreachable("Should be simplified by InstSimplify");
9304 case FCmpInst::FCMP_OLT:
9305 return new FCmpInst(FCmpInst::FCMP_ONE, Op0, Op1, "", &I);
9306 case FCmpInst::FCMP_OLE:
9307 return new FCmpInst(FCmpInst::FCMP_ORD, Op0, ConstantFP::getZero(Ty: OpType),
9308 "", &I);
9309 case FCmpInst::FCMP_OGE:
9310 return new FCmpInst(FCmpInst::FCMP_OEQ, Op0, Op1, "", &I);
9311 case FCmpInst::FCMP_ULT:
9312 return new FCmpInst(FCmpInst::FCMP_UNE, Op0, Op1, "", &I);
9313 case FCmpInst::FCMP_UGT:
9314 return new FCmpInst(FCmpInst::FCMP_UNO, Op0, ConstantFP::getZero(Ty: OpType),
9315 "", &I);
9316 case FCmpInst::FCMP_UGE:
9317 return new FCmpInst(FCmpInst::FCMP_UEQ, Op0, Op1, "", &I);
9318 }
9319 }
9320
9321 // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
9322 // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
9323 if (match(V: Op1, P: m_PosZeroFP()) &&
9324 match(V: Op0, P: m_OneUse(SubPattern: m_ElementWiseBitCast(Op: m_Value(V&: X)))) &&
9325 X->getType()->isIntOrIntVectorTy() &&
9326 !F.getDenormalMode(FPType: Op1->getType()->getScalarType()->getFltSemantics())
9327 .inputsMayBeZero()) {
9328 ICmpInst::Predicate IntPred = ICmpInst::BAD_ICMP_PREDICATE;
9329 if (Pred == FCmpInst::FCMP_OEQ)
9330 IntPred = ICmpInst::ICMP_EQ;
9331 else if (Pred == FCmpInst::FCMP_UNE)
9332 IntPred = ICmpInst::ICMP_NE;
9333
9334 if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
9335 Type *IntTy = X->getType();
9336 const APInt &SignMask = ~APInt::getSignMask(BitWidth: IntTy->getScalarSizeInBits());
9337 Value *MaskX = Builder.CreateAnd(LHS: X, RHS: ConstantInt::get(Ty: IntTy, V: SignMask));
9338 return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(Ty: IntTy));
9339 }
9340 }
9341
9342 // Handle fcmp with instruction LHS and constant RHS.
9343 Instruction *LHSI;
9344 Constant *RHSC;
9345 if (match(V: Op0, P: m_Instruction(I&: LHSI)) && match(V: Op1, P: m_Constant(C&: RHSC))) {
9346 switch (LHSI->getOpcode()) {
9347 case Instruction::Select:
9348 // fcmp eq (cond ? x : -x), 0 --> fcmp eq x, 0
9349 if (FCmpInst::isEquality(Pred) && match(V: RHSC, P: m_AnyZeroFP()) &&
9350 match(V: LHSI, P: m_c_Select(L: m_FNeg(X: m_Value(V&: X)), R: m_Deferred(V: X))))
9351 return replaceOperand(I, OpNum: 0, V: X);
9352 if (Instruction *NV = FoldOpIntoSelect(Op&: I, SI: cast<SelectInst>(Val: LHSI)))
9353 return NV;
9354 break;
9355 case Instruction::FSub:
9356 if (LHSI->hasOneUse())
9357 if (Instruction *NV = foldFCmpFSubIntoFCmp(I, LHSI, RHSC, CI&: *this))
9358 return NV;
9359 break;
9360 case Instruction::PHI:
9361 if (Instruction *NV = foldOpIntoPhi(I, PN: cast<PHINode>(Val: LHSI)))
9362 return NV;
9363 break;
9364 case Instruction::SIToFP:
9365 case Instruction::UIToFP:
9366 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
9367 return NV;
9368 break;
9369 case Instruction::FDiv:
9370 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
9371 return NV;
9372 break;
9373 case Instruction::Load:
9374 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: LHSI->getOperand(i: 0)))
9375 if (Instruction *Res =
9376 foldCmpLoadFromIndexedGlobal(LI: cast<LoadInst>(Val: LHSI), GEP, ICI&: I))
9377 return Res;
9378 break;
9379 case Instruction::FPTrunc:
9380 if (Instruction *NV = foldFCmpFpTrunc(I, FPTrunc: *LHSI, C: *RHSC))
9381 return NV;
9382 break;
9383 }
9384 }
9385
9386 if (Instruction *R = foldFabsWithFcmpZero(I, IC&: *this))
9387 return R;
9388
9389 if (Instruction *R = foldFCmpFAbsFSubIntToFP(I, IC&: *this))
9390 return R;
9391
9392 if (Instruction *R = foldSqrtWithFcmpZero(I, IC&: *this))
9393 return R;
9394
9395 if (Instruction *R = foldFCmpWithFloorAndCeil(I, IC&: *this))
9396 return R;
9397
9398 if (Instruction *R = foldCmpSelectOfConstants(I))
9399 return R;
9400
9401 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: X)))) {
9402 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
9403 Constant *C;
9404 if (match(V: Op1, P: m_Constant(C)))
9405 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL))
9406 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
9407 }
9408
9409 // fcmp (fadd X, 0.0), Y --> fcmp X, Y
9410 if (match(V: Op0, P: m_FAdd(L: m_Value(V&: X), R: m_AnyZeroFP())))
9411 return new FCmpInst(Pred, X, Op1, "", &I);
9412
9413 // fcmp X, (fadd Y, 0.0) --> fcmp X, Y
9414 if (match(V: Op1, P: m_FAdd(L: m_Value(V&: Y), R: m_AnyZeroFP())))
9415 return new FCmpInst(Pred, Op0, Y, "", &I);
9416
9417 // fcmp ord/uno (fptrunc X), (fptrunc Y) -> fcmp ord/uno X, Y
9418 if ((Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) &&
9419 match(V: Op0, P: m_FPTrunc(Op: m_Value(V&: X))) && match(V: Op1, P: m_FPTrunc(Op: m_Value(V&: Y))) &&
9420 X->getType() == Y->getType())
9421 return new FCmpInst(Pred, X, Y, "", &I);
9422
9423 if (match(V: Op0, P: m_FPExt(Op: m_Value(V&: X)))) {
9424 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
9425 if (match(V: Op1, P: m_FPExt(Op: m_Value(V&: Y))) && X->getType() == Y->getType())
9426 return new FCmpInst(Pred, X, Y, "", &I);
9427
9428 const APFloat *C;
9429 if (match(V: Op1, P: m_APFloat(Res&: C))) {
9430 const fltSemantics &FPSem =
9431 X->getType()->getScalarType()->getFltSemantics();
9432 bool Lossy;
9433 APFloat TruncC = *C;
9434 TruncC.convert(ToSemantics: FPSem, RM: APFloat::rmNearestTiesToEven, losesInfo: &Lossy);
9435
9436 if (Lossy) {
9437 // X can't possibly equal the higher-precision constant, so reduce any
9438 // equality comparison.
9439 // TODO: Other predicates can be handled via getFCmpCode().
9440 switch (Pred) {
9441 case FCmpInst::FCMP_OEQ:
9442 // X is ordered and equal to an impossible constant --> false
9443 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
9444 case FCmpInst::FCMP_ONE:
9445 // X is ordered and not equal to an impossible constant --> ordered
9446 return new FCmpInst(FCmpInst::FCMP_ORD, X,
9447 ConstantFP::getZero(Ty: X->getType()));
9448 case FCmpInst::FCMP_UEQ:
9449 // X is unordered or equal to an impossible constant --> unordered
9450 return new FCmpInst(FCmpInst::FCMP_UNO, X,
9451 ConstantFP::getZero(Ty: X->getType()));
9452 case FCmpInst::FCMP_UNE:
9453 // X is unordered or not equal to an impossible constant --> true
9454 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
9455 default:
9456 break;
9457 }
9458 }
9459
9460 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
9461 // Avoid lossy conversions and denormals.
9462 // Zero is a special case that's OK to convert.
9463 APFloat Fabs = TruncC;
9464 Fabs.clearSign();
9465 if (!Lossy &&
9466 (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(Sem: FPSem)))) {
9467 Constant *NewC = ConstantFP::get(Ty: X->getType(), V: TruncC);
9468 return new FCmpInst(Pred, X, NewC, "", &I);
9469 }
9470 }
9471 }
9472
9473 // Convert a sign-bit test of an FP value into a cast and integer compare.
9474 // TODO: Simplify if the copysign constant is 0.0 or NaN.
9475 // TODO: Handle non-zero compare constants.
9476 // TODO: Handle other predicates.
9477 if (match(V: Op0, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::copysign>(Ops: m_APFloat(Res&: C),
9478 Ops: m_Value(V&: X)))) &&
9479 match(V: Op1, P: m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
9480 Type *IntType = Builder.getIntNTy(N: X->getType()->getScalarSizeInBits());
9481 if (auto *VecTy = dyn_cast<VectorType>(Val: OpType))
9482 IntType = VectorType::get(ElementType: IntType, EC: VecTy->getElementCount());
9483
9484 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
9485 if (Pred == FCmpInst::FCMP_OLT) {
9486 Value *IntX = Builder.CreateBitCast(V: X, DestTy: IntType);
9487 return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
9488 ConstantInt::getNullValue(Ty: IntType));
9489 }
9490 }
9491
9492 {
9493 Value *CanonLHS = nullptr;
9494 match(V: Op0, P: m_Intrinsic<Intrinsic::canonicalize>(Ops: m_Value(V&: CanonLHS)));
9495 // (canonicalize(x) == x) => (x == x)
9496 if (CanonLHS == Op1)
9497 return new FCmpInst(Pred, Op1, Op1, "", &I);
9498
9499 Value *CanonRHS = nullptr;
9500 match(V: Op1, P: m_Intrinsic<Intrinsic::canonicalize>(Ops: m_Value(V&: CanonRHS)));
9501 // (x == canonicalize(x)) => (x == x)
9502 if (CanonRHS == Op0)
9503 return new FCmpInst(Pred, Op0, Op0, "", &I);
9504
9505 // (canonicalize(x) == canonicalize(y)) => (x == y)
9506 if (CanonLHS && CanonRHS)
9507 return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
9508 }
9509
9510 if (I.getType()->isVectorTy())
9511 if (Instruction *Res = foldVectorCmp(Cmp&: I, Builder))
9512 return Res;
9513
9514 return Changed ? &I : nullptr;
9515}
9516