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/APInt.h"
16#include "llvm/ADT/APSInt.h"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/Analysis/CaptureTracking.h"
20#include "llvm/Analysis/CmpInstAnalysis.h"
21#include "llvm/Analysis/ConstantFolding.h"
22#include "llvm/Analysis/InstructionSimplify.h"
23#include "llvm/Analysis/Loads.h"
24#include "llvm/Analysis/Utils/Local.h"
25#include "llvm/Analysis/VectorUtils.h"
26#include "llvm/IR/ConstantRange.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/InstrTypes.h"
30#include "llvm/IR/Instruction.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/IntrinsicInst.h"
33#include "llvm/IR/PatternMatch.h"
34#include "llvm/Support/KnownBits.h"
35#include "llvm/Transforms/InstCombine/InstCombiner.h"
36#include <bitset>
37
38using namespace llvm;
39using namespace PatternMatch;
40
41#define DEBUG_TYPE "instcombine"
42
43// How many times is a select replaced by one of its operands?
44STATISTIC(NumSel, "Number of select opts");
45
46/// Compute Result = In1+In2, returning true if the result overflowed for this
47/// type.
48static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
49 bool IsSigned = false) {
50 bool Overflow;
51 if (IsSigned)
52 Result = In1.sadd_ov(RHS: In2, Overflow);
53 else
54 Result = In1.uadd_ov(RHS: In2, Overflow);
55
56 return Overflow;
57}
58
59/// Compute Result = In1-In2, returning true if the result overflowed for this
60/// type.
61static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
62 bool IsSigned = false) {
63 bool Overflow;
64 if (IsSigned)
65 Result = In1.ssub_ov(RHS: In2, Overflow);
66 else
67 Result = In1.usub_ov(RHS: In2, Overflow);
68
69 return Overflow;
70}
71
72/// Given an icmp instruction, return true if any use of this comparison is a
73/// branch on sign bit comparison.
74static bool hasBranchUse(ICmpInst &I) {
75 for (auto *U : I.users())
76 if (isa<CondBrInst>(Val: U))
77 return true;
78 return false;
79}
80
81/// Returns true if the exploded icmp can be expressed as a signed comparison
82/// to zero and updates the predicate accordingly.
83/// The signedness of the comparison is preserved.
84/// TODO: Refactor with decomposeBitTestICmp()?
85static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
86 if (!ICmpInst::isSigned(Pred))
87 return false;
88
89 if (C.isZero())
90 return ICmpInst::isRelational(P: Pred);
91
92 if (C.isOne()) {
93 if (Pred == ICmpInst::ICMP_SLT) {
94 Pred = ICmpInst::ICMP_SLE;
95 return true;
96 }
97 } else if (C.isAllOnes()) {
98 if (Pred == ICmpInst::ICMP_SGT) {
99 Pred = ICmpInst::ICMP_SGE;
100 return true;
101 }
102 }
103
104 return false;
105}
106
107/// This is called when we see this pattern:
108/// cmp pred (load (gep GV, ...)), cmpcst
109/// where GV is a global variable with a constant initializer. Try to simplify
110/// this into some simple computation that does not need the load. For example
111/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
112///
113/// If AndCst is non-null, then the loaded value is masked with that constant
114/// before doing the comparison. This handles cases like "A[i]&4 == 0".
115///
116/// We allow multi-use cases in this fold, even though it can increase
117/// instruction count, because it appears to be mostly beneficial in practice.
118/// Even if there are multiple uses, they can often be sunk into the block
119/// guarded by the icmp.
120Instruction *InstCombinerImpl::foldCmpLoadFromIndexedGlobal(
121 LoadInst *LI, GetElementPtrInst *GEP, CmpInst &ICI, ConstantInt *AndCst) {
122 auto *GV = dyn_cast<GlobalVariable>(Val: getUnderlyingObject(V: GEP));
123 if (LI->isVolatile() || !GV || !GV->isConstant() ||
124 !GV->hasDefinitiveInitializer())
125 return nullptr;
126
127 Type *EltTy = LI->getType();
128 TypeSize EltSize = DL.getTypeStoreSize(Ty: EltTy);
129 if (EltSize.isScalable())
130 return nullptr;
131
132 LinearExpression Expr = decomposeLinearExpression(DL, Ptr: GEP);
133 if (!Expr.Index || Expr.BasePtr != GV || Expr.Offset.getBitWidth() > 64)
134 return nullptr;
135
136 Constant *Init = GV->getInitializer();
137 TypeSize GlobalSize = DL.getTypeAllocSize(Ty: Init->getType());
138
139 Value *Idx = Expr.Index;
140 const APInt &Stride = Expr.Scale;
141 const APInt &ConstOffset = Expr.Offset;
142
143 // Allow an additional context offset, but only within the stride.
144 if (!ConstOffset.ult(RHS: Stride))
145 return nullptr;
146
147 // Don't handle overlapping loads for now.
148 if (!Stride.uge(RHS: EltSize.getFixedValue()))
149 return nullptr;
150
151 // Don't blow up on huge arrays.
152 uint64_t ArrayElementCount =
153 divideCeil(Numerator: (GlobalSize.getFixedValue() - ConstOffset.getZExtValue()),
154 Denominator: Stride.getZExtValue());
155 if (ArrayElementCount > CLOpts.maxarray_size)
156 return nullptr;
157
158 enum { Overdefined = -3, Undefined = -2 };
159
160 // Variables for our state machines.
161
162 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
163 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
164 // and 87 is the second (and last) index. FirstTrueElement is -2 when
165 // undefined, otherwise set to the first true element. SecondTrueElement is
166 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
167 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
168
169 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
170 // form "i != 47 & i != 87". Same state transitions as for true elements.
171 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
172
173 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
174 /// define a state machine that triggers for ranges of values that the index
175 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
176 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
177 /// index in the range (inclusive). We use -2 for undefined here because we
178 /// use relative comparisons and don't want 0-1 to match -1.
179 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
180
181 // MagicBitvector - This is a magic bitvector where we set a bit if the
182 // comparison is true for element 'i'. If there are 64 elements or less in
183 // the array, this will fully represent all the comparison results.
184 uint64_t MagicBitvector = 0;
185
186 // Scan the array and see if one of our patterns matches.
187 Constant *CompareRHS = cast<Constant>(Val: ICI.getOperand(i_nocapture: 1));
188 APInt Offset = ConstOffset;
189 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i, Offset += Stride) {
190 Constant *Elt = ConstantFoldLoadFromConst(C: Init, Ty: EltTy, Offset, DL);
191 if (!Elt)
192 return nullptr;
193
194 // If the element is masked, handle it.
195 if (AndCst) {
196 Elt = ConstantFoldBinaryOpOperands(Opcode: Instruction::And, LHS: Elt, RHS: AndCst, DL);
197 if (!Elt)
198 return nullptr;
199 }
200
201 // Find out if the comparison would be true or false for the i'th element.
202 Constant *C = ConstantFoldCompareInstOperands(Predicate: ICI.getPredicate(), LHS: Elt,
203 RHS: CompareRHS, DL, TLI: &TLI);
204 if (!C)
205 return nullptr;
206
207 // If the result is undef for this element, ignore it.
208 if (isa<UndefValue>(Val: C)) {
209 // Extend range state machines to cover this element in case there is an
210 // undef in the middle of the range.
211 if (TrueRangeEnd == (int)i - 1)
212 TrueRangeEnd = i;
213 if (FalseRangeEnd == (int)i - 1)
214 FalseRangeEnd = i;
215 continue;
216 }
217
218 // If we can't compute the result for any of the elements, we have to give
219 // up evaluating the entire conditional.
220 if (!isa<ConstantInt>(Val: C))
221 return nullptr;
222
223 // Otherwise, we know if the comparison is true or false for this element,
224 // update our state machines.
225 bool IsTrueForElt = !cast<ConstantInt>(Val: C)->isZero();
226
227 // State machine for single/double/range index comparison.
228 if (IsTrueForElt) {
229 // Update the TrueElement state machine.
230 if (FirstTrueElement == Undefined)
231 FirstTrueElement = TrueRangeEnd = i; // First true element.
232 else {
233 // Update double-compare state machine.
234 if (SecondTrueElement == Undefined)
235 SecondTrueElement = i;
236 else
237 SecondTrueElement = Overdefined;
238
239 // Update range state machine.
240 if (TrueRangeEnd == (int)i - 1)
241 TrueRangeEnd = i;
242 else
243 TrueRangeEnd = Overdefined;
244 }
245 } else {
246 // Update the FalseElement state machine.
247 if (FirstFalseElement == Undefined)
248 FirstFalseElement = FalseRangeEnd = i; // First false element.
249 else {
250 // Update double-compare state machine.
251 if (SecondFalseElement == Undefined)
252 SecondFalseElement = i;
253 else
254 SecondFalseElement = Overdefined;
255
256 // Update range state machine.
257 if (FalseRangeEnd == (int)i - 1)
258 FalseRangeEnd = i;
259 else
260 FalseRangeEnd = Overdefined;
261 }
262 }
263
264 // If this element is in range, update our magic bitvector.
265 if (i < 64 && IsTrueForElt)
266 MagicBitvector |= 1ULL << i;
267
268 // If all of our states become overdefined, bail out early. Since the
269 // predicate is expensive, only check it every 8 elements. This is only
270 // really useful for really huge arrays.
271 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
272 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
273 FalseRangeEnd == Overdefined)
274 return nullptr;
275 }
276
277 // Now that we've scanned the entire array, emit our new comparison(s). We
278 // order the state machines in complexity of the generated code.
279
280 // If inbounds keyword is not present, Idx * Stride can overflow.
281 // Let's assume that Stride is 2 and the wanted value is at offset 0.
282 // Then, there are two possible values for Idx to match offset 0:
283 // 0x00..00, 0x80..00.
284 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
285 // comparison is false if Idx was 0x80..00.
286 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
287 auto MaskIdx = [&](Value *Idx) {
288 if (!Expr.Flags.isInBounds() && Stride.countr_zero() != 0) {
289 Value *Mask = Constant::getAllOnesValue(Ty: Idx->getType());
290 Mask = Builder.CreateLShr(LHS: Mask, RHS: Stride.countr_zero());
291 Idx = Builder.CreateAnd(LHS: Idx, RHS: Mask);
292 }
293 return Idx;
294 };
295
296 // If the comparison is only true for one or two elements, emit direct
297 // comparisons.
298 if (SecondTrueElement != Overdefined) {
299 Idx = MaskIdx(Idx);
300 // None true -> false.
301 if (FirstTrueElement == Undefined)
302 return replaceInstUsesWith(I&: ICI, V: Builder.getFalse());
303
304 Value *FirstTrueIdx = ConstantInt::get(Ty: Idx->getType(), V: FirstTrueElement);
305
306 // True for one element -> 'i == 47'.
307 if (SecondTrueElement == Undefined)
308 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
309
310 // True for two elements -> 'i == 47 | i == 72'.
311 Value *C1 = Builder.CreateICmpEQ(LHS: Idx, RHS: FirstTrueIdx);
312 Value *SecondTrueIdx = ConstantInt::get(Ty: Idx->getType(), V: SecondTrueElement);
313 Value *C2 = Builder.CreateICmpEQ(LHS: Idx, RHS: SecondTrueIdx);
314 return BinaryOperator::CreateOr(V1: C1, V2: C2);
315 }
316
317 // If the comparison is only false for one or two elements, emit direct
318 // comparisons.
319 if (SecondFalseElement != Overdefined) {
320 Idx = MaskIdx(Idx);
321 // None false -> true.
322 if (FirstFalseElement == Undefined)
323 return replaceInstUsesWith(I&: ICI, V: Builder.getTrue());
324
325 Value *FirstFalseIdx = ConstantInt::get(Ty: Idx->getType(), V: FirstFalseElement);
326
327 // False for one element -> 'i != 47'.
328 if (SecondFalseElement == Undefined)
329 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
330
331 // False for two elements -> 'i != 47 & i != 72'.
332 Value *C1 = Builder.CreateICmpNE(LHS: Idx, RHS: FirstFalseIdx);
333 Value *SecondFalseIdx =
334 ConstantInt::get(Ty: Idx->getType(), V: SecondFalseElement);
335 Value *C2 = Builder.CreateICmpNE(LHS: Idx, RHS: SecondFalseIdx);
336 return BinaryOperator::CreateAnd(V1: C1, V2: C2);
337 }
338
339 // If the comparison can be replaced with a range comparison for the elements
340 // where it is true, emit the range check.
341 if (TrueRangeEnd != Overdefined) {
342 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
343 Idx = MaskIdx(Idx);
344
345 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
346 if (FirstTrueElement) {
347 Value *Offs = ConstantInt::getSigned(Ty: Idx->getType(), V: -FirstTrueElement);
348 Idx = Builder.CreateAdd(LHS: Idx, RHS: Offs);
349 }
350
351 Value *End =
352 ConstantInt::get(Ty: Idx->getType(), V: TrueRangeEnd - FirstTrueElement + 1);
353 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
354 }
355
356 // False range check.
357 if (FalseRangeEnd != Overdefined) {
358 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
359 Idx = MaskIdx(Idx);
360 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
361 if (FirstFalseElement) {
362 Value *Offs = ConstantInt::getSigned(Ty: Idx->getType(), V: -FirstFalseElement);
363 Idx = Builder.CreateAdd(LHS: Idx, RHS: Offs);
364 }
365
366 Value *End =
367 ConstantInt::get(Ty: Idx->getType(), V: FalseRangeEnd - FirstFalseElement);
368 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
369 }
370
371 // If a magic bitvector captures the entire comparison state
372 // of this load, replace it with computation that does:
373 // ((magic_cst >> i) & 1) != 0
374 {
375 Type *Ty = nullptr;
376
377 // Look for an appropriate type:
378 // - The type of Idx if the magic fits
379 // - The smallest fitting legal type
380 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
381 Ty = Idx->getType();
382 else
383 Ty = DL.getSmallestLegalIntType(C&: Init->getContext(), Width: ArrayElementCount);
384
385 if (Ty) {
386 Idx = MaskIdx(Idx);
387 Value *V = Builder.CreateIntCast(V: Idx, DestTy: Ty, isSigned: false);
388 V = Builder.CreateLShr(LHS: ConstantInt::get(Ty, V: MagicBitvector), RHS: V);
389 V = Builder.CreateAnd(LHS: ConstantInt::get(Ty, V: 1), RHS: V);
390 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, V: 0));
391 }
392 }
393
394 return nullptr;
395}
396
397/// Returns true if we can rewrite Start as a GEP with pointer Base
398/// and some integer offset. The nodes that need to be re-written
399/// for this transformation will be added to Explored.
400static bool canRewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags &NW,
401 const DataLayout &DL,
402 SetVector<Value *> &Explored) {
403 SmallVector<Value *, 16> WorkList(1, Start);
404 Explored.insert(X: Base);
405
406 // The following traversal gives us an order which can be used
407 // when doing the final transformation. Since in the final
408 // transformation we create the PHI replacement instructions first,
409 // we don't have to get them in any particular order.
410 //
411 // However, for other instructions we will have to traverse the
412 // operands of an instruction first, which means that we have to
413 // do a post-order traversal.
414 while (!WorkList.empty()) {
415 SetVector<PHINode *> PHIs;
416
417 while (!WorkList.empty()) {
418 if (Explored.size() >= 100)
419 return false;
420
421 Value *V = WorkList.back();
422
423 if (Explored.contains(key: V)) {
424 WorkList.pop_back();
425 continue;
426 }
427
428 if (!isa<GetElementPtrInst>(Val: V) && !isa<PHINode>(Val: V))
429 // We've found some value that we can't explore which is different from
430 // the base. Therefore we can't do this transformation.
431 return false;
432
433 if (auto *GEP = dyn_cast<GEPOperator>(Val: V)) {
434 // Only allow inbounds GEPs with at most one variable offset.
435 auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(Val: V); };
436 if (!GEP->isInBounds() || count_if(Range: GEP->indices(), P: IsNonConst) > 1)
437 return false;
438
439 NW = NW.intersectForOffsetAdd(Other: GEP->getNoWrapFlags());
440 if (!Explored.contains(key: GEP->getOperand(i_nocapture: 0)))
441 WorkList.push_back(Elt: GEP->getOperand(i_nocapture: 0));
442 }
443
444 if (WorkList.back() == V) {
445 WorkList.pop_back();
446 // We've finished visiting this node, mark it as such.
447 Explored.insert(X: V);
448 }
449
450 if (auto *PN = dyn_cast<PHINode>(Val: V)) {
451 // We cannot transform PHIs on unsplittable basic blocks.
452 if (isa<CatchSwitchInst>(Val: PN->getParent()->getTerminator()))
453 return false;
454 Explored.insert(X: PN);
455 PHIs.insert(X: PN);
456 }
457 }
458
459 // Explore the PHI nodes further.
460 for (auto *PN : PHIs)
461 for (Value *Op : PN->incoming_values())
462 if (!Explored.contains(key: Op))
463 WorkList.push_back(Elt: Op);
464 }
465
466 // Make sure that we can do this. Since we can't insert GEPs in a basic
467 // block before a PHI node, we can't easily do this transformation if
468 // we have PHI node users of transformed instructions.
469 for (Value *Val : Explored) {
470 for (Value *Use : Val->uses()) {
471
472 auto *PHI = dyn_cast<PHINode>(Val: Use);
473 auto *Inst = dyn_cast<Instruction>(Val);
474
475 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
476 !Explored.contains(key: PHI))
477 continue;
478
479 if (PHI->getParent() == Inst->getParent())
480 return false;
481 }
482 }
483 return true;
484}
485
486// Sets the appropriate insert point on Builder where we can add
487// a replacement Instruction for V (if that is possible).
488static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
489 bool Before = true) {
490 if (auto *PHI = dyn_cast<PHINode>(Val: V)) {
491 BasicBlock *Parent = PHI->getParent();
492 Builder.SetInsertPoint(Parent->getFirstInsertionPt());
493 return;
494 }
495 if (auto *I = dyn_cast<Instruction>(Val: V)) {
496 if (!Before)
497 I = &*std::next(x: I->getIterator());
498 Builder.SetInsertPoint(I);
499 return;
500 }
501 if (auto *A = dyn_cast<Argument>(Val: V)) {
502 // Set the insertion point in the entry block.
503 BasicBlock &Entry = A->getParent()->getEntryBlock();
504 Builder.SetInsertPoint(Entry.getFirstInsertionPt());
505 return;
506 }
507 // Otherwise, this is a constant and we don't need to set a new
508 // insertion point.
509 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
510}
511
512/// Returns a re-written value of Start as an indexed GEP using Base as a
513/// pointer.
514static Value *rewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags NW,
515 const DataLayout &DL,
516 SetVector<Value *> &Explored,
517 InstCombiner &IC) {
518 // Perform all the substitutions. This is a bit tricky because we can
519 // have cycles in our use-def chains.
520 // 1. Create the PHI nodes without any incoming values.
521 // 2. Create all the other values.
522 // 3. Add the edges for the PHI nodes.
523 // 4. Emit GEPs to get the original pointers.
524 // 5. Remove the original instructions.
525 Type *IndexType = IntegerType::get(
526 C&: Base->getContext(), NumBits: DL.getIndexTypeSizeInBits(Ty: Start->getType()));
527
528 DenseMap<Value *, Value *> NewInsts;
529 NewInsts[Base] = ConstantInt::getNullValue(Ty: IndexType);
530
531 // Create the new PHI nodes, without adding any incoming values.
532 for (Value *Val : Explored) {
533 if (Val == Base)
534 continue;
535 // Create empty phi nodes. This avoids cyclic dependencies when creating
536 // the remaining instructions.
537 if (auto *PHI = dyn_cast<PHINode>(Val))
538 NewInsts[PHI] =
539 PHINode::Create(Ty: IndexType, NumReservedValues: PHI->getNumIncomingValues(),
540 NameStr: PHI->getName() + ".idx", InsertBefore: PHI->getIterator());
541 }
542 IRBuilder<> Builder(IC.getModule());
543
544 // Create all the other instructions.
545 for (Value *Val : Explored) {
546 if (NewInsts.contains(Val))
547 continue;
548
549 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
550 setInsertionPoint(Builder, V: GEP);
551 Value *Op = NewInsts[GEP->getOperand(i_nocapture: 0)];
552 Value *OffsetV = emitGEPOffset(Builder: &Builder, DL, GEP);
553 if (isa<ConstantInt>(Val: Op) && cast<ConstantInt>(Val: Op)->isZero())
554 NewInsts[GEP] = OffsetV;
555 else
556 NewInsts[GEP] = Builder.CreateAdd(
557 LHS: Op, RHS: OffsetV, Name: GEP->getOperand(i_nocapture: 0)->getName() + ".add",
558 /*NUW=*/HasNUW: NW.hasNoUnsignedWrap(),
559 /*NSW=*/HasNSW: NW.hasNoUnsignedSignedWrap());
560 continue;
561 }
562 if (isa<PHINode>(Val))
563 continue;
564
565 llvm_unreachable("Unexpected instruction type");
566 }
567
568 // Add the incoming values to the PHI nodes.
569 for (Value *Val : Explored) {
570 if (Val == Base)
571 continue;
572 // All the instructions have been created, we can now add edges to the
573 // phi nodes.
574 if (auto *PHI = dyn_cast<PHINode>(Val)) {
575 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
576 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
577 Value *NewIncoming = PHI->getIncomingValue(i: I);
578
579 auto It = NewInsts.find(Val: NewIncoming);
580 if (It != NewInsts.end())
581 NewIncoming = It->second;
582
583 NewPhi->addIncoming(V: NewIncoming, BB: PHI->getIncomingBlock(i: I));
584 }
585 }
586 }
587
588 for (Value *Val : Explored) {
589 if (Val == Base)
590 continue;
591
592 setInsertionPoint(Builder, V: Val, Before: false);
593 // Create GEP for external users.
594 Value *NewVal = Builder.CreateGEP(Ty: Builder.getInt8Ty(), Ptr: Base, IdxList: NewInsts[Val],
595 Name: Val->getName() + ".ptr", NW);
596 IC.replaceInstUsesWith(I&: *cast<Instruction>(Val), V: NewVal);
597 // Add old instruction to worklist for DCE. We don't directly remove it
598 // here because the original compare is one of the users.
599 IC.addToWorklist(I: cast<Instruction>(Val));
600 }
601
602 return NewInsts[Start];
603}
604
605/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
606/// We can look through PHIs, GEPs and casts in order to determine a common base
607/// between GEPLHS and RHS.
608static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
609 CmpPredicate Cond,
610 const DataLayout &DL,
611 InstCombiner &IC) {
612 // FIXME: Support vector of pointers.
613 if (GEPLHS->getType()->isVectorTy())
614 return nullptr;
615
616 if (!GEPLHS->hasAllConstantIndices())
617 return nullptr;
618
619 APInt Offset(DL.getIndexTypeSizeInBits(Ty: GEPLHS->getType()), 0);
620 Value *PtrBase =
621 GEPLHS->stripAndAccumulateConstantOffsets(DL, Offset,
622 /*AllowNonInbounds*/ false);
623
624 // Bail if we looked through addrspacecast.
625 if (PtrBase->getType() != GEPLHS->getType())
626 return nullptr;
627
628 // The set of nodes that will take part in this transformation.
629 SetVector<Value *> Nodes;
630 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags();
631 if (!canRewriteGEPAsOffset(Start: RHS, Base: PtrBase, NW, DL, Explored&: Nodes))
632 return nullptr;
633
634 // We know we can re-write this as
635 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
636 // Since we've only looked through inbouds GEPs we know that we
637 // can't have overflow on either side. We can therefore re-write
638 // this as:
639 // OFFSET1 cmp OFFSET2
640 Value *NewRHS = rewriteGEPAsOffset(Start: RHS, Base: PtrBase, NW, DL, Explored&: Nodes, IC);
641
642 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
643 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
644 // offset. Since Index is the offset of LHS to the base pointer, we will now
645 // compare the offsets instead of comparing the pointers.
646 return new ICmpInst(ICmpInst::getSignedPredicate(Pred: Cond),
647 IC.Builder.getInt(AI: Offset), NewRHS);
648}
649
650/// Fold comparisons between a GEP instruction and something else. At this point
651/// we know that the GEP is on the LHS of the comparison.
652Instruction *InstCombinerImpl::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
653 CmpPredicate Cond, Instruction &I) {
654 // Don't transform signed compares of GEPs into index compares. Even if the
655 // GEP is inbounds, the final add of the base pointer can have signed overflow
656 // and would change the result of the icmp.
657 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
658 // the maximum signed value for the pointer type.
659 if (ICmpInst::isSigned(Pred: Cond))
660 return nullptr;
661
662 // Look through bitcasts and addrspacecasts. We do not however want to remove
663 // 0 GEPs.
664 if (!isa<GetElementPtrInst>(Val: RHS))
665 RHS = RHS->stripPointerCasts();
666
667 auto CanFold = [Cond](GEPNoWrapFlags NW) {
668 if (ICmpInst::isEquality(P: Cond))
669 return true;
670
671 // Unsigned predicates can be folded if the GEPs have *any* nowrap flags.
672 assert(ICmpInst::isUnsigned(Cond));
673 return NW != GEPNoWrapFlags::none();
674 };
675
676 auto NewICmp = [Cond](GEPNoWrapFlags NW, Value *Op1, Value *Op2) {
677 if (!NW.hasNoUnsignedWrap()) {
678 // Convert signed to unsigned comparison.
679 return new ICmpInst(ICmpInst::getSignedPredicate(Pred: Cond), Op1, Op2);
680 }
681
682 auto *I = new ICmpInst(Cond, Op1, Op2);
683 I->setSameSign(NW.hasNoUnsignedSignedWrap());
684 return I;
685 };
686
687 CommonPointerBase Base = CommonPointerBase::compute(LHS: GEPLHS, RHS);
688 if (Base.Ptr == RHS && CanFold(Base.LHSNW) && !Base.isExpensive()) {
689 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
690 Type *IdxTy = DL.getIndexType(PtrTy: GEPLHS->getType());
691 Value *Offset =
692 EmitGEPOffsets(GEPs: Base.LHSGEPs, NW: Base.LHSNW, IdxTy, /*RewriteGEPs=*/true);
693 return NewICmp(Base.LHSNW, Offset,
694 Constant::getNullValue(Ty: Offset->getType()));
695 }
696
697 if (GEPLHS->isInBounds() && ICmpInst::isEquality(P: Cond) &&
698 isa<ConstantPointerNull>(Val: RHS) &&
699 !NullPointerIsDefined(F: I.getFunction(),
700 AS: RHS->getType()->getPointerAddressSpace())) {
701 // For most address spaces, an allocation can't be placed at null, but null
702 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
703 // the only valid inbounds address derived from null, is null itself.
704 // Thus, we have four cases to consider:
705 // 1) Base == nullptr, Offset == 0 -> inbounds, null
706 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
707 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
708 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
709 //
710 // (Note if we're indexing a type of size 0, that simply collapses into one
711 // of the buckets above.)
712 //
713 // In general, we're allowed to make values less poison (i.e. remove
714 // sources of full UB), so in this case, we just select between the two
715 // non-poison cases (1 and 4 above).
716 //
717 // For vectors, we apply the same reasoning on a per-lane basis.
718 auto *Base = GEPLHS->getPointerOperand();
719 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
720 auto EC = cast<VectorType>(Val: GEPLHS->getType())->getElementCount();
721 Base = Builder.CreateVectorSplat(EC, V: Base);
722 }
723 return new ICmpInst(Cond, Base,
724 ConstantExpr::getPointerBitCastOrAddrSpaceCast(
725 C: cast<Constant>(Val: RHS), Ty: Base->getType()));
726 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(Val: RHS)) {
727 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags() & GEPRHS->getNoWrapFlags();
728
729 // If the base pointers are different, but the indices are the same, just
730 // compare the base pointer.
731 if (GEPLHS->getOperand(i_nocapture: 0) != GEPRHS->getOperand(i_nocapture: 0)) {
732 bool IndicesTheSame =
733 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
734 GEPLHS->getPointerOperand()->getType() ==
735 GEPRHS->getPointerOperand()->getType() &&
736 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
737 if (IndicesTheSame)
738 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
739 if (GEPLHS->getOperand(i_nocapture: i) != GEPRHS->getOperand(i_nocapture: i)) {
740 IndicesTheSame = false;
741 break;
742 }
743
744 // If all indices are the same, just compare the base pointers.
745 Type *BaseType = GEPLHS->getOperand(i_nocapture: 0)->getType();
746 if (IndicesTheSame &&
747 CmpInst::makeCmpResultType(opnd_type: BaseType) == I.getType() && CanFold(NW))
748 return new ICmpInst(Cond, GEPLHS->getOperand(i_nocapture: 0), GEPRHS->getOperand(i_nocapture: 0));
749
750 // If we're comparing GEPs with two base pointers that only differ in type
751 // and both GEPs have only constant indices or just one use, then fold
752 // the compare with the adjusted indices.
753 // FIXME: Support vector of pointers.
754 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
755 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
756 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
757 GEPLHS->getOperand(i_nocapture: 0)->stripPointerCasts() ==
758 GEPRHS->getOperand(i_nocapture: 0)->stripPointerCasts() &&
759 !GEPLHS->getType()->isVectorTy()) {
760 Value *LOffset = EmitGEPOffset(GEP: GEPLHS);
761 Value *ROffset = EmitGEPOffset(GEP: GEPRHS);
762
763 // If we looked through an addrspacecast between different sized address
764 // spaces, the LHS and RHS pointers are different sized
765 // integers. Truncate to the smaller one.
766 Type *LHSIndexTy = LOffset->getType();
767 Type *RHSIndexTy = ROffset->getType();
768 if (LHSIndexTy != RHSIndexTy) {
769 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
770 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
771 ROffset = Builder.CreateTrunc(V: ROffset, DestTy: LHSIndexTy);
772 } else
773 LOffset = Builder.CreateTrunc(V: LOffset, DestTy: RHSIndexTy);
774 }
775
776 Value *Cmp = Builder.CreateICmp(P: ICmpInst::getSignedPredicate(Pred: Cond),
777 LHS: LOffset, RHS: ROffset);
778 return replaceInstUsesWith(I, V: Cmp);
779 }
780 }
781
782 if (GEPLHS->getOperand(i_nocapture: 0) == GEPRHS->getOperand(i_nocapture: 0) &&
783 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
784 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
785 // If the GEPs only differ by one index, compare it.
786 unsigned NumDifferences = 0; // Keep track of # differences.
787 unsigned DiffOperand = 0; // The operand that differs.
788 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
789 if (GEPLHS->getOperand(i_nocapture: i) != GEPRHS->getOperand(i_nocapture: i)) {
790 Type *LHSType = GEPLHS->getOperand(i_nocapture: i)->getType();
791 Type *RHSType = GEPRHS->getOperand(i_nocapture: i)->getType();
792 // FIXME: Better support for vector of pointers.
793 if (LHSType->getPrimitiveSizeInBits() !=
794 RHSType->getPrimitiveSizeInBits() ||
795 (GEPLHS->getType()->isVectorTy() &&
796 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
797 // Irreconcilable differences.
798 NumDifferences = 2;
799 break;
800 }
801
802 if (NumDifferences++)
803 break;
804 DiffOperand = i;
805 }
806
807 if (NumDifferences == 0) // SAME GEP?
808 return replaceInstUsesWith(
809 I, // No comparison is needed here.
810 V: ConstantInt::get(Ty: I.getType(), V: ICmpInst::isTrueWhenEqual(predicate: Cond)));
811 // If two GEPs only differ by an index, compare them.
812 // Note that nowrap flags are always needed when comparing two indices.
813 else if (NumDifferences == 1 && NW != GEPNoWrapFlags::none()) {
814 Value *LHSV = GEPLHS->getOperand(i_nocapture: DiffOperand);
815 Value *RHSV = GEPRHS->getOperand(i_nocapture: DiffOperand);
816 return NewICmp(NW, LHSV, RHSV);
817 }
818 }
819
820 if (Base.Ptr && !Base.isExpensive()) {
821 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
822 bool DoFold = CanFold(Base.LHSNW & Base.RHSNW);
823
824 if (!DoFold && Base.Ptr->getType()->isPointerTy()) {
825 // Without the flags, we can still fold if the offsets are constant and
826 // they cross the base's alignment boundary the same number of times, so
827 // either both arguments will wrap, or none of them will.
828 unsigned BW = DL.getIndexTypeSizeInBits(Ty: GEPLHS->getType());
829 APInt Alignment = APInt(BW, Base.Ptr->getPointerAlignment(DL).value());
830 APInt LOff(BW, 0);
831 APInt ROff(BW, 0);
832 if (GEPLHS->stripAndAccumulateConstantOffsets(
833 DL, Offset&: LOff, /*AllowNonInbounds=*/true) == Base.Ptr &&
834 RHS->stripAndAccumulateConstantOffsets(
835 DL, Offset&: ROff, /*AllowNonInbounds=*/true) == Base.Ptr)
836 DoFold =
837 APIntOps::RoundingSDiv(A: LOff, B: Alignment, RM: APInt::Rounding::DOWN) ==
838 APIntOps::RoundingSDiv(A: ROff, B: Alignment, RM: APInt::Rounding::DOWN);
839 }
840
841 if (DoFold) {
842 Type *IdxTy = DL.getIndexType(PtrTy: GEPLHS->getType());
843 Value *L = EmitGEPOffsets(GEPs: Base.LHSGEPs, NW: Base.LHSNW, IdxTy,
844 /*RewriteGEP=*/RewriteGEPs: true);
845 Value *R = EmitGEPOffsets(GEPs: Base.RHSGEPs, NW: Base.RHSNW, IdxTy,
846 /*RewriteGEP=*/RewriteGEPs: true);
847 return NewICmp(Base.LHSNW & Base.RHSNW, L, R);
848 }
849 }
850 }
851
852 // Try convert this to an indexed compare by looking through PHIs/casts as a
853 // last resort.
854 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, IC&: *this);
855}
856
857bool InstCombinerImpl::foldAllocaCmp(AllocaInst *Alloca) {
858 // It would be tempting to fold away comparisons between allocas and any
859 // pointer not based on that alloca (e.g. an argument). However, even
860 // though such pointers cannot alias, they can still compare equal.
861 //
862 // But LLVM doesn't specify where allocas get their memory, so if the alloca
863 // doesn't escape we can argue that it's impossible to guess its value, and we
864 // can therefore act as if any such guesses are wrong.
865 //
866 // However, we need to ensure that this folding is consistent: We can't fold
867 // one comparison to false, and then leave a different comparison against the
868 // same value alone (as it might evaluate to true at runtime, leading to a
869 // contradiction). As such, this code ensures that all comparisons are folded
870 // at the same time, and there are no other escapes.
871
872 struct CmpCaptureTracker : public CaptureTracker {
873 AllocaInst *Alloca;
874 bool Captured = false;
875 /// The value of the map is a bit mask of which icmp operands the alloca is
876 /// used in.
877 SmallMapVector<ICmpInst *, unsigned, 4> ICmps;
878
879 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
880
881 void tooManyUses() override { Captured = true; }
882
883 Action captured(const Use *U, UseCaptureInfo CI) override {
884 // TODO(captures): Use UseCaptureInfo.
885 auto *ICmp = dyn_cast<ICmpInst>(Val: U->getUser());
886 // We need to check that U is based *only* on the alloca, and doesn't
887 // have other contributions from a select/phi operand.
888 // TODO: We could check whether getUnderlyingObjects() reduces to one
889 // object, which would allow looking through phi nodes.
890 if (ICmp && ICmp->isEquality() && getUnderlyingObject(V: *U) == Alloca) {
891 // Collect equality icmps of the alloca, and don't treat them as
892 // captures.
893 ICmps[ICmp] |= 1u << U->getOperandNo();
894 return Continue;
895 }
896
897 Captured = true;
898 return Stop;
899 }
900 };
901
902 CmpCaptureTracker Tracker(Alloca);
903 PointerMayBeCaptured(V: Alloca, Tracker: &Tracker);
904 if (Tracker.Captured)
905 return false;
906
907 bool Changed = false;
908 for (auto [ICmp, Operands] : Tracker.ICmps) {
909 switch (Operands) {
910 case 1:
911 case 2: {
912 // The alloca is only used in one icmp operand. Assume that the
913 // equality is false.
914 auto *Res = ConstantInt::get(Ty: ICmp->getType(),
915 V: ICmp->getPredicate() == ICmpInst::ICMP_NE);
916 replaceInstUsesWith(I&: *ICmp, V: Res);
917 eraseInstFromFunction(I&: *ICmp);
918 Changed = true;
919 break;
920 }
921 case 3:
922 // Both icmp operands are based on the alloca, so this is comparing
923 // pointer offsets, without leaking any information about the address
924 // of the alloca. Ignore such comparisons.
925 break;
926 default:
927 llvm_unreachable("Cannot happen");
928 }
929 }
930
931 return Changed;
932}
933
934/// Fold "icmp pred (X+C), X".
935Instruction *InstCombinerImpl::foldICmpAddOpConst(Value *X, const APInt &C,
936 CmpPredicate Pred) {
937 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
938 // so the values can never be equal. Similarly for all other "or equals"
939 // operators.
940 assert(!!C && "C should not be zero!");
941
942 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
943 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
944 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
945 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
946 Constant *R =
947 ConstantInt::get(Ty: X->getType(), V: APInt::getMaxValue(numBits: C.getBitWidth()) - C);
948 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
949 }
950
951 // (X+1) >u X --> X <u (0-1) --> X != 255
952 // (X+2) >u X --> X <u (0-2) --> X <u 254
953 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
954 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
955 return new ICmpInst(ICmpInst::ICMP_ULT, X,
956 ConstantInt::get(Ty: X->getType(), V: -C));
957
958 APInt SMax = APInt::getSignedMaxValue(numBits: C.getBitWidth());
959
960 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
961 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
962 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
963 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
964 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
965 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
966 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
967 return new ICmpInst(ICmpInst::ICMP_SGT, X,
968 ConstantInt::get(Ty: X->getType(), V: SMax - C));
969
970 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
971 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
972 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
973 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
974 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
975 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
976
977 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
978 return new ICmpInst(ICmpInst::ICMP_SLT, X,
979 ConstantInt::get(Ty: X->getType(), V: SMax - (C - 1)));
980}
981
982/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
983/// (icmp eq/ne A, Log2(AP2/AP1)) ->
984/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
985Instruction *InstCombinerImpl::foldICmpShrConstConst(ICmpInst &I, Value *A,
986 const APInt &AP1,
987 const APInt &AP2) {
988 assert(I.isEquality() && "Cannot fold icmp gt/lt");
989
990 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
991 if (I.getPredicate() == I.ICMP_NE)
992 Pred = CmpInst::getInversePredicate(pred: Pred);
993 return new ICmpInst(Pred, LHS, RHS);
994 };
995
996 // Don't bother doing any work for cases which InstSimplify handles.
997 if (AP2.isZero())
998 return nullptr;
999
1000 bool IsAShr = isa<AShrOperator>(Val: I.getOperand(i_nocapture: 0));
1001 if (IsAShr) {
1002 if (AP2.isAllOnes())
1003 return nullptr;
1004 if (AP2.isNegative() != AP1.isNegative())
1005 return nullptr;
1006 if (AP2.sgt(RHS: AP1))
1007 return nullptr;
1008 }
1009
1010 if (!AP1)
1011 // 'A' must be large enough to shift out the highest set bit.
1012 return getICmp(I.ICMP_UGT, A,
1013 ConstantInt::get(Ty: A->getType(), V: AP2.logBase2()));
1014
1015 if (AP1 == AP2)
1016 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(Ty: A->getType()));
1017
1018 int Shift;
1019 if (IsAShr && AP1.isNegative())
1020 Shift = AP1.countl_one() - AP2.countl_one();
1021 else
1022 Shift = AP1.countl_zero() - AP2.countl_zero();
1023
1024 if (Shift > 0) {
1025 if (IsAShr && AP1 == AP2.ashr(ShiftAmt: Shift)) {
1026 // There are multiple solutions if we are comparing against -1 and the LHS
1027 // of the ashr is not a power of two.
1028 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1029 return getICmp(I.ICMP_UGE, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1030 return getICmp(I.ICMP_EQ, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1031 } else if (AP1 == AP2.lshr(shiftAmt: Shift)) {
1032 return getICmp(I.ICMP_EQ, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1033 }
1034 }
1035
1036 // Shifting const2 will never be equal to const1.
1037 // FIXME: This should always be handled by InstSimplify?
1038 auto *TorF = ConstantInt::get(Ty: I.getType(), V: I.getPredicate() == I.ICMP_NE);
1039 return replaceInstUsesWith(I, V: TorF);
1040}
1041
1042/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1043/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1044Instruction *InstCombinerImpl::foldICmpShlConstConst(ICmpInst &I, Value *A,
1045 const APInt &AP1,
1046 const APInt &AP2) {
1047 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1048
1049 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1050 if (I.getPredicate() == I.ICMP_NE)
1051 Pred = CmpInst::getInversePredicate(pred: Pred);
1052 return new ICmpInst(Pred, LHS, RHS);
1053 };
1054
1055 // Don't bother doing any work for cases which InstSimplify handles.
1056 if (AP2.isZero())
1057 return nullptr;
1058
1059 unsigned AP2TrailingZeros = AP2.countr_zero();
1060
1061 if (!AP1 && AP2TrailingZeros != 0)
1062 return getICmp(
1063 I.ICMP_UGE, A,
1064 ConstantInt::get(Ty: A->getType(), V: AP2.getBitWidth() - AP2TrailingZeros));
1065
1066 if (AP1 == AP2)
1067 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(Ty: A->getType()));
1068
1069 // Get the distance between the lowest bits that are set.
1070 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1071
1072 if (Shift > 0 && AP2.shl(shiftAmt: Shift) == AP1)
1073 return getICmp(I.ICMP_EQ, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1074
1075 // Shifting const2 will never be equal to const1.
1076 // FIXME: This should always be handled by InstSimplify?
1077 auto *TorF = ConstantInt::get(Ty: I.getType(), V: I.getPredicate() == I.ICMP_NE);
1078 return replaceInstUsesWith(I, V: TorF);
1079}
1080
1081/// The caller has matched a pattern of the form:
1082/// I = icmp ugt (add (add A, B), CI2), CI1
1083/// If this is of the form:
1084/// sum = a + b
1085/// if (sum+128 >u 255)
1086/// Then replace it with llvm.sadd.with.overflow.i8.
1087///
1088static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1089 ConstantInt *CI2, ConstantInt *CI1,
1090 InstCombinerImpl &IC) {
1091 // The transformation we're trying to do here is to transform this into an
1092 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1093 // with a narrower add, and discard the add-with-constant that is part of the
1094 // range check (if we can't eliminate it, this isn't profitable).
1095
1096 // In order to eliminate the add-with-constant, the compare can be its only
1097 // use.
1098 Instruction *AddWithCst = cast<Instruction>(Val: I.getOperand(i_nocapture: 0));
1099 if (!AddWithCst->hasOneUse())
1100 return nullptr;
1101
1102 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1103 if (!CI2->getValue().isPowerOf2())
1104 return nullptr;
1105 unsigned NewWidth = CI2->getValue().countr_zero();
1106 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1107 return nullptr;
1108
1109 // The width of the new add formed is 1 more than the bias.
1110 ++NewWidth;
1111
1112 // Check to see that CI1 is an all-ones value with NewWidth bits.
1113 if (CI1->getBitWidth() == NewWidth ||
1114 CI1->getValue() != APInt::getLowBitsSet(numBits: CI1->getBitWidth(), loBitsSet: NewWidth))
1115 return nullptr;
1116
1117 // This is only really a signed overflow check if the inputs have been
1118 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1119 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1120 if (IC.ComputeMaxSignificantBits(Op: A, CtxI: &I) > NewWidth ||
1121 IC.ComputeMaxSignificantBits(Op: B, CtxI: &I) > NewWidth)
1122 return nullptr;
1123
1124 // In order to replace the original add with a narrower
1125 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1126 // and truncates that discard the high bits of the add. Verify that this is
1127 // the case.
1128 Instruction *OrigAdd = cast<Instruction>(Val: AddWithCst->getOperand(i: 0));
1129 for (User *U : OrigAdd->users()) {
1130 if (U == AddWithCst)
1131 continue;
1132
1133 // Only accept truncates for now. We would really like a nice recursive
1134 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1135 // chain to see which bits of a value are actually demanded. If the
1136 // original add had another add which was then immediately truncated, we
1137 // could still do the transformation.
1138 TruncInst *TI = dyn_cast<TruncInst>(Val: U);
1139 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1140 return nullptr;
1141 }
1142
1143 // If the pattern matches, truncate the inputs to the narrower type and
1144 // use the sadd_with_overflow intrinsic to efficiently compute both the
1145 // result and the overflow bit.
1146 Type *NewType = IntegerType::get(C&: OrigAdd->getContext(), NumBits: NewWidth);
1147 Function *F = Intrinsic::getOrInsertDeclaration(
1148 M: I.getModule(), id: Intrinsic::sadd_with_overflow, OverloadTys: NewType);
1149
1150 InstCombiner::BuilderTy &Builder = IC.Builder;
1151
1152 // Put the new code above the original add, in case there are any uses of the
1153 // add between the add and the compare.
1154 Builder.SetInsertPoint(OrigAdd);
1155
1156 Value *TruncA = Builder.CreateTrunc(V: A, DestTy: NewType, Name: A->getName() + ".trunc");
1157 Value *TruncB = Builder.CreateTrunc(V: B, DestTy: NewType, Name: B->getName() + ".trunc");
1158 CallInst *Call = Builder.CreateCall(Callee: F, Args: {TruncA, TruncB}, Name: "sadd");
1159 Value *Add = Builder.CreateExtractValue(Agg: Call, Idxs: 0, Name: "sadd.result");
1160 Value *ZExt = Builder.CreateZExt(V: Add, DestTy: OrigAdd->getType());
1161
1162 // The inner add was the result of the narrow add, zero extended to the
1163 // wider type. Replace it with the result computed by the intrinsic.
1164 IC.replaceInstUsesWith(I&: *OrigAdd, V: ZExt);
1165 IC.eraseInstFromFunction(I&: *OrigAdd);
1166
1167 // The original icmp gets replaced with the overflow value.
1168 return ExtractValueInst::Create(Agg: Call, Idxs: 1, NameStr: "sadd.overflow");
1169}
1170
1171/// If we have:
1172/// icmp eq/ne (urem/srem %x, %y), 0
1173/// iff %y is a power-of-two, we can replace this with a bit test:
1174/// icmp eq/ne (and %x, (add %y, -1)), 0
1175Instruction *InstCombinerImpl::foldIRemByPowerOfTwoToBitTest(ICmpInst &I) {
1176 // This fold is only valid for equality predicates.
1177 if (!I.isEquality())
1178 return nullptr;
1179 CmpPredicate Pred;
1180 Value *X, *Y, *Zero;
1181 if (!match(V: &I, P: m_ICmp(Pred, L: m_OneUse(SubPattern: m_IRem(L: m_Value(V&: X), R: m_Value(V&: Y))),
1182 R: m_CombineAnd(Ps: m_Zero(), Ps: m_Value(V&: Zero)))))
1183 return nullptr;
1184 if (!isKnownToBeAPowerOfTwo(V: Y, /*OrZero*/ true, CtxI: &I))
1185 return nullptr;
1186 // This may increase instruction count, we don't enforce that Y is a constant.
1187 Value *Mask = Builder.CreateAdd(LHS: Y, RHS: Constant::getAllOnesValue(Ty: Y->getType()));
1188 Value *Masked = Builder.CreateAnd(LHS: X, RHS: Mask);
1189 return ICmpInst::Create(Op: Instruction::ICmp, Pred, S1: Masked, S2: Zero);
1190}
1191
1192/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1193/// by one-less-than-bitwidth into a sign test on the original value.
1194Instruction *InstCombinerImpl::foldSignBitTest(ICmpInst &I) {
1195 Instruction *Val;
1196 CmpPredicate Pred;
1197 if (!I.isEquality() || !match(V: &I, P: m_ICmp(Pred, L: m_Instruction(I&: Val), R: m_Zero())))
1198 return nullptr;
1199
1200 Value *X;
1201 Type *XTy;
1202
1203 Constant *C;
1204 if (match(V: Val, P: m_TruncOrSelf(Op: m_Shr(L: m_Value(V&: X), R: m_Constant(C))))) {
1205 XTy = X->getType();
1206 unsigned XBitWidth = XTy->getScalarSizeInBits();
1207 if (!match(V: C, P: m_SpecificInt_ICMP(Predicate: ICmpInst::Predicate::ICMP_EQ,
1208 Threshold: APInt(XBitWidth, XBitWidth - 1))))
1209 return nullptr;
1210 } else if (isa<BinaryOperator>(Val) &&
1211 (X = reassociateShiftAmtsOfTwoSameDirectionShifts(
1212 Sh0: cast<BinaryOperator>(Val), SQ: SQ.getWithInstruction(I: Val),
1213 /*AnalyzeForSignBitExtraction=*/true))) {
1214 XTy = X->getType();
1215 } else
1216 return nullptr;
1217
1218 return ICmpInst::Create(Op: Instruction::ICmp,
1219 Pred: Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SGE
1220 : ICmpInst::ICMP_SLT,
1221 S1: X, S2: ConstantInt::getNullValue(Ty: XTy));
1222}
1223
1224// Handle icmp pred X, 0
1225Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) {
1226 CmpInst::Predicate Pred = Cmp.getPredicate();
1227 if (!match(V: Cmp.getOperand(i_nocapture: 1), P: m_Zero()))
1228 return nullptr;
1229
1230 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1231 if (Pred == ICmpInst::ICMP_SGT) {
1232 Value *A, *B;
1233 if (match(V: Cmp.getOperand(i_nocapture: 0), P: m_SMin(Op0: m_Value(V&: A), Op1: m_Value(V&: B)))) {
1234 if (isKnownPositive(V: A, SQ: SQ.getWithInstruction(I: &Cmp)))
1235 return new ICmpInst(Pred, B, Cmp.getOperand(i_nocapture: 1));
1236 if (isKnownPositive(V: B, SQ: SQ.getWithInstruction(I: &Cmp)))
1237 return new ICmpInst(Pred, A, Cmp.getOperand(i_nocapture: 1));
1238 }
1239 }
1240
1241 if (Instruction *New = foldIRemByPowerOfTwoToBitTest(I&: Cmp))
1242 return New;
1243
1244 // Given:
1245 // icmp eq/ne (urem %x, %y), 0
1246 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1247 // icmp eq/ne %x, 0
1248 Value *X, *Y;
1249 if (match(V: Cmp.getOperand(i_nocapture: 0), P: m_URem(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
1250 ICmpInst::isEquality(P: Pred)) {
1251 KnownBits XKnown = computeKnownBits(V: X, CtxI: &Cmp);
1252 KnownBits YKnown = computeKnownBits(V: Y, CtxI: &Cmp);
1253 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1254 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
1255 }
1256
1257 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1258 // odd/non-zero/there is no overflow.
1259 if (match(V: Cmp.getOperand(i_nocapture: 0), P: m_Mul(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
1260 ICmpInst::isEquality(P: Pred)) {
1261
1262 KnownBits XKnown = computeKnownBits(V: X, CtxI: &Cmp);
1263 // if X % 2 != 0
1264 // (icmp eq/ne Y)
1265 if (XKnown.countMaxTrailingZeros() == 0)
1266 return new ICmpInst(Pred, Y, Cmp.getOperand(i_nocapture: 1));
1267
1268 KnownBits YKnown = computeKnownBits(V: Y, CtxI: &Cmp);
1269 // if Y % 2 != 0
1270 // (icmp eq/ne X)
1271 if (YKnown.countMaxTrailingZeros() == 0)
1272 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
1273
1274 auto *BO0 = cast<OverflowingBinaryOperator>(Val: Cmp.getOperand(i_nocapture: 0));
1275 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1276 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
1277 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1278 // but to avoid unnecessary work, first just if this is an obvious case.
1279
1280 // if X non-zero and NoOverflow(X * Y)
1281 // (icmp eq/ne Y)
1282 if (!XKnown.One.isZero() || isKnownNonZero(V: X, Q))
1283 return new ICmpInst(Pred, Y, Cmp.getOperand(i_nocapture: 1));
1284
1285 // if Y non-zero and NoOverflow(X * Y)
1286 // (icmp eq/ne X)
1287 if (!YKnown.One.isZero() || isKnownNonZero(V: Y, Q))
1288 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
1289 }
1290 // Note, we are skipping cases:
1291 // if Y % 2 != 0 AND X % 2 != 0
1292 // (false/true)
1293 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1294 // (false/true)
1295 // Those can be simplified later as we would have already replaced the (icmp
1296 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1297 // will fold to a constant elsewhere.
1298 }
1299
1300 // (icmp eq/ne f(X), 0) -> (icmp eq/ne X, 0)
1301 // where f(X) == 0 if and only if X == 0
1302 if (ICmpInst::isEquality(P: Pred))
1303 if (Value *Stripped = stripNullTest(V: Cmp.getOperand(i_nocapture: 0)))
1304 return new ICmpInst(Pred, Stripped,
1305 Constant::getNullValue(Ty: Stripped->getType()));
1306
1307 return nullptr;
1308}
1309
1310/// Fold icmp eq (num + mask) & ~mask, num
1311/// to
1312/// icmp eq (and num, mask), 0
1313/// Where mask is a low bit mask.
1314Instruction *InstCombinerImpl::foldIsMultipleOfAPowerOfTwo(ICmpInst &Cmp) {
1315 Value *Num;
1316 CmpPredicate Pred;
1317 const APInt *Mask, *Neg;
1318
1319 if (!match(V: &Cmp,
1320 P: m_c_ICmp(Pred, L: m_Value(V&: Num),
1321 R: m_OneUse(SubPattern: m_c_And(L: m_OneUse(SubPattern: m_c_Add(L: m_Deferred(V: Num),
1322 R: m_LowBitMask(V&: Mask))),
1323 R: m_APInt(Res&: Neg))))))
1324 return nullptr;
1325
1326 if (*Neg != ~*Mask)
1327 return nullptr;
1328
1329 if (!ICmpInst::isEquality(P: Pred))
1330 return nullptr;
1331
1332 // Create new icmp eq (num & mask), 0
1333 auto *NewAnd = Builder.CreateAnd(LHS: Num, RHS: *Mask);
1334 auto *Zero = Constant::getNullValue(Ty: Num->getType());
1335
1336 return new ICmpInst(Pred, NewAnd, Zero);
1337}
1338
1339/// Fold icmp Pred X, C.
1340/// TODO: This code structure does not make sense. The saturating add fold
1341/// should be moved to some other helper and extended as noted below (it is also
1342/// possible that code has been made unnecessary - do we canonicalize IR to
1343/// overflow/saturating intrinsics or not?).
1344Instruction *InstCombinerImpl::foldICmpWithConstant(ICmpInst &Cmp) {
1345 // Match the following pattern, which is a common idiom when writing
1346 // overflow-safe integer arithmetic functions. The source performs an addition
1347 // in wider type and explicitly checks for overflow using comparisons against
1348 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1349 //
1350 // TODO: This could probably be generalized to handle other overflow-safe
1351 // operations if we worked out the formulas to compute the appropriate magic
1352 // constants.
1353 //
1354 // sum = a + b
1355 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1356 CmpInst::Predicate Pred = Cmp.getPredicate();
1357 Value *Op0 = Cmp.getOperand(i_nocapture: 0), *Op1 = Cmp.getOperand(i_nocapture: 1);
1358 Value *A, *B;
1359 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1360 if (Pred == ICmpInst::ICMP_UGT && match(V: Op1, P: m_ConstantInt(CI)) &&
1361 match(V: Op0, P: m_Add(L: m_Add(L: m_Value(V&: A), R: m_Value(V&: B)), R: m_ConstantInt(CI&: CI2))))
1362 if (Instruction *Res = processUGT_ADDCST_ADD(I&: Cmp, A, B, CI2, CI1: CI, IC&: *this))
1363 return Res;
1364
1365 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1366 Constant *C = dyn_cast<Constant>(Val: Op1);
1367 if (!C)
1368 return nullptr;
1369
1370 if (auto *Phi = dyn_cast<PHINode>(Val: Op0))
1371 if (all_of(Range: Phi->operands(), P: IsaPred<Constant>)) {
1372 SmallVector<Constant *> Ops;
1373 for (Value *V : Phi->incoming_values()) {
1374 Constant *Res =
1375 ConstantFoldCompareInstOperands(Predicate: Pred, LHS: cast<Constant>(Val: V), RHS: C, DL);
1376 if (!Res)
1377 return nullptr;
1378 Ops.push_back(Elt: Res);
1379 }
1380 Builder.SetInsertPoint(Phi);
1381 PHINode *NewPhi = Builder.CreatePHI(Ty: Cmp.getType(), NumReservedValues: Phi->getNumOperands());
1382 for (auto [V, Pred] : zip(t&: Ops, u: Phi->blocks()))
1383 NewPhi->addIncoming(V, BB: Pred);
1384 return replaceInstUsesWith(I&: Cmp, V: NewPhi);
1385 }
1386
1387 if (Instruction *R = tryFoldInstWithCtpopWithNot(I: &Cmp))
1388 return R;
1389
1390 return nullptr;
1391}
1392
1393/// Canonicalize icmp instructions based on dominating conditions.
1394Instruction *InstCombinerImpl::foldICmpWithDominatingICmp(ICmpInst &Cmp) {
1395 // We already checked simple implication in InstSimplify, only handle complex
1396 // cases here.
1397 Value *X = Cmp.getOperand(i_nocapture: 0), *Y = Cmp.getOperand(i_nocapture: 1);
1398 const APInt *C;
1399 if (!match(V: Y, P: m_APInt(Res&: C)))
1400 return nullptr;
1401
1402 CmpInst::Predicate Pred = Cmp.getPredicate();
1403 ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, Other: *C);
1404
1405 auto handleDomCond = [&](ICmpInst::Predicate DomPred,
1406 const APInt *DomC) -> Instruction * {
1407 // We have 2 compares of a variable with constants. Calculate the constant
1408 // ranges of those compares to see if we can transform the 2nd compare:
1409 // DomBB:
1410 // DomCond = icmp DomPred X, DomC
1411 // br DomCond, CmpBB, FalseBB
1412 // CmpBB:
1413 // Cmp = icmp Pred X, C
1414 ConstantRange DominatingCR =
1415 ConstantRange::makeExactICmpRegion(Pred: DomPred, Other: *DomC);
1416 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1417 ConstantRange Difference = DominatingCR.difference(CR);
1418 if (Intersection.isEmptySet())
1419 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
1420 if (Difference.isEmptySet())
1421 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
1422
1423 // Canonicalizing a sign bit comparison that gets used in a branch,
1424 // pessimizes codegen by generating branch on zero instruction instead
1425 // of a test and branch. So we avoid canonicalizing in such situations
1426 // because test and branch instruction has better branch displacement
1427 // than compare and branch instruction.
1428 bool UnusedBit;
1429 bool IsSignBit = isSignBitCheck(Pred, RHS: *C, TrueIfSigned&: UnusedBit);
1430 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(I&: Cmp)))
1431 return nullptr;
1432
1433 // Avoid an infinite loop with min/max canonicalization.
1434 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1435 if (Cmp.hasOneUse() &&
1436 match(V: Cmp.user_back(), P: m_MaxOrMin(Op0: m_Value(), Op1: m_Value())))
1437 return nullptr;
1438
1439 if (const APInt *EqC = Intersection.getSingleElement())
1440 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(AI: *EqC));
1441 if (const APInt *NeC = Difference.getSingleElement())
1442 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(AI: *NeC));
1443 return nullptr;
1444 };
1445
1446 for (CondBrInst *BI : DC.conditionsFor(V: X)) {
1447 CmpPredicate DomPred;
1448 const APInt *DomC;
1449 if (!match(V: BI->getCondition(),
1450 P: m_ICmp(Pred&: DomPred, L: m_Specific(V: X), R: m_APInt(Res&: DomC))))
1451 continue;
1452
1453 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(i: 0));
1454 if (DT.dominates(BBE: Edge0, BB: Cmp.getParent())) {
1455 if (auto *V = handleDomCond(DomPred, DomC))
1456 return V;
1457 } else {
1458 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(i: 1));
1459 if (DT.dominates(BBE: Edge1, BB: Cmp.getParent()))
1460 if (auto *V =
1461 handleDomCond(CmpInst::getInversePredicate(pred: DomPred), DomC))
1462 return V;
1463 }
1464 }
1465
1466 return nullptr;
1467}
1468
1469/// Fold icmp (trunc X), C.
1470Instruction *InstCombinerImpl::foldICmpTruncConstant(ICmpInst &Cmp,
1471 TruncInst *Trunc,
1472 const APInt &C) {
1473 ICmpInst::Predicate Pred = Cmp.getPredicate();
1474 Value *X = Trunc->getOperand(i_nocapture: 0);
1475 Type *SrcTy = X->getType();
1476 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1477 SrcBits = SrcTy->getScalarSizeInBits();
1478
1479 // Match (icmp pred (trunc nuw/nsw X), C)
1480 // Which we can convert to (icmp pred X, (sext/zext C))
1481 if (shouldChangeType(From: Trunc->getType(), To: SrcTy)) {
1482 if (Trunc->hasNoSignedWrap())
1483 return new ICmpInst(Pred, X, ConstantInt::get(Ty: SrcTy, V: C.sext(width: SrcBits)));
1484 if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())
1485 return new ICmpInst(Pred, X, ConstantInt::get(Ty: SrcTy, V: C.zext(width: SrcBits)));
1486 }
1487
1488 if (C.isOne() && C.getBitWidth() > 1) {
1489 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1490 Value *V = nullptr;
1491 if (Pred == ICmpInst::ICMP_SLT && match(V: X, P: m_Signum(V: m_Value(V))))
1492 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1493 ConstantInt::get(Ty: V->getType(), V: 1));
1494 }
1495
1496 // TODO: Handle non-equality predicates.
1497 Value *Y;
1498 const APInt *Pow2;
1499 if (Cmp.isEquality() && match(V: X, P: m_Shl(L: m_Power2(V&: Pow2), R: m_Value(V&: Y))) &&
1500 DstBits > Pow2->logBase2()) {
1501 // (trunc (Pow2 << Y) to iN) == 0 --> Y u>= N - log2(Pow2)
1502 // (trunc (Pow2 << Y) to iN) != 0 --> Y u< N - log2(Pow2)
1503 // iff N > log2(Pow2)
1504 if (C.isZero()) {
1505 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1506 return new ICmpInst(NewPred, Y,
1507 ConstantInt::get(Ty: SrcTy, V: DstBits - Pow2->logBase2()));
1508 }
1509 // (trunc (Pow2 << Y) to iN) == 2**C --> Y == C - log2(Pow2)
1510 // (trunc (Pow2 << Y) to iN) != 2**C --> Y != C - log2(Pow2)
1511 if (C.isPowerOf2())
1512 return new ICmpInst(
1513 Pred, Y, ConstantInt::get(Ty: SrcTy, V: C.logBase2() - Pow2->logBase2()));
1514 }
1515
1516 if (Cmp.isEquality() && (Trunc->hasOneUse() || Trunc->hasNoUnsignedWrap())) {
1517 // Canonicalize to a mask and wider compare if the wide type is suitable:
1518 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1519 if (!SrcTy->isVectorTy() && shouldChangeType(FromBitWidth: DstBits, ToBitWidth: SrcBits)) {
1520 Constant *Mask =
1521 ConstantInt::get(Ty: SrcTy, V: APInt::getLowBitsSet(numBits: SrcBits, loBitsSet: DstBits));
1522 Value *And = Trunc->hasNoUnsignedWrap() ? X : Builder.CreateAnd(LHS: X, RHS: Mask);
1523 Constant *WideC = ConstantInt::get(Ty: SrcTy, V: C.zext(width: SrcBits));
1524 return new ICmpInst(Pred, And, WideC);
1525 }
1526
1527 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1528 // of the high bits truncated out of x are known.
1529 KnownBits Known = computeKnownBits(V: X, CtxI: &Cmp);
1530
1531 // If all the high bits are known, we can do this xform.
1532 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1533 // Pull in the high bits from known-ones set.
1534 APInt NewRHS = C.zext(width: SrcBits);
1535 NewRHS |= Known.One & APInt::getHighBitsSet(numBits: SrcBits, hiBitsSet: SrcBits - DstBits);
1536 return new ICmpInst(Pred, X, ConstantInt::get(Ty: SrcTy, V: NewRHS));
1537 }
1538 }
1539
1540 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1541 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1542 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1543 Value *ShOp;
1544 uint64_t ShAmt;
1545 bool TrueIfSigned;
1546 if (isSignBitCheck(Pred, RHS: C, TrueIfSigned) &&
1547 match(V: X, P: m_Shr(L: m_Value(V&: ShOp), R: m_ConstantInt(V&: ShAmt))) &&
1548 DstBits == SrcBits - ShAmt) {
1549 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1550 ConstantInt::getNullValue(Ty: SrcTy))
1551 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1552 ConstantInt::getAllOnesValue(Ty: SrcTy));
1553 }
1554
1555 return nullptr;
1556}
1557
1558/// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
1559/// Fold icmp (trunc nuw/nsw X), (zext/sext Y).
1560Instruction *
1561InstCombinerImpl::foldICmpTruncWithTruncOrExt(ICmpInst &Cmp,
1562 const SimplifyQuery &Q) {
1563 Value *X, *Y;
1564 CmpPredicate Pred;
1565 bool YIsSExt = false;
1566 // Try to match icmp (trunc X), (trunc Y)
1567 if (match(V: &Cmp, P: m_ICmp(Pred, L: m_Trunc(Op: m_Value(V&: X)), R: m_Trunc(Op: m_Value(V&: Y))))) {
1568 unsigned NoWrapFlags = cast<TruncInst>(Val: Cmp.getOperand(i_nocapture: 0))->getNoWrapKind() &
1569 cast<TruncInst>(Val: Cmp.getOperand(i_nocapture: 1))->getNoWrapKind();
1570 if (Cmp.isSigned()) {
1571 // For signed comparisons, both truncs must be nsw.
1572 if (!(NoWrapFlags & TruncInst::NoSignedWrap))
1573 return nullptr;
1574 } else {
1575 // For unsigned and equality comparisons, either both must be nuw or
1576 // both must be nsw, we don't care which.
1577 if (!NoWrapFlags)
1578 return nullptr;
1579 }
1580
1581 if (X->getType() != Y->getType() &&
1582 (!Cmp.getOperand(i_nocapture: 0)->hasOneUse() || !Cmp.getOperand(i_nocapture: 1)->hasOneUse()))
1583 return nullptr;
1584 if (!isDesirableIntType(BitWidth: X->getType()->getScalarSizeInBits()) &&
1585 isDesirableIntType(BitWidth: Y->getType()->getScalarSizeInBits())) {
1586 std::swap(a&: X, b&: Y);
1587 Pred = Cmp.getSwappedPredicate(pred: Pred);
1588 }
1589 YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);
1590 }
1591 // Try to match icmp (trunc nuw X), (zext Y)
1592 else if (!Cmp.isSigned() &&
1593 match(V: &Cmp, P: m_c_ICmp(Pred, L: m_NUWTrunc(Op: m_Value(V&: X)),
1594 R: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: Y)))))) {
1595 // Can fold trunc nuw + zext for unsigned and equality predicates.
1596 }
1597 // Try to match icmp (trunc nsw X), (sext Y)
1598 else if (match(V: &Cmp, P: m_c_ICmp(Pred, L: m_NSWTrunc(Op: m_Value(V&: X)),
1599 R: m_OneUse(SubPattern: m_ZExtOrSExt(Op: m_Value(V&: Y)))))) {
1600 // Can fold trunc nsw + zext/sext for all predicates.
1601 YIsSExt =
1602 isa<SExtInst>(Val: Cmp.getOperand(i_nocapture: 0)) || isa<SExtInst>(Val: Cmp.getOperand(i_nocapture: 1));
1603 } else
1604 return nullptr;
1605
1606 Type *TruncTy = Cmp.getOperand(i_nocapture: 0)->getType();
1607 unsigned TruncBits = TruncTy->getScalarSizeInBits();
1608
1609 // If this transform will end up changing from desirable types -> undesirable
1610 // types skip it.
1611 if (isDesirableIntType(BitWidth: TruncBits) &&
1612 !isDesirableIntType(BitWidth: X->getType()->getScalarSizeInBits()))
1613 return nullptr;
1614
1615 Value *NewY = Builder.CreateIntCast(V: Y, DestTy: X->getType(), isSigned: YIsSExt);
1616 return new ICmpInst(Pred, X, NewY);
1617}
1618
1619/// Fold icmp (xor X, Y), C.
1620Instruction *InstCombinerImpl::foldICmpXorConstant(ICmpInst &Cmp,
1621 BinaryOperator *Xor,
1622 const APInt &C) {
1623 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1624 return I;
1625
1626 Value *X = Xor->getOperand(i_nocapture: 0);
1627 Value *Y = Xor->getOperand(i_nocapture: 1);
1628 const APInt *XorC;
1629 if (!match(V: Y, P: m_APInt(Res&: XorC)))
1630 return nullptr;
1631
1632 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1633 // fold the xor.
1634 ICmpInst::Predicate Pred = Cmp.getPredicate();
1635 bool TrueIfSigned = false;
1636 if (isSignBitCheck(Pred: Cmp.getPredicate(), RHS: C, TrueIfSigned)) {
1637
1638 // If the sign bit of the XorCst is not set, there is no change to
1639 // the operation, just stop using the Xor.
1640 if (!XorC->isNegative())
1641 return replaceOperand(I&: Cmp, OpNum: 0, V: X);
1642
1643 // Emit the opposite comparison.
1644 if (TrueIfSigned)
1645 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1646 ConstantInt::getAllOnesValue(Ty: X->getType()));
1647 else
1648 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1649 ConstantInt::getNullValue(Ty: X->getType()));
1650 }
1651
1652 if (Xor->hasOneUse()) {
1653 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1654 if (!Cmp.isEquality() && XorC->isSignMask()) {
1655 Pred = Cmp.getFlippedSignednessPredicate();
1656 return new ICmpInst(Pred, X, ConstantInt::get(Ty: X->getType(), V: C ^ *XorC));
1657 }
1658
1659 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1660 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1661 Pred = Cmp.getFlippedSignednessPredicate();
1662 Pred = Cmp.getSwappedPredicate(pred: Pred);
1663 return new ICmpInst(Pred, X, ConstantInt::get(Ty: X->getType(), V: C ^ *XorC));
1664 }
1665 }
1666
1667 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1668 if (Pred == ICmpInst::ICMP_UGT) {
1669 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1670 if (*XorC == ~C && (C + 1).isPowerOf2())
1671 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
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_UGT, X, Y);
1675 }
1676 if (Pred == ICmpInst::ICMP_ULT) {
1677 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1678 if (*XorC == -C && C.isPowerOf2())
1679 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1680 ConstantInt::get(Ty: X->getType(), V: ~C));
1681 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1682 if (*XorC == C && (-C).isPowerOf2())
1683 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1684 ConstantInt::get(Ty: X->getType(), V: ~C));
1685 }
1686 return nullptr;
1687}
1688
1689/// For power-of-2 C:
1690/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1691/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1692Instruction *InstCombinerImpl::foldICmpXorShiftConst(ICmpInst &Cmp,
1693 BinaryOperator *Xor,
1694 const APInt &C) {
1695 CmpInst::Predicate Pred = Cmp.getPredicate();
1696 APInt PowerOf2;
1697 if (Pred == ICmpInst::ICMP_ULT)
1698 PowerOf2 = C;
1699 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1700 PowerOf2 = C + 1;
1701 else
1702 return nullptr;
1703 if (!PowerOf2.isPowerOf2())
1704 return nullptr;
1705 Value *X;
1706 const APInt *ShiftC;
1707 if (!match(V: Xor, P: m_OneUse(SubPattern: m_c_Xor(L: m_Value(V&: X),
1708 R: m_AShr(L: m_Deferred(V: X), R: m_APInt(Res&: ShiftC))))))
1709 return nullptr;
1710 uint64_t Shift = ShiftC->getLimitedValue();
1711 Type *XType = X->getType();
1712 if (Shift == 0 || PowerOf2.isMinSignedValue())
1713 return nullptr;
1714 Value *Add = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty: XType, V: PowerOf2));
1715 APInt Bound =
1716 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1717 return new ICmpInst(Pred, Add, ConstantInt::get(Ty: XType, V: Bound));
1718}
1719
1720/// Fold icmp (and (sh X, Y), C2), C1.
1721Instruction *InstCombinerImpl::foldICmpAndShift(ICmpInst &Cmp,
1722 BinaryOperator *And,
1723 const APInt &C1,
1724 const APInt &C2) {
1725 BinaryOperator *Shift = dyn_cast<BinaryOperator>(Val: And->getOperand(i_nocapture: 0));
1726 if (!Shift || !Shift->isShift())
1727 return nullptr;
1728
1729 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1730 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1731 // code produced by the clang front-end, for bitfield access.
1732 // This seemingly simple opportunity to fold away a shift turns out to be
1733 // rather complicated. See PR17827 for details.
1734 unsigned ShiftOpcode = Shift->getOpcode();
1735 bool IsShl = ShiftOpcode == Instruction::Shl;
1736 const APInt *C3;
1737 if (match(V: Shift->getOperand(i_nocapture: 1), P: m_APInt(Res&: C3))) {
1738 APInt NewAndCst, NewCmpCst;
1739 bool AnyCmpCstBitsShiftedOut;
1740 if (ShiftOpcode == Instruction::Shl) {
1741 // For a left shift, we can fold if the comparison is not signed. We can
1742 // also fold a signed comparison if the mask value and comparison value
1743 // are not negative. These constraints may not be obvious, but we can
1744 // prove that they are correct using an SMT solver.
1745 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1746 return nullptr;
1747
1748 NewCmpCst = C1.lshr(ShiftAmt: *C3);
1749 NewAndCst = C2.lshr(ShiftAmt: *C3);
1750 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(ShiftAmt: *C3) != C1;
1751 } else if (ShiftOpcode == Instruction::LShr) {
1752 // For a logical right shift, we can fold if the comparison is not signed.
1753 // We can also fold a signed comparison if the shifted mask value and the
1754 // shifted comparison value are not negative. These constraints may not be
1755 // obvious, but we can prove that they are correct using an SMT solver.
1756 NewCmpCst = C1.shl(ShiftAmt: *C3);
1757 NewAndCst = C2.shl(ShiftAmt: *C3);
1758 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(ShiftAmt: *C3) != C1;
1759 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1760 return nullptr;
1761 } else {
1762 // For an arithmetic shift, check that both constants don't use (in a
1763 // signed sense) the top bits being shifted out.
1764 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1765 NewCmpCst = C1.shl(ShiftAmt: *C3);
1766 NewAndCst = C2.shl(ShiftAmt: *C3);
1767 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(ShiftAmt: *C3) != C1;
1768 if (NewAndCst.ashr(ShiftAmt: *C3) != C2)
1769 return nullptr;
1770 }
1771
1772 if (AnyCmpCstBitsShiftedOut) {
1773 // If we shifted bits out, the fold is not going to work out. As a
1774 // special case, check to see if this means that the result is always
1775 // true or false now.
1776 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1777 return replaceInstUsesWith(I&: Cmp, V: ConstantInt::getFalse(Ty: Cmp.getType()));
1778 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1779 return replaceInstUsesWith(I&: Cmp, V: ConstantInt::getTrue(Ty: Cmp.getType()));
1780 } else {
1781 Value *NewAnd = Builder.CreateAnd(
1782 LHS: Shift->getOperand(i_nocapture: 0), RHS: ConstantInt::get(Ty: And->getType(), V: NewAndCst));
1783 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1784 ConstantInt::get(Ty: And->getType(), V: NewCmpCst));
1785 }
1786 }
1787
1788 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1789 // preferable because it allows the C2 << Y expression to be hoisted out of a
1790 // loop if Y is invariant and X is not.
1791 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1792 !Shift->isArithmeticShift() &&
1793 ((!IsShl && C2.isOne()) || !isa<Constant>(Val: Shift->getOperand(i_nocapture: 0)))) {
1794 // Compute C2 << Y.
1795 Value *NewShift =
1796 IsShl ? Builder.CreateLShr(LHS: And->getOperand(i_nocapture: 1), RHS: Shift->getOperand(i_nocapture: 1))
1797 : Builder.CreateShl(LHS: And->getOperand(i_nocapture: 1), RHS: Shift->getOperand(i_nocapture: 1));
1798
1799 // Compute X & (C2 << Y).
1800 Value *NewAnd = Builder.CreateAnd(LHS: Shift->getOperand(i_nocapture: 0), RHS: NewShift);
1801 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(i_nocapture: 1));
1802 }
1803
1804 return nullptr;
1805}
1806
1807/// Fold icmp (and X, C2), C1.
1808Instruction *InstCombinerImpl::foldICmpAndConstConst(ICmpInst &Cmp,
1809 BinaryOperator *And,
1810 const APInt &C1) {
1811 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1812
1813 // icmp ne (and X, 1), 0 --> trunc X to i1
1814 if (isICMP_NE && C1.isZero() && match(V: And->getOperand(i_nocapture: 1), P: m_One()))
1815 return new TruncInst(And->getOperand(i_nocapture: 0), Cmp.getType());
1816
1817 const APInt *C2;
1818 Value *X;
1819 if (!match(V: And, P: m_And(L: m_Value(V&: X), R: m_APInt(Res&: C2))))
1820 return nullptr;
1821
1822 // (and X, highmask) s> [0, ~highmask] --> X s> ~highmask
1823 if (Cmp.getPredicate() == ICmpInst::ICMP_SGT && C1.ule(RHS: ~*C2) &&
1824 C2->isNegatedPowerOf2())
1825 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1826 ConstantInt::get(Ty: X->getType(), V: ~*C2));
1827 // (and X, highmask) s< [1, -highmask] --> X s< -highmask
1828 if (Cmp.getPredicate() == ICmpInst::ICMP_SLT && !C1.isSignMask() &&
1829 (C1 - 1).ule(RHS: ~*C2) && C2->isNegatedPowerOf2() && !C2->isSignMask())
1830 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1831 ConstantInt::get(Ty: X->getType(), V: -*C2));
1832
1833 // Don't perform the following transforms if the AND has multiple uses
1834 if (!And->hasOneUse())
1835 return nullptr;
1836
1837 if (Cmp.isEquality() && C1.isZero()) {
1838 // Restrict this fold to single-use 'and' (PR10267).
1839 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1840 if (C2->isSignMask()) {
1841 Constant *Zero = Constant::getNullValue(Ty: X->getType());
1842 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1843 return new ICmpInst(NewPred, X, Zero);
1844 }
1845
1846 APInt NewC2 = *C2;
1847 KnownBits Know = computeKnownBits(V: And->getOperand(i_nocapture: 0), CtxI: And);
1848 // Set high zeros of C2 to allow matching negated power-of-2.
1849 NewC2 = *C2 | APInt::getHighBitsSet(numBits: C2->getBitWidth(),
1850 hiBitsSet: Know.countMinLeadingZeros());
1851
1852 // Restrict this fold only for single-use 'and' (PR10267).
1853 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1854 if (NewC2.isNegatedPowerOf2()) {
1855 Constant *NegBOC = ConstantInt::get(Ty: And->getType(), V: -NewC2);
1856 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1857 return new ICmpInst(NewPred, X, NegBOC);
1858 }
1859 }
1860
1861 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1862 // the input width without changing the value produced, eliminate the cast:
1863 //
1864 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1865 //
1866 // We can do this transformation if the constants do not have their sign bits
1867 // set or if it is an equality comparison. Extending a relational comparison
1868 // when we're checking the sign bit would not work.
1869 Value *W;
1870 if (match(V: And->getOperand(i_nocapture: 0), P: m_OneUse(SubPattern: m_Trunc(Op: m_Value(V&: W)))) &&
1871 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1872 // TODO: Is this a good transform for vectors? Wider types may reduce
1873 // throughput. Should this transform be limited (even for scalars) by using
1874 // shouldChangeType()?
1875 if (!Cmp.getType()->isVectorTy()) {
1876 Type *WideType = W->getType();
1877 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1878 Constant *ZextC1 = ConstantInt::get(Ty: WideType, V: C1.zext(width: WideScalarBits));
1879 Constant *ZextC2 = ConstantInt::get(Ty: WideType, V: C2->zext(width: WideScalarBits));
1880 Value *NewAnd = Builder.CreateAnd(LHS: W, RHS: ZextC2, Name: And->getName());
1881 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1882 }
1883 }
1884
1885 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, C2: *C2))
1886 return I;
1887
1888 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1889 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1890 //
1891 // iff pred isn't signed
1892 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(i_nocapture: 0)->hasOneUse() &&
1893 match(V: And->getOperand(i_nocapture: 1), P: m_One())) {
1894 Constant *One = cast<Constant>(Val: And->getOperand(i_nocapture: 1));
1895 Value *Or = And->getOperand(i_nocapture: 0);
1896 Value *A, *B, *LShr;
1897 if (match(V: Or, P: m_Or(L: m_Value(V&: LShr), R: m_Value(V&: A))) &&
1898 match(V: LShr, P: m_LShr(L: m_Specific(V: A), R: m_Value(V&: B)))) {
1899 unsigned UsesRemoved = 0;
1900 if (And->hasOneUse())
1901 ++UsesRemoved;
1902 if (Or->hasOneUse())
1903 ++UsesRemoved;
1904 if (LShr->hasOneUse())
1905 ++UsesRemoved;
1906
1907 // Compute A & ((1 << B) | 1)
1908 unsigned RequireUsesRemoved = match(V: B, P: m_ImmConstant()) ? 1 : 3;
1909 if (UsesRemoved >= RequireUsesRemoved) {
1910 Value *NewOr =
1911 Builder.CreateOr(LHS: Builder.CreateShl(LHS: One, RHS: B, Name: LShr->getName(),
1912 /*HasNUW=*/true),
1913 RHS: One, Name: Or->getName());
1914 Value *NewAnd = Builder.CreateAnd(LHS: A, RHS: NewOr, Name: And->getName());
1915 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(i_nocapture: 1));
1916 }
1917 }
1918 }
1919
1920 // (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->
1921 // llvm.is.fpclass(X, fcInf|fcNan)
1922 // (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->
1923 // llvm.is.fpclass(X, ~(fcInf|fcNan))
1924 // (icmp eq (and (bitcast X to int), ExponentMask), 0) -->
1925 // llvm.is.fpclass(X, fcSubnormal|fcZero)
1926 // (icmp ne (and (bitcast X to int), ExponentMask), 0) -->
1927 // llvm.is.fpclass(X, ~(fcSubnormal|fcZero))
1928 Value *V;
1929 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1930 Kind: Attribute::NoImplicitFloat) &&
1931 Cmp.isEquality() &&
1932 match(V: X, P: m_OneUse(SubPattern: m_ElementWiseBitCast(Op: m_Value(V))))) {
1933 Type *FPType = V->getType()->getScalarType();
1934 if (FPType->isIEEELikeFPTy() && (C1.isZero() || C1 == *C2)) {
1935 APInt ExponentMask =
1936 APFloat::getInf(Sem: FPType->getFltSemantics()).bitcastToAPInt();
1937 if (*C2 == ExponentMask) {
1938 unsigned Mask = C1.isZero()
1939 ? FPClassTest::fcZero | FPClassTest::fcSubnormal
1940 : FPClassTest::fcNan | FPClassTest::fcInf;
1941 if (isICMP_NE)
1942 Mask = ~Mask & fcAllFlags;
1943 return replaceInstUsesWith(I&: Cmp, V: Builder.createIsFPClass(FPNum: V, Test: Mask));
1944 }
1945 }
1946 }
1947
1948 return nullptr;
1949}
1950
1951/// Fold icmp (and X, Y), C.
1952Instruction *InstCombinerImpl::foldICmpAndConstant(ICmpInst &Cmp,
1953 BinaryOperator *And,
1954 const APInt &C) {
1955 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C1: C))
1956 return I;
1957
1958 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1959 bool TrueIfNeg;
1960 if (isSignBitCheck(Pred, RHS: C, TrueIfSigned&: TrueIfNeg)) {
1961 // ((X - 1) & ~X) < 0 --> X == 0
1962 // ((X - 1) & ~X) >= 0 --> X != 0
1963 Value *X;
1964 if (match(V: And->getOperand(i_nocapture: 0), P: m_Add(L: m_Value(V&: X), R: m_AllOnes())) &&
1965 match(V: And->getOperand(i_nocapture: 1), P: m_Not(V: m_Specific(V: X)))) {
1966 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1967 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(Ty: X->getType()));
1968 }
1969 // (X & -X) < 0 --> X == MinSignedC
1970 // (X & -X) > -1 --> X != MinSignedC
1971 if (match(V: And, P: m_c_And(L: m_Neg(V: m_Value(V&: X)), R: m_Deferred(V: X)))) {
1972 Constant *MinSignedC = ConstantInt::get(
1973 Ty: X->getType(),
1974 V: APInt::getSignedMinValue(numBits: X->getType()->getScalarSizeInBits()));
1975 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1976 return new ICmpInst(NewPred, X, MinSignedC);
1977 }
1978 }
1979
1980 // TODO: These all require that Y is constant too, so refactor with the above.
1981
1982 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1983 Value *X = And->getOperand(i_nocapture: 0);
1984 Value *Y = And->getOperand(i_nocapture: 1);
1985 if (auto *C2 = dyn_cast<ConstantInt>(Val: Y))
1986 if (auto *LI = dyn_cast<LoadInst>(Val: X))
1987 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: LI->getOperand(i_nocapture: 0)))
1988 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(LI, GEP, ICI&: Cmp, AndCst: C2))
1989 return Res;
1990
1991 if (!Cmp.isEquality())
1992 return nullptr;
1993
1994 // (X & -X) == 0 --> X == 0
1995 // (X & -X) != 0 --> X != 0
1996 // (X & -X) == 1 --> trunc X to i1
1997 // (X & -X) != 1 --> !(trunc X to i1)
1998 // Cmp is == or != by the check above.
1999 Value *MatchedX;
2000 // Match X & -X in either operand order.
2001 if (C.getBitWidth() > 1 && (C.isZero() || C.isOne()) &&
2002 match(V: And, P: m_c_And(L: m_Neg(V: m_Value(V&: MatchedX)), R: m_Deferred(V: MatchedX)))) {
2003 // Preserve the predicate: (X & -X) ==/!= 0 --> X ==/!= 0.
2004 if (C.isZero())
2005 return new ICmpInst(Pred, MatchedX, Cmp.getOperand(i_nocapture: 1));
2006
2007 // (X & -X) == 1 iff the low bit of X is set.
2008 if (Pred == CmpInst::ICMP_EQ)
2009 return new TruncInst(MatchedX, Cmp.getType());
2010
2011 // The remaining case needs a trunc and not. Require the original and
2012 // to become dead to avoid increasing the instruction count.
2013 if (And->hasOneUse()) {
2014 Value *Trunc = Builder.CreateTrunc(V: MatchedX, DestTy: Cmp.getType());
2015 return BinaryOperator::CreateNot(Op: Trunc);
2016 }
2017 }
2018
2019 // X & -C == -C -> X > u ~C
2020 // X & -C != -C -> X <= u ~C
2021 // iff C is a power of 2
2022 if (Cmp.getOperand(i_nocapture: 1) == Y && C.isNegatedPowerOf2()) {
2023 auto NewPred =
2024 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT : CmpInst::ICMP_ULE;
2025 return new ICmpInst(NewPred, X, SubOne(C: cast<Constant>(Val: Cmp.getOperand(i_nocapture: 1))));
2026 }
2027
2028 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
2029 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
2030 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
2031 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
2032 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)))) &&
2033 X->getType()->isIntOrIntVectorTy(BitWidth: 1) && (C.isZero() || C.isOne())) {
2034 Value *TruncY = Builder.CreateTrunc(V: Y, DestTy: X->getType());
2035 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
2036 Value *And = Builder.CreateAnd(LHS: TruncY, RHS: X);
2037 return BinaryOperator::CreateNot(Op: And);
2038 }
2039 return BinaryOperator::CreateAnd(V1: TruncY, V2: X);
2040 }
2041
2042 // (icmp eq/ne (and (shl -1, X), Y), 0)
2043 // -> (icmp eq/ne (lshr Y, X), 0)
2044 // We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems
2045 // highly unlikely the non-zero case will ever show up in code.
2046 if (C.isZero() &&
2047 match(V: And, P: m_OneUse(SubPattern: m_c_And(L: m_OneUse(SubPattern: m_Shl(L: m_AllOnes(), R: m_Value(V&: X))),
2048 R: m_Value(V&: Y))))) {
2049 Value *LShr = Builder.CreateLShr(LHS: Y, RHS: X);
2050 return new ICmpInst(Pred, LShr, Constant::getNullValue(Ty: LShr->getType()));
2051 }
2052
2053 // (icmp eq/ne (and (add A, Addend), Msk), C)
2054 // -> (icmp eq/ne (and A, Msk), (and (sub C, Addend), Msk))
2055 {
2056 Value *A;
2057 const APInt *Addend, *Msk;
2058 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))),
2059 R: m_LowBitMask(V&: Msk)))) &&
2060 C.ule(RHS: *Msk)) {
2061 APInt NewComperand = (C - *Addend) & *Msk;
2062 Value *MaskA = Builder.CreateAnd(LHS: A, RHS: ConstantInt::get(Ty: A->getType(), V: *Msk));
2063 return new ICmpInst(Pred, MaskA,
2064 ConstantInt::get(Ty: MaskA->getType(), V: NewComperand));
2065 }
2066 }
2067
2068 return nullptr;
2069}
2070
2071/// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
2072static Value *foldICmpOrXorSubChain(ICmpInst &Cmp, BinaryOperator *Or,
2073 InstCombiner::BuilderTy &Builder) {
2074 // Are we using xors or subs to bitwise check for a pair or pairs of
2075 // (in)equalities? Convert to a shorter form that has more potential to be
2076 // folded even further.
2077 // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
2078 // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
2079 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
2080 // (X1 == X2) && (X3 == X4) && (X5 == X6)
2081 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
2082 // (X1 != X2) || (X3 != X4) || (X5 != X6)
2083 SmallVector<std::pair<Value *, Value *>, 2> CmpValues;
2084 SmallVector<Value *, 16> WorkList(1, Or);
2085
2086 while (!WorkList.empty()) {
2087 auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
2088 Value *Lhs, *Rhs;
2089
2090 if (match(V: OrOperatorArgument,
2091 P: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: Lhs), R: m_Value(V&: Rhs))))) {
2092 CmpValues.emplace_back(Args&: Lhs, Args&: Rhs);
2093 return;
2094 }
2095
2096 if (match(V: OrOperatorArgument,
2097 P: m_OneUse(SubPattern: m_Sub(L: m_Value(V&: Lhs), R: m_Value(V&: Rhs))))) {
2098 CmpValues.emplace_back(Args&: Lhs, Args&: Rhs);
2099 return;
2100 }
2101
2102 WorkList.push_back(Elt: OrOperatorArgument);
2103 };
2104
2105 Value *CurrentValue = WorkList.pop_back_val();
2106 Value *OrOperatorLhs, *OrOperatorRhs;
2107
2108 if (!match(V: CurrentValue,
2109 P: m_Or(L: m_Value(V&: OrOperatorLhs), R: m_Value(V&: OrOperatorRhs)))) {
2110 return nullptr;
2111 }
2112
2113 MatchOrOperatorArgument(OrOperatorRhs);
2114 MatchOrOperatorArgument(OrOperatorLhs);
2115 }
2116
2117 ICmpInst::Predicate Pred = Cmp.getPredicate();
2118 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2119 Value *LhsCmp = Builder.CreateICmp(P: Pred, LHS: CmpValues.rbegin()->first,
2120 RHS: CmpValues.rbegin()->second);
2121
2122 for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
2123 Value *RhsCmp = Builder.CreateICmp(P: Pred, LHS: It->first, RHS: It->second);
2124 LhsCmp = Builder.CreateBinOp(Opc: BOpc, LHS: LhsCmp, RHS: RhsCmp);
2125 }
2126
2127 return LhsCmp;
2128}
2129
2130/// Fold icmp (or X, Y), C.
2131Instruction *InstCombinerImpl::foldICmpOrConstant(ICmpInst &Cmp,
2132 BinaryOperator *Or,
2133 const APInt &C) {
2134 ICmpInst::Predicate Pred = Cmp.getPredicate();
2135 if (C.isOne()) {
2136 // icmp slt signum(V) 1 --> icmp slt V, 1
2137 Value *V = nullptr;
2138 if (Pred == ICmpInst::ICMP_SLT && match(V: Or, P: m_Signum(V: m_Value(V))))
2139 return new ICmpInst(ICmpInst::ICMP_SLT, V,
2140 ConstantInt::get(Ty: V->getType(), V: 1));
2141 }
2142
2143 Value *OrOp0 = Or->getOperand(i_nocapture: 0), *OrOp1 = Or->getOperand(i_nocapture: 1);
2144
2145 // (icmp eq/ne (or disjoint x, C0), C1)
2146 // -> (icmp eq/ne x, C0^C1)
2147 if (Cmp.isEquality() && match(V: OrOp1, P: m_ImmConstant()) &&
2148 cast<PossiblyDisjointInst>(Val: Or)->isDisjoint()) {
2149 Value *NewC =
2150 Builder.CreateXor(LHS: OrOp1, RHS: ConstantInt::get(Ty: OrOp1->getType(), V: C));
2151 return new ICmpInst(Pred, OrOp0, NewC);
2152 }
2153
2154 const APInt *MaskC;
2155 if (match(V: OrOp1, P: m_APInt(Res&: MaskC)) && Cmp.isEquality()) {
2156 if (*MaskC == C && (C + 1).isPowerOf2()) {
2157 // X | C == C --> X <=u C
2158 // X | C != C --> X >u C
2159 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
2160 Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT;
2161 return new ICmpInst(Pred, OrOp0, OrOp1);
2162 }
2163
2164 // More general: canonicalize 'equality with set bits mask' to
2165 // 'equality with clear bits mask'.
2166 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2167 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2168 if (Or->hasOneUse()) {
2169 Value *And = Builder.CreateAnd(LHS: OrOp0, RHS: ~(*MaskC));
2170 Constant *NewC = ConstantInt::get(Ty: Or->getType(), V: C ^ (*MaskC));
2171 return new ICmpInst(Pred, And, NewC);
2172 }
2173 }
2174
2175 // (X | (X-1)) s< 0 --> X s< 1
2176 // (X | (X-1)) s> -1 --> X s> 0
2177 Value *X;
2178 bool TrueIfSigned;
2179 if (isSignBitCheck(Pred, RHS: C, TrueIfSigned) &&
2180 match(V: Or, P: m_c_Or(L: m_Add(L: m_Value(V&: X), R: m_AllOnes()), R: m_Deferred(V: X)))) {
2181 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2182 Constant *NewC = ConstantInt::get(Ty: X->getType(), V: TrueIfSigned ? 1 : 0);
2183 return new ICmpInst(NewPred, X, NewC);
2184 }
2185
2186 const APInt *OrC;
2187 // icmp(X | OrC, C) --> icmp(X, 0)
2188 if (C.isNonNegative() && match(V: Or, P: m_Or(L: m_Value(V&: X), R: m_APInt(Res&: OrC)))) {
2189 switch (Pred) {
2190 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2191 case ICmpInst::ICMP_SLT:
2192 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2193 case ICmpInst::ICMP_SGE:
2194 if (OrC->sge(RHS: C))
2195 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: X->getType()));
2196 break;
2197 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2198 case ICmpInst::ICMP_SLE:
2199 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2200 case ICmpInst::ICMP_SGT:
2201 if (OrC->sgt(RHS: C))
2202 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), X,
2203 ConstantInt::getNullValue(Ty: X->getType()));
2204 break;
2205 default:
2206 break;
2207 }
2208 }
2209
2210 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2211 return nullptr;
2212
2213 Value *P, *Q;
2214 if (match(V: Or, P: m_Or(L: m_PtrToInt(Op: m_Value(V&: P)), R: m_PtrToInt(Op: m_Value(V&: Q))))) {
2215 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2216 // -> and (icmp eq P, null), (icmp eq Q, null).
2217 Value *CmpP =
2218 Builder.CreateICmp(P: Pred, LHS: P, RHS: ConstantInt::getNullValue(Ty: P->getType()));
2219 Value *CmpQ =
2220 Builder.CreateICmp(P: Pred, LHS: Q, RHS: ConstantInt::getNullValue(Ty: Q->getType()));
2221 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2222 return BinaryOperator::Create(Op: BOpc, S1: CmpP, S2: CmpQ);
2223 }
2224
2225 if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2226 return replaceInstUsesWith(I&: Cmp, V);
2227
2228 return nullptr;
2229}
2230
2231/// Fold icmp (mul X, Y), C.
2232Instruction *InstCombinerImpl::foldICmpMulConstant(ICmpInst &Cmp,
2233 BinaryOperator *Mul,
2234 const APInt &C) {
2235 ICmpInst::Predicate Pred = Cmp.getPredicate();
2236 Type *MulTy = Mul->getType();
2237 Value *X = Mul->getOperand(i_nocapture: 0);
2238
2239 // If comparing a square with a constant, try simplifying to comparing square
2240 // roots.
2241 if (X == Mul->getOperand(i_nocapture: 1) && !Cmp.isSigned()) {
2242 APInt R = C.sqrtFloor();
2243 bool IsSqr = C == R * R;
2244
2245 // X * X eq/ne C
2246 if (Cmp.isEquality() &&
2247 (Mul->hasNoUnsignedWrap() || (Mul->hasNoSignedWrap() && C.isZero()))) {
2248
2249 // If constant is not a square, eq/ne is false/true respectively
2250 if (!IsSqr)
2251 return replaceInstUsesWith(
2252 I&: Cmp,
2253 V: ConstantInt::getBool(Ty: Cmp.getType(), V: Pred == ICmpInst::ICMP_NE));
2254
2255 return new ICmpInst(Pred, X, ConstantInt::get(Ty: MulTy, V: R));
2256 }
2257
2258 // If the multiply does not wrap
2259 // X * X pred C --> X pred R
2260 if (Mul->hasNoUnsignedWrap()) {
2261
2262 if (IsSqr)
2263 return new ICmpInst(Pred, X, ConstantInt::get(Ty: MulTy, V: R));
2264
2265 // If C is not a square, we use floor/ceil of sqrt(C).
2266 //
2267 // If LT or LE, we need R to be an overestimate of sqrt(C),
2268 // then use the strict predicate (LT->LT, LE->LT).
2269 //
2270 // If GT or GE, we need R to be an underestimate of sqrt(C),
2271 // then use the strict predicate (GT->GT, GE->GT).
2272 //
2273 // R is already an underestimate of sqrt(C) due to sqrtFloor.
2274 if (ICmpInst::isLT(P: Pred) || ICmpInst::isLE(P: Pred))
2275 ++R;
2276
2277 return new ICmpInst(Cmp.getStrictPredicate(), X,
2278 ConstantInt::get(Ty: MulTy, V: R));
2279 }
2280 }
2281
2282 const APInt *MulC;
2283 if (!match(V: Mul->getOperand(i_nocapture: 1), P: m_APInt(Res&: MulC)))
2284 return nullptr;
2285
2286 // If this is a test of the sign bit and the multiply is sign-preserving with
2287 // a constant operand, use the multiply LHS operand instead:
2288 // (X * +MulC) < 0 --> X < 0
2289 // (X * -MulC) < 0 --> X > 0
2290 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2291 if (MulC->isNegative())
2292 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
2293 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: MulTy));
2294 }
2295
2296 if (MulC->isZero())
2297 return nullptr;
2298
2299 // If the multiply does not wrap or the constant is odd, try to divide the
2300 // compare constant by the multiplication factor.
2301 if (Cmp.isEquality()) {
2302 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2303 if (Mul->hasNoSignedWrap() && C.srem(RHS: *MulC).isZero()) {
2304 Constant *NewC = ConstantInt::get(Ty: MulTy, V: C.sdiv(RHS: *MulC));
2305 return new ICmpInst(Pred, X, NewC);
2306 }
2307
2308 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2309 // correct to transform if MulC * N == C including overflow. I.e with i8
2310 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2311 // miss that case.
2312 if (C.urem(RHS: *MulC).isZero()) {
2313 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2314 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2315 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2316 Constant *NewC = ConstantInt::get(Ty: MulTy, V: C.udiv(RHS: *MulC));
2317 return new ICmpInst(Pred, X, NewC);
2318 }
2319 }
2320 }
2321
2322 // With a matching no-overflow guarantee, fold the constants:
2323 // (X * MulC) < C --> X < (C / MulC)
2324 // (X * MulC) > C --> X > (C / MulC)
2325 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2326 Constant *NewC = nullptr;
2327 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2328 // MININT / -1 --> overflow.
2329 if (C.isMinSignedValue() && MulC->isAllOnes())
2330 return nullptr;
2331 if (MulC->isNegative())
2332 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
2333
2334 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2335 NewC = ConstantInt::get(
2336 Ty: MulTy, V: APIntOps::RoundingSDiv(A: C, B: *MulC, RM: APInt::Rounding::UP));
2337 } else {
2338 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2339 "Unexpected predicate");
2340 NewC = ConstantInt::get(
2341 Ty: MulTy, V: APIntOps::RoundingSDiv(A: C, B: *MulC, RM: APInt::Rounding::DOWN));
2342 }
2343 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2344 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2345 NewC = ConstantInt::get(
2346 Ty: MulTy, V: APIntOps::RoundingUDiv(A: C, B: *MulC, RM: APInt::Rounding::UP));
2347 } else {
2348 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2349 "Unexpected predicate");
2350 NewC = ConstantInt::get(
2351 Ty: MulTy, V: APIntOps::RoundingUDiv(A: C, B: *MulC, RM: APInt::Rounding::DOWN));
2352 }
2353 }
2354
2355 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2356}
2357
2358/// Fold icmp (shl nuw C2, Y), C.
2359static Instruction *foldICmpShlLHSC(ICmpInst &Cmp, Instruction *Shl,
2360 const APInt &C) {
2361 Value *Y;
2362 const APInt *C2;
2363 if (!match(V: Shl, P: m_NUWShl(L: m_APInt(Res&: C2), R: m_Value(V&: Y))))
2364 return nullptr;
2365
2366 Type *ShiftType = Shl->getType();
2367 unsigned TypeBits = C.getBitWidth();
2368 ICmpInst::Predicate Pred = Cmp.getPredicate();
2369 if (Cmp.isUnsigned()) {
2370 if (C2->isZero() || C2->ugt(RHS: C))
2371 return nullptr;
2372 APInt Div, Rem;
2373 APInt::udivrem(LHS: C, RHS: *C2, Quotient&: Div, Remainder&: Rem);
2374 bool CIsPowerOf2 = Rem.isZero() && Div.isPowerOf2();
2375
2376 // (1 << Y) pred C -> Y pred Log2(C)
2377 if (!CIsPowerOf2) {
2378 // (1 << Y) < 30 -> Y <= 4
2379 // (1 << Y) <= 30 -> Y <= 4
2380 // (1 << Y) >= 30 -> Y > 4
2381 // (1 << Y) > 30 -> Y > 4
2382 if (Pred == ICmpInst::ICMP_ULT)
2383 Pred = ICmpInst::ICMP_ULE;
2384 else if (Pred == ICmpInst::ICMP_UGE)
2385 Pred = ICmpInst::ICMP_UGT;
2386 }
2387
2388 unsigned CLog2 = Div.logBase2();
2389 return new ICmpInst(Pred, Y, ConstantInt::get(Ty: ShiftType, V: CLog2));
2390 } else if (Cmp.isSigned() && C2->isOne()) {
2391 Constant *BitWidthMinusOne = ConstantInt::get(Ty: ShiftType, V: TypeBits - 1);
2392 // (1 << Y) > 0 -> Y != 31
2393 // (1 << Y) > C -> Y != 31 if C is negative.
2394 if (Pred == ICmpInst::ICMP_SGT && C.sle(RHS: 0))
2395 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2396
2397 // (1 << Y) < 0 -> Y == 31
2398 // (1 << Y) < 1 -> Y == 31
2399 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2400 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2401 if (Pred == ICmpInst::ICMP_SLT && (C - 1).sle(RHS: 0))
2402 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2403 }
2404
2405 return nullptr;
2406}
2407
2408/// Fold icmp (shl X, Y), C.
2409Instruction *InstCombinerImpl::foldICmpShlConstant(ICmpInst &Cmp,
2410 BinaryOperator *Shl,
2411 const APInt &C) {
2412 const APInt *ShiftVal;
2413 if (Cmp.isEquality() && match(V: Shl->getOperand(i_nocapture: 0), P: m_APInt(Res&: ShiftVal)))
2414 return foldICmpShlConstConst(I&: Cmp, A: Shl->getOperand(i_nocapture: 1), AP1: C, AP2: *ShiftVal);
2415
2416 ICmpInst::Predicate Pred = Cmp.getPredicate();
2417 // (icmp pred (shl nuw&nsw X, Y), Csle0)
2418 // -> (icmp pred X, Csle0)
2419 //
2420 // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2421 // so X's must be what is used.
2422 if (C.sle(RHS: 0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2423 return new ICmpInst(Pred, Shl->getOperand(i_nocapture: 0), Cmp.getOperand(i_nocapture: 1));
2424
2425 // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2426 // -> (icmp eq/ne X, 0)
2427 if (ICmpInst::isEquality(P: Pred) && C.isZero() &&
2428 (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2429 return new ICmpInst(Pred, Shl->getOperand(i_nocapture: 0), Cmp.getOperand(i_nocapture: 1));
2430
2431 // (icmp slt (shl nsw X, Y), 0/1)
2432 // -> (icmp slt X, 0/1)
2433 // (icmp sgt (shl nsw X, Y), 0/-1)
2434 // -> (icmp sgt X, 0/-1)
2435 //
2436 // NB: sge/sle with a constant will canonicalize to sgt/slt.
2437 if (Shl->hasNoSignedWrap() &&
2438 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2439 if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2440 return new ICmpInst(Pred, Shl->getOperand(i_nocapture: 0), Cmp.getOperand(i_nocapture: 1));
2441
2442 const APInt *ShiftAmt;
2443 if (!match(V: Shl->getOperand(i_nocapture: 1), P: m_APInt(Res&: ShiftAmt)))
2444 return foldICmpShlLHSC(Cmp, Shl, C);
2445
2446 // Check that the shift amount is in range. If not, don't perform undefined
2447 // shifts. When the shift is visited, it will be simplified.
2448 unsigned TypeBits = C.getBitWidth();
2449 if (ShiftAmt->uge(RHS: TypeBits))
2450 return nullptr;
2451
2452 Value *X = Shl->getOperand(i_nocapture: 0);
2453 Type *ShType = Shl->getType();
2454
2455 // NSW guarantees that we are only shifting out sign bits from the high bits,
2456 // so we can ASHR the compare constant without needing a mask and eliminate
2457 // the shift.
2458 if (Shl->hasNoSignedWrap()) {
2459 if (Pred == ICmpInst::ICMP_SGT) {
2460 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2461 APInt ShiftedC = C.ashr(ShiftAmt: *ShiftAmt);
2462 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2463 }
2464 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2465 C.ashr(ShiftAmt: *ShiftAmt).shl(ShiftAmt: *ShiftAmt) == C) {
2466 APInt ShiftedC = C.ashr(ShiftAmt: *ShiftAmt);
2467 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2468 }
2469 if (Pred == ICmpInst::ICMP_SLT) {
2470 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2471 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2472 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2473 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2474 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2475 APInt ShiftedC = (C - 1).ashr(ShiftAmt: *ShiftAmt) + 1;
2476 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2477 }
2478 }
2479
2480 // NUW guarantees that we are only shifting out zero bits from the high bits,
2481 // so we can LSHR the compare constant without needing a mask and eliminate
2482 // the shift.
2483 if (Shl->hasNoUnsignedWrap()) {
2484 if (Pred == ICmpInst::ICMP_UGT) {
2485 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2486 APInt ShiftedC = C.lshr(ShiftAmt: *ShiftAmt);
2487 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2488 }
2489 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2490 C.lshr(ShiftAmt: *ShiftAmt).shl(ShiftAmt: *ShiftAmt) == C) {
2491 APInt ShiftedC = C.lshr(ShiftAmt: *ShiftAmt);
2492 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2493 }
2494 if (Pred == ICmpInst::ICMP_ULT) {
2495 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2496 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2497 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2498 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2499 assert(C.ugt(0) && "ult 0 should have been eliminated");
2500 APInt ShiftedC = (C - 1).lshr(ShiftAmt: *ShiftAmt) + 1;
2501 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2502 }
2503 }
2504
2505 if (Cmp.isEquality() && Shl->hasOneUse()) {
2506 // Strength-reduce the shift into an 'and'.
2507 Constant *Mask = ConstantInt::get(
2508 Ty: ShType,
2509 V: APInt::getLowBitsSet(numBits: TypeBits, loBitsSet: TypeBits - ShiftAmt->getZExtValue()));
2510 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask, Name: Shl->getName() + ".mask");
2511 Constant *LShrC = ConstantInt::get(Ty: ShType, V: C.lshr(ShiftAmt: *ShiftAmt));
2512 return new ICmpInst(Pred, And, LShrC);
2513 }
2514
2515 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2516 bool TrueIfSigned = false;
2517 if (Shl->hasOneUse() && isSignBitCheck(Pred, RHS: C, TrueIfSigned)) {
2518 // (X << 31) <s 0 --> (X & 1) != 0
2519 Constant *Mask = ConstantInt::get(
2520 Ty: ShType,
2521 V: APInt::getOneBitSet(numBits: TypeBits, BitNo: TypeBits - ShiftAmt->getZExtValue() - 1));
2522 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask, Name: Shl->getName() + ".mask");
2523 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2524 And, Constant::getNullValue(Ty: ShType));
2525 }
2526
2527 // Simplify 'shl' inequality test into 'and' equality test.
2528 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2529 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2530 if ((C + 1).isPowerOf2() &&
2531 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2532 Value *And = Builder.CreateAnd(LHS: X, RHS: (~C).lshr(shiftAmt: ShiftAmt->getZExtValue()));
2533 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2534 : ICmpInst::ICMP_NE,
2535 And, Constant::getNullValue(Ty: ShType));
2536 }
2537 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2538 if (C.isPowerOf2() &&
2539 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2540 Value *And =
2541 Builder.CreateAnd(LHS: X, RHS: (~(C - 1)).lshr(shiftAmt: ShiftAmt->getZExtValue()));
2542 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2543 : ICmpInst::ICMP_NE,
2544 And, Constant::getNullValue(Ty: ShType));
2545 }
2546 }
2547
2548 // Transform (icmp pred iM (shl iM %v, N), C)
2549 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2550 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2551 // This enables us to get rid of the shift in favor of a trunc that may be
2552 // free on the target. It has the additional benefit of comparing to a
2553 // smaller constant that may be more target-friendly.
2554 unsigned Amt = ShiftAmt->getLimitedValue(Limit: TypeBits - 1);
2555 if (Shl->hasOneUse() && Amt != 0 &&
2556 shouldChangeType(FromBitWidth: ShType->getScalarSizeInBits(), ToBitWidth: TypeBits - Amt)) {
2557 ICmpInst::Predicate CmpPred = Pred;
2558 APInt RHSC = C;
2559
2560 if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(predicate: CmpPred)) {
2561 // Try the flipped strictness predicate.
2562 // e.g.:
2563 // icmp ult i64 (shl X, 32), 8589934593 ->
2564 // icmp ule i64 (shl X, 32), 8589934592 ->
2565 // icmp ule i32 (trunc X, i32), 2 ->
2566 // icmp ult i32 (trunc X, i32), 3
2567 if (auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(
2568 Pred, C: ConstantInt::get(Context&: ShType->getContext(), V: C))) {
2569 CmpPred = FlippedStrictness->first;
2570 RHSC = cast<ConstantInt>(Val: FlippedStrictness->second)->getValue();
2571 }
2572 }
2573
2574 if (RHSC.countr_zero() >= Amt) {
2575 Type *TruncTy = ShType->getWithNewBitWidth(NewBitWidth: TypeBits - Amt);
2576 Constant *NewC =
2577 ConstantInt::get(Ty: TruncTy, V: RHSC.ashr(ShiftAmt: *ShiftAmt).trunc(width: TypeBits - Amt));
2578 return new ICmpInst(CmpPred,
2579 Builder.CreateTrunc(V: X, DestTy: TruncTy, Name: "", /*IsNUW=*/false,
2580 IsNSW: Shl->hasNoSignedWrap()),
2581 NewC);
2582 }
2583 }
2584
2585 return nullptr;
2586}
2587
2588/// Fold icmp ({al}shr X, Y), C.
2589Instruction *InstCombinerImpl::foldICmpShrConstant(ICmpInst &Cmp,
2590 BinaryOperator *Shr,
2591 const APInt &C) {
2592 // An exact shr only shifts out zero bits, so:
2593 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2594 Value *X = Shr->getOperand(i_nocapture: 0);
2595 CmpInst::Predicate Pred = Cmp.getPredicate();
2596 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2597 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
2598
2599 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2600 const APInt *ShiftValC;
2601 if (match(V: X, P: m_APInt(Res&: ShiftValC))) {
2602 if (Cmp.isEquality())
2603 return foldICmpShrConstConst(I&: Cmp, A: Shr->getOperand(i_nocapture: 1), AP1: C, AP2: *ShiftValC);
2604
2605 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2606 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2607 bool TrueIfSigned;
2608 if (!IsAShr && ShiftValC->isNegative() &&
2609 isSignBitCheck(Pred, RHS: C, TrueIfSigned))
2610 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2611 Shr->getOperand(i_nocapture: 1),
2612 ConstantInt::getNullValue(Ty: X->getType()));
2613
2614 // If the shifted constant is a power-of-2, test the shift amount directly:
2615 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2616 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2617 if (!IsAShr && ShiftValC->isPowerOf2() &&
2618 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2619 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2620 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2621 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2622
2623 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2624 unsigned ShiftLZ = ShiftValC->countl_zero();
2625 Constant *NewC = ConstantInt::get(Ty: Shr->getType(), V: CmpLZ - ShiftLZ);
2626 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2627 return new ICmpInst(NewPred, Shr->getOperand(i_nocapture: 1), NewC);
2628 }
2629 }
2630
2631 const APInt *ShiftAmtC;
2632 if (!match(V: Shr->getOperand(i_nocapture: 1), P: m_APInt(Res&: ShiftAmtC)))
2633 return nullptr;
2634
2635 // Check that the shift amount is in range. If not, don't perform undefined
2636 // shifts. When the shift is visited it will be simplified.
2637 unsigned TypeBits = C.getBitWidth();
2638 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(Limit: TypeBits);
2639 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2640 return nullptr;
2641
2642 bool IsExact = Shr->isExact();
2643 Type *ShrTy = Shr->getType();
2644 // TODO: If we could guarantee that InstSimplify would handle all of the
2645 // constant-value-based preconditions in the folds below, then we could assert
2646 // those conditions rather than checking them. This is difficult because of
2647 // undef/poison (PR34838).
2648 if (IsAShr && Shr->hasOneUse()) {
2649 if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&
2650 (C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {
2651 // When C - 1 is a power of two and the transform can be legally
2652 // performed, prefer this form so the produced constant is close to a
2653 // power of two.
2654 // icmp slt/ult (ashr exact X, ShAmtC), C
2655 // --> icmp slt/ult X, (C - 1) << ShAmtC) + 1
2656 APInt ShiftedC = (C - 1).shl(shiftAmt: ShAmtVal) + 1;
2657 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2658 }
2659 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2660 // When ShAmtC can be shifted losslessly:
2661 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2662 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2663 APInt ShiftedC = C.shl(shiftAmt: ShAmtVal);
2664 if (ShiftedC.ashr(ShiftAmt: ShAmtVal) == C)
2665 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2666 }
2667 if (Pred == CmpInst::ICMP_SGT) {
2668 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2669 APInt ShiftedC = (C + 1).shl(shiftAmt: ShAmtVal) - 1;
2670 if (!C.isMaxSignedValue() && !(C + 1).shl(shiftAmt: ShAmtVal).isMinSignedValue() &&
2671 (ShiftedC + 1).ashr(ShiftAmt: ShAmtVal) == (C + 1))
2672 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2673 }
2674 if (Pred == CmpInst::ICMP_UGT) {
2675 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2676 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2677 // clause accounts for that pattern.
2678 APInt ShiftedC = (C + 1).shl(shiftAmt: ShAmtVal) - 1;
2679 if ((ShiftedC + 1).ashr(ShiftAmt: ShAmtVal) == (C + 1) ||
2680 (C + 1).shl(shiftAmt: ShAmtVal).isMinSignedValue())
2681 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2682 }
2683
2684 // If the compare constant has significant bits above the lowest sign-bit,
2685 // then convert an unsigned cmp to a test of the sign-bit:
2686 // (ashr X, ShiftC) u> C --> X s< 0
2687 // (ashr X, ShiftC) u< C --> X s> -1
2688 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2689 if (Pred == CmpInst::ICMP_UGT) {
2690 return new ICmpInst(CmpInst::ICMP_SLT, X,
2691 ConstantInt::getNullValue(Ty: ShrTy));
2692 }
2693 if (Pred == CmpInst::ICMP_ULT) {
2694 return new ICmpInst(CmpInst::ICMP_SGT, X,
2695 ConstantInt::getAllOnesValue(Ty: ShrTy));
2696 }
2697 }
2698 } else if (!IsAShr) {
2699 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2700 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2701 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2702 APInt ShiftedC = C.shl(shiftAmt: ShAmtVal);
2703 if (ShiftedC.lshr(shiftAmt: ShAmtVal) == C)
2704 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2705 }
2706 if (Pred == CmpInst::ICMP_UGT) {
2707 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2708 APInt ShiftedC = (C + 1).shl(shiftAmt: ShAmtVal) - 1;
2709 if ((ShiftedC + 1).lshr(shiftAmt: ShAmtVal) == (C + 1))
2710 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2711 }
2712 }
2713
2714 if (!Cmp.isEquality())
2715 return nullptr;
2716
2717 // Handle equality comparisons of shift-by-constant.
2718
2719 // If the comparison constant changes with the shift, the comparison cannot
2720 // succeed (bits of the comparison constant cannot match the shifted value).
2721 // This should be known by InstSimplify and already be folded to true/false.
2722 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2723 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2724 "Expected icmp+shr simplify did not occur.");
2725
2726 // If the bits shifted out are known zero, compare the unshifted value:
2727 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2728 if (Shr->isExact())
2729 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: C << ShAmtVal));
2730
2731 if (Shr->hasOneUse()) {
2732 // Canonicalize the shift into an 'and':
2733 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2734 APInt Val(APInt::getHighBitsSet(numBits: TypeBits, hiBitsSet: TypeBits - ShAmtVal));
2735 Constant *Mask = ConstantInt::get(Ty: ShrTy, V: Val);
2736 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask, Name: Shr->getName() + ".mask");
2737 return new ICmpInst(Pred, And, ConstantInt::get(Ty: ShrTy, V: C << ShAmtVal));
2738 }
2739
2740 return nullptr;
2741}
2742
2743Instruction *InstCombinerImpl::foldICmpSRemConstant(ICmpInst &Cmp,
2744 BinaryOperator *SRem,
2745 const APInt &C) {
2746 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2747 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT) {
2748 // Canonicalize unsigned predicates to signed:
2749 // (X s% DivisorC) u> C -> (X s% DivisorC) s< 0
2750 // iff (C s< 0 ? ~C : C) u>= abs(DivisorC)-1
2751 // (X s% DivisorC) u< C+1 -> (X s% DivisorC) s> -1
2752 // iff (C+1 s< 0 ? ~C : C) u>= abs(DivisorC)-1
2753
2754 const APInt *DivisorC;
2755 if (!match(V: SRem->getOperand(i_nocapture: 1), P: m_APInt(Res&: DivisorC)))
2756 return nullptr;
2757 if (DivisorC->isZero())
2758 return nullptr;
2759
2760 APInt NormalizedC = C;
2761 if (Pred == ICmpInst::ICMP_ULT) {
2762 assert(!NormalizedC.isZero() &&
2763 "ult X, 0 should have been simplified already.");
2764 --NormalizedC;
2765 }
2766 if (C.isNegative())
2767 NormalizedC.flipAllBits();
2768 if (!NormalizedC.uge(RHS: DivisorC->abs() - 1))
2769 return nullptr;
2770
2771 Type *Ty = SRem->getType();
2772 if (Pred == ICmpInst::ICMP_UGT)
2773 return new ICmpInst(ICmpInst::ICMP_SLT, SRem,
2774 ConstantInt::getNullValue(Ty));
2775 return new ICmpInst(ICmpInst::ICMP_SGT, SRem,
2776 ConstantInt::getAllOnesValue(Ty));
2777 }
2778 // Match an 'is positive' or 'is negative' comparison of remainder by a
2779 // constant power-of-2 value:
2780 // (X % pow2C) sgt/slt 0
2781 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2782 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2783 return nullptr;
2784
2785 // TODO: The one-use check is standard because we do not typically want to
2786 // create longer instruction sequences, but this might be a special-case
2787 // because srem is not good for analysis or codegen.
2788 if (!SRem->hasOneUse())
2789 return nullptr;
2790
2791 const APInt *DivisorC;
2792 if (!match(V: SRem->getOperand(i_nocapture: 1), P: m_Power2(V&: DivisorC)))
2793 return nullptr;
2794
2795 // For cmp_sgt/cmp_slt only zero valued C is handled.
2796 // For cmp_eq/cmp_ne only positive valued C is handled.
2797 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2798 !C.isZero()) ||
2799 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2800 !C.isStrictlyPositive()))
2801 return nullptr;
2802
2803 // Mask off the sign bit and the modulo bits (low-bits).
2804 Type *Ty = SRem->getType();
2805 APInt SignMask = APInt::getSignMask(BitWidth: Ty->getScalarSizeInBits());
2806 Constant *MaskC = ConstantInt::get(Ty, V: SignMask | (*DivisorC - 1));
2807 Value *And = Builder.CreateAnd(LHS: SRem->getOperand(i_nocapture: 0), RHS: MaskC);
2808
2809 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2810 return new ICmpInst(Pred, And, ConstantInt::get(Ty, V: C));
2811
2812 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2813 // bit is set. Example:
2814 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2815 if (Pred == ICmpInst::ICMP_SGT)
2816 return new ICmpInst(ICmpInst::ICMP_SGT, And, ConstantInt::getNullValue(Ty));
2817
2818 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2819 // bit is set. Example:
2820 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2821 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, V: SignMask));
2822}
2823
2824/// Fold icmp (udiv X, Y), C.
2825Instruction *InstCombinerImpl::foldICmpUDivConstant(ICmpInst &Cmp,
2826 BinaryOperator *UDiv,
2827 const APInt &C) {
2828 ICmpInst::Predicate Pred = Cmp.getPredicate();
2829 Value *X = UDiv->getOperand(i_nocapture: 0);
2830 Value *Y = UDiv->getOperand(i_nocapture: 1);
2831 Type *Ty = UDiv->getType();
2832
2833 const APInt *C2;
2834 if (!match(V: X, P: m_APInt(Res&: C2)))
2835 return nullptr;
2836
2837 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2838
2839 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2840 if (Pred == ICmpInst::ICMP_UGT) {
2841 assert(!C.isMaxValue() &&
2842 "icmp ugt X, UINT_MAX should have been simplified already.");
2843 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2844 ConstantInt::get(Ty, V: C2->udiv(RHS: C + 1)));
2845 }
2846
2847 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2848 if (Pred == ICmpInst::ICMP_ULT) {
2849 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2850 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2851 ConstantInt::get(Ty, V: C2->udiv(RHS: C)));
2852 }
2853
2854 return nullptr;
2855}
2856
2857/// Fold icmp ({su}div X, Y), C.
2858Instruction *InstCombinerImpl::foldICmpDivConstant(ICmpInst &Cmp,
2859 BinaryOperator *Div,
2860 const APInt &C) {
2861 ICmpInst::Predicate Pred = Cmp.getPredicate();
2862 Value *X = Div->getOperand(i_nocapture: 0);
2863 Value *Y = Div->getOperand(i_nocapture: 1);
2864 Type *Ty = Div->getType();
2865 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2866
2867 // If unsigned division and the compare constant is bigger than
2868 // UMAX/2 (negative), there's only one pair of values that satisfies an
2869 // equality check, so eliminate the division:
2870 // (X u/ Y) == C --> (X == C) && (Y == 1)
2871 // (X u/ Y) != C --> (X != C) || (Y != 1)
2872 // Similarly, if signed division and the compare constant is exactly SMIN:
2873 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2874 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2875 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2876 (!DivIsSigned || C.isMinSignedValue())) {
2877 Value *XBig = Builder.CreateICmp(P: Pred, LHS: X, RHS: ConstantInt::get(Ty, V: C));
2878 Value *YOne = Builder.CreateICmp(P: Pred, LHS: Y, RHS: ConstantInt::get(Ty, V: 1));
2879 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2880 return BinaryOperator::Create(Op: Logic, S1: XBig, S2: YOne);
2881 }
2882
2883 // Fold: icmp pred ([us]div X, C2), C -> range test
2884 // Fold this div into the comparison, producing a range check.
2885 // Determine, based on the divide type, what the range is being
2886 // checked. If there is an overflow on the low or high side, remember
2887 // it, otherwise compute the range [low, hi) bounding the new value.
2888 // See: InsertRangeTest above for the kinds of replacements possible.
2889 const APInt *C2;
2890 if (!match(V: Y, P: m_APInt(Res&: C2)))
2891 return nullptr;
2892
2893 // FIXME: If the operand types don't match the type of the divide
2894 // then don't attempt this transform. The code below doesn't have the
2895 // logic to deal with a signed divide and an unsigned compare (and
2896 // vice versa). This is because (x /s C2) <s C produces different
2897 // results than (x /s C2) <u C or (x /u C2) <s C or even
2898 // (x /u C2) <u C. Simply casting the operands and result won't
2899 // work. :( The if statement below tests that condition and bails
2900 // if it finds it.
2901 // However, when the divisor is a positive constant and the dividend is
2902 // known non-negative, sdiv is equivalent to udiv, so we can lower
2903 // DivIsSigned and proceed through the unsigned path.
2904 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) {
2905 if (!DivIsSigned || !C2->isStrictlyPositive() ||
2906 !isKnownNonNegative(V: X, SQ: SQ.getWithInstruction(I: &Cmp)))
2907 return nullptr;
2908 DivIsSigned = false;
2909 }
2910
2911 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2912 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2913 // division-by-constant cases should be present, we can not assert that they
2914 // have happened before we reach this icmp instruction.
2915 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2916 return nullptr;
2917
2918 // Compute Prod = C * C2. We are essentially solving an equation of
2919 // form X / C2 = C. We solve for X by multiplying C2 and C.
2920 // By solving for X, we can turn this into a range check instead of computing
2921 // a divide.
2922 APInt Prod = C * *C2;
2923
2924 // Determine if the product overflows by seeing if the product is not equal to
2925 // the divide. Make sure we do the same kind of divide as in the LHS
2926 // instruction that we're folding.
2927 bool ProdOV = (DivIsSigned ? Prod.sdiv(RHS: *C2) : Prod.udiv(RHS: *C2)) != C;
2928
2929 // If the division is known to be exact, then there is no remainder from the
2930 // divide, so the covered range size is unit, otherwise it is the divisor.
2931 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2932
2933 // Figure out the interval that is being checked. For example, a comparison
2934 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2935 // Compute this interval based on the constants involved and the signedness of
2936 // the compare/divide. This computes a half-open interval, keeping track of
2937 // whether either value in the interval overflows. After analysis each
2938 // overflow variable is set to 0 if it's corresponding bound variable is valid
2939 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2940 int LoOverflow = 0, HiOverflow = 0;
2941 APInt LoBound, HiBound;
2942
2943 if (!DivIsSigned) { // udiv
2944 // e.g. X/5 op 3 --> [15, 20)
2945 LoBound = Prod;
2946 HiOverflow = LoOverflow = ProdOV;
2947 if (!HiOverflow) {
2948 // If this is not an exact divide, then many values in the range collapse
2949 // to the same result value.
2950 HiOverflow = addWithOverflow(Result&: HiBound, In1: LoBound, In2: RangeSize, IsSigned: false);
2951 }
2952 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2953 if (C.isZero()) { // (X / pos) op 0
2954 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2955 LoBound = -(RangeSize - 1);
2956 HiBound = RangeSize;
2957 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2958 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2959 HiOverflow = LoOverflow = ProdOV;
2960 if (!HiOverflow)
2961 HiOverflow = addWithOverflow(Result&: HiBound, In1: Prod, In2: RangeSize, IsSigned: true);
2962 } else { // (X / pos) op neg
2963 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2964 HiBound = Prod + 1;
2965 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2966 if (!LoOverflow) {
2967 APInt DivNeg = -RangeSize;
2968 LoOverflow = addWithOverflow(Result&: LoBound, In1: HiBound, In2: DivNeg, IsSigned: true) ? -1 : 0;
2969 }
2970 }
2971 } else if (C2->isNegative()) { // Divisor is < 0.
2972 if (Div->isExact())
2973 RangeSize.negate();
2974 if (C.isZero()) { // (X / neg) op 0
2975 // e.g. X/-5 op 0 --> [-4, 5)
2976 LoBound = RangeSize + 1;
2977 HiBound = -RangeSize;
2978 if (HiBound == *C2) { // -INTMIN = INTMIN
2979 HiOverflow = 1; // [INTMIN+1, overflow)
2980 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2981 }
2982 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2983 // e.g. X/-5 op 3 --> [-19, -14)
2984 HiBound = Prod + 1;
2985 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2986 if (!LoOverflow)
2987 LoOverflow =
2988 addWithOverflow(Result&: LoBound, In1: HiBound, In2: RangeSize, IsSigned: true) ? -1 : 0;
2989 } else { // (X / neg) op neg
2990 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2991 LoOverflow = HiOverflow = ProdOV;
2992 if (!HiOverflow)
2993 HiOverflow = subWithOverflow(Result&: HiBound, In1: Prod, In2: RangeSize, IsSigned: true);
2994 }
2995
2996 // Dividing by a negative swaps the condition. LT <-> GT
2997 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
2998 }
2999
3000 switch (Pred) {
3001 default:
3002 llvm_unreachable("Unhandled icmp predicate!");
3003 case ICmpInst::ICMP_EQ:
3004 if (LoOverflow && HiOverflow)
3005 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
3006 if (HiOverflow)
3007 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3008 X, ConstantInt::get(Ty, V: LoBound));
3009 if (LoOverflow)
3010 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3011 X, ConstantInt::get(Ty, V: HiBound));
3012 return replaceInstUsesWith(
3013 I&: Cmp, V: insertRangeTest(V: X, Lo: LoBound, Hi: HiBound, isSigned: DivIsSigned, Inside: true));
3014 case ICmpInst::ICMP_NE:
3015 if (LoOverflow && HiOverflow)
3016 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
3017 if (HiOverflow)
3018 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3019 X, ConstantInt::get(Ty, V: LoBound));
3020 if (LoOverflow)
3021 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3022 X, ConstantInt::get(Ty, V: HiBound));
3023 return replaceInstUsesWith(
3024 I&: Cmp, V: insertRangeTest(V: X, Lo: LoBound, Hi: HiBound, isSigned: DivIsSigned, Inside: false));
3025 case ICmpInst::ICMP_ULT:
3026 case ICmpInst::ICMP_SLT:
3027 if (LoOverflow == +1) // Low bound is greater than input range.
3028 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
3029 if (LoOverflow == -1) // Low bound is less than input range.
3030 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
3031 return new ICmpInst(Pred, X, ConstantInt::get(Ty, V: LoBound));
3032 case ICmpInst::ICMP_UGT:
3033 case ICmpInst::ICMP_SGT:
3034 if (HiOverflow == +1) // High bound greater than input range.
3035 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
3036 if (HiOverflow == -1) // High bound less than input range.
3037 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
3038 if (Pred == ICmpInst::ICMP_UGT)
3039 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, V: HiBound));
3040 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, V: HiBound));
3041 }
3042
3043 return nullptr;
3044}
3045
3046/// Fold icmp (sub X, Y), C.
3047Instruction *InstCombinerImpl::foldICmpSubConstant(ICmpInst &Cmp,
3048 BinaryOperator *Sub,
3049 const APInt &C) {
3050 Value *X = Sub->getOperand(i_nocapture: 0), *Y = Sub->getOperand(i_nocapture: 1);
3051 ICmpInst::Predicate Pred = Cmp.getPredicate();
3052 Type *Ty = Sub->getType();
3053
3054 // (X - (X urem D)) is D*(X/D), a multiple of D, so it is u> C exactly when
3055 // X u>= D (for C u< D), and u< C exactly when X u< D (for 0 u< C u<= D):
3056 // icmp ugt (sub X, (urem X, D)), C --> icmp ugt X, D-1
3057 // icmp ult (sub X, (urem X, D)), C --> icmp ult X, D
3058 const APInt *D;
3059 if (match(V: Y, P: m_URem(L: m_Specific(V: X), R: m_APInt(Res&: D))) && !D->isZero()) {
3060 if (Pred == ICmpInst::ICMP_UGT && C.ult(RHS: *D))
3061 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, V: *D - 1));
3062 if (Pred == ICmpInst::ICMP_ULT && !C.isZero() && C.ule(RHS: *D))
3063 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, V: *D));
3064 }
3065
3066 // (SubC - Y) == C) --> Y == (SubC - C)
3067 // (SubC - Y) != C) --> Y != (SubC - C)
3068 Constant *SubC;
3069 if (Cmp.isEquality() && match(V: X, P: m_ImmConstant(C&: SubC))) {
3070 return new ICmpInst(Pred, Y,
3071 ConstantExpr::getSub(C1: SubC, C2: ConstantInt::get(Ty, V: C)));
3072 }
3073
3074 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
3075 const APInt *C2;
3076 APInt SubResult;
3077 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
3078 bool HasNSW = Sub->hasNoSignedWrap();
3079 bool HasNUW = Sub->hasNoUnsignedWrap();
3080 if (match(V: X, P: m_APInt(Res&: C2)) &&
3081 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
3082 !subWithOverflow(Result&: SubResult, In1: *C2, In2: C, IsSigned: Cmp.isSigned()))
3083 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, V: SubResult));
3084
3085 // X - Y == 0 --> X == Y.
3086 // X - Y != 0 --> X != Y.
3087 // TODO: We allow this with multiple uses as long as the other uses are not
3088 // in phis. The phi use check is guarding against a codegen regression
3089 // for a loop test. If the backend could undo this (and possibly
3090 // subsequent transforms), we would not need this hack.
3091 if (Cmp.isEquality() && C.isZero() &&
3092 none_of(Range: (Sub->users()), P: [](const User *U) { return isa<PHINode>(Val: U); }))
3093 return new ICmpInst(Pred, X, Y);
3094
3095 // The following transforms are only worth it if the only user of the subtract
3096 // is the icmp.
3097 // TODO: This is an artificial restriction for all of the transforms below
3098 // that only need a single replacement icmp. Can these use the phi test
3099 // like the transform above here?
3100 if (!Sub->hasOneUse())
3101 return nullptr;
3102
3103 if (Sub->hasNoSignedWrap()) {
3104 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
3105 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3106 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3107
3108 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
3109 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
3110 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3111
3112 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
3113 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
3114 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3115
3116 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
3117 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3118 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3119 }
3120
3121 if (!match(V: X, P: m_APInt(Res&: C2)))
3122 return nullptr;
3123
3124 // C2 - Y <u C -> (Y | (C - 1)) == C2
3125 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
3126 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
3127 (*C2 & (C - 1)) == (C - 1))
3128 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(LHS: Y, RHS: C - 1), X);
3129
3130 // C2 - Y >u C -> (Y | C) != C2
3131 // iff C2 & C == C and C + 1 is a power of 2
3132 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
3133 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(LHS: Y, RHS: C), X);
3134
3135 // We have handled special cases that reduce.
3136 // Canonicalize any remaining sub to add as:
3137 // (C2 - Y) > C --> (Y + ~C2) < ~C
3138 Value *Add = Builder.CreateAdd(LHS: Y, RHS: ConstantInt::get(Ty, V: ~(*C2)), Name: "notsub",
3139 HasNUW, HasNSW);
3140 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, V: ~C));
3141}
3142
3143static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
3144 Value *Op1, IRBuilderBase &Builder,
3145 bool HasOneUse) {
3146 auto FoldConstant = [&](bool Val) {
3147 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3148 if (Op0->getType()->isVectorTy())
3149 Res = ConstantVector::getSplat(
3150 EC: cast<VectorType>(Val: Op0->getType())->getElementCount(), Elt: Res);
3151 return Res;
3152 };
3153
3154 switch (Table.to_ulong()) {
3155 case 0: // 0 0 0 0
3156 return FoldConstant(false);
3157 case 1: // 0 0 0 1
3158 return HasOneUse ? Builder.CreateNot(V: Builder.CreateOr(LHS: Op0, RHS: Op1)) : nullptr;
3159 case 2: // 0 0 1 0
3160 return HasOneUse ? Builder.CreateAnd(LHS: Builder.CreateNot(V: Op0), RHS: Op1) : nullptr;
3161 case 3: // 0 0 1 1
3162 return Builder.CreateNot(V: Op0);
3163 case 4: // 0 1 0 0
3164 return HasOneUse ? Builder.CreateAnd(LHS: Op0, RHS: Builder.CreateNot(V: Op1)) : nullptr;
3165 case 5: // 0 1 0 1
3166 return Builder.CreateNot(V: Op1);
3167 case 6: // 0 1 1 0
3168 return Builder.CreateXor(LHS: Op0, RHS: Op1);
3169 case 7: // 0 1 1 1
3170 return HasOneUse ? Builder.CreateNot(V: Builder.CreateAnd(LHS: Op0, RHS: Op1)) : nullptr;
3171 case 8: // 1 0 0 0
3172 return Builder.CreateAnd(LHS: Op0, RHS: Op1);
3173 case 9: // 1 0 0 1
3174 return HasOneUse ? Builder.CreateNot(V: Builder.CreateXor(LHS: Op0, RHS: Op1)) : nullptr;
3175 case 10: // 1 0 1 0
3176 return Op1;
3177 case 11: // 1 0 1 1
3178 return HasOneUse ? Builder.CreateOr(LHS: Builder.CreateNot(V: Op0), RHS: Op1) : nullptr;
3179 case 12: // 1 1 0 0
3180 return Op0;
3181 case 13: // 1 1 0 1
3182 return HasOneUse ? Builder.CreateOr(LHS: Op0, RHS: Builder.CreateNot(V: Op1)) : nullptr;
3183 case 14: // 1 1 1 0
3184 return Builder.CreateOr(LHS: Op0, RHS: Op1);
3185 case 15: // 1 1 1 1
3186 return FoldConstant(true);
3187 default:
3188 llvm_unreachable("Invalid Operation");
3189 }
3190 return nullptr;
3191}
3192
3193Instruction *InstCombinerImpl::foldICmpBinOpWithConstantViaTruthTable(
3194 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3195 Value *A, *B;
3196 Constant *C1, *C2, *C3, *C4;
3197 if (!match(V: BO->getOperand(i_nocapture: 0),
3198 P: m_SelectLike(C: m_Value(V&: A), TrueC: m_Constant(C&: C1), FalseC: m_Constant(C&: C2))) ||
3199 !match(V: BO->getOperand(i_nocapture: 1),
3200 P: m_SelectLike(C: m_Value(V&: B), TrueC: m_Constant(C&: C3), FalseC: m_Constant(C&: C4))) ||
3201 Cmp.getType() != A->getType() || Cmp.getType() != B->getType())
3202 return nullptr;
3203
3204 std::bitset<4> Table;
3205 auto ComputeTable = [&](bool First, bool Second) -> std::optional<bool> {
3206 Constant *L = First ? C1 : C2;
3207 Constant *R = Second ? C3 : C4;
3208 if (auto *Res = ConstantFoldBinaryOpOperands(Opcode: BO->getOpcode(), LHS: L, RHS: R, DL)) {
3209 auto *Val = Res->getType()->isVectorTy() ? Res->getSplatValue() : Res;
3210 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val))
3211 return ICmpInst::compare(LHS: CI->getValue(), RHS: C, Pred: Cmp.getPredicate());
3212 }
3213 return std::nullopt;
3214 };
3215
3216 for (unsigned I = 0; I < 4; ++I) {
3217 bool First = (I >> 1) & 1;
3218 bool Second = I & 1;
3219 if (auto Res = ComputeTable(First, Second))
3220 Table[I] = *Res;
3221 else
3222 return nullptr;
3223 }
3224
3225 // Synthesize optimal logic.
3226 if (auto *Cond = createLogicFromTable(Table, Op0: A, Op1: B, Builder, HasOneUse: BO->hasOneUse()))
3227 return replaceInstUsesWith(I&: Cmp, V: Cond);
3228 return nullptr;
3229}
3230
3231/// Fold icmp (add X, Y), C.
3232Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp,
3233 BinaryOperator *Add,
3234 const APInt &C) {
3235 Value *Y = Add->getOperand(i_nocapture: 1);
3236 Value *X = Add->getOperand(i_nocapture: 0);
3237 const CmpPredicate Pred = Cmp.getCmpPredicate();
3238
3239 // icmp ult (add nuw A, (lshr A, ShAmtC)), C --> icmp ult A, C
3240 // when C <= (1 << ShAmtC).
3241 const APInt *ShAmtC;
3242 Value *A;
3243 unsigned BitWidth = C.getBitWidth();
3244 if (Pred == ICmpInst::ICMP_ULT &&
3245 match(V: Add,
3246 P: m_c_NUWAdd(L: m_Value(V&: A), R: m_LShr(L: m_Deferred(V: A), R: m_APInt(Res&: ShAmtC)))) &&
3247 ShAmtC->ult(RHS: BitWidth) &&
3248 C.ule(RHS: APInt::getOneBitSet(numBits: BitWidth, BitNo: ShAmtC->getZExtValue())))
3249 return new ICmpInst(Pred, A, ConstantInt::get(Ty: A->getType(), V: C));
3250
3251 const APInt *C2;
3252 if (Cmp.isEquality() || !match(V: Y, P: m_APInt(Res&: C2)))
3253 return nullptr;
3254
3255 // Fold icmp pred (add X, C2), C.
3256 Type *Ty = Add->getType();
3257
3258 // If the add does not wrap, we can always adjust the compare by subtracting
3259 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3260 // have been canonicalized to SGT/SLT/UGT/ULT.
3261 if (Add->hasNoUnsignedWrap() &&
3262 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT)) {
3263 bool Overflow;
3264 APInt NewC = C.usub_ov(RHS: *C2, Overflow);
3265 // If there is overflow, the result must be true or false.
3266 if (!Overflow)
3267 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
3268 return new ICmpInst(Pred, X, ConstantInt::get(Ty, V: NewC));
3269 }
3270
3271 CmpInst::Predicate ChosenPred = Pred.getPreferredSignedPredicate();
3272
3273 if (Add->hasNoSignedWrap() &&
3274 (ChosenPred == ICmpInst::ICMP_SGT || ChosenPred == ICmpInst::ICMP_SLT)) {
3275 bool Overflow;
3276 APInt NewC = C.ssub_ov(RHS: *C2, Overflow);
3277 if (!Overflow)
3278 // icmp samesign ugt/ult (add nsw X, C2), C
3279 // -> icmp sgt/slt X, (C - C2)
3280 return new ICmpInst(ChosenPred, X, ConstantInt::get(Ty, V: NewC));
3281 }
3282
3283 if (ICmpInst::isUnsigned(Pred) && Add->hasNoSignedWrap() &&
3284 C.isNonNegative() && (C - *C2).isNonNegative() &&
3285 computeConstantRange(V: X, /*ForSigned=*/true, SQ: SQ.getWithInstruction(I: &Cmp))
3286 .add(Other: *C2)
3287 .isAllNonNegative())
3288 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), X,
3289 ConstantInt::get(Ty, V: C - *C2));
3290
3291 auto CR = ConstantRange::makeExactICmpRegion(Pred, Other: C).subtract(CI: *C2);
3292 const APInt &Upper = CR.getUpper();
3293 const APInt &Lower = CR.getLower();
3294 if (Cmp.isSigned()) {
3295 if (Lower.isSignMask())
3296 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, V: Upper));
3297 if (Upper.isSignMask())
3298 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, V: Lower));
3299 } else {
3300 if (Lower.isMinValue())
3301 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, V: Upper));
3302 if (Upper.isMinValue())
3303 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, V: Lower));
3304 }
3305
3306 // This set of folds is intentionally placed after folds that use no-wrapping
3307 // flags because those folds are likely better for later analysis/codegen.
3308 const APInt SMax = APInt::getSignedMaxValue(numBits: Ty->getScalarSizeInBits());
3309 const APInt SMin = APInt::getSignedMinValue(numBits: Ty->getScalarSizeInBits());
3310
3311 // Fold compare with offset to opposite sign compare if it eliminates offset:
3312 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3313 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3314 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, V: -(*C2)));
3315
3316 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3317 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3318 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, V: ~(*C2)));
3319
3320 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3321 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3322 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, V: SMax - C));
3323
3324 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3325 if (Pred == CmpInst::ICMP_SLT && C == *C2)
3326 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, V: C ^ SMax));
3327
3328 // (X + -1) <u C --> X <=u C (if X is never null)
3329 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3330 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
3331 if (llvm::isKnownNonZero(V: X, Q))
3332 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, V: C));
3333 }
3334
3335 if (!Add->hasOneUse())
3336 return nullptr;
3337
3338 // X+C <u C2 -> (X & -C2) == C
3339 // iff C & (C2-1) == 0
3340 // C2 is a power of 2
3341 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3342 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(LHS: X, RHS: -C),
3343 ConstantExpr::getNeg(C: cast<Constant>(Val: Y)));
3344
3345 // X+C2 <u C -> (X & C) == 2C
3346 // iff C == -(C2)
3347 // C2 is a power of 2
3348 if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)
3349 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(LHS: X, RHS: C),
3350 ConstantInt::get(Ty, V: C * 2));
3351
3352 // X+C >u C2 -> (X & ~C2) != C
3353 // iff C & C2 == 0
3354 // C2+1 is a power of 2
3355 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3356 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(LHS: X, RHS: ~C),
3357 ConstantExpr::getNeg(C: cast<Constant>(Val: Y)));
3358
3359 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3360 // to the ult form.
3361 // X+C2 >u C -> X+(C2-C-1) <u ~C
3362 if (Pred == ICmpInst::ICMP_UGT)
3363 return new ICmpInst(ICmpInst::ICMP_ULT,
3364 Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: *C2 - C - 1)),
3365 ConstantInt::get(Ty, V: ~C));
3366
3367 // zext(V) + C2 pred C -> V + C3 pred' C4
3368 Value *V;
3369 if (match(V: X, P: m_ZExt(Op: m_Value(V)))) {
3370 Type *NewCmpTy = V->getType();
3371 unsigned NewCmpBW = NewCmpTy->getScalarSizeInBits();
3372 if (shouldChangeType(From: Ty, To: NewCmpTy)) {
3373 ConstantRange SrcCR = CR.truncate(BitWidth: NewCmpBW, NoWrapKind: TruncInst::NoUnsignedWrap);
3374 CmpInst::Predicate EquivPred;
3375 APInt EquivInt;
3376 APInt EquivOffset;
3377
3378 SrcCR.getEquivalentICmp(Pred&: EquivPred, RHS&: EquivInt, Offset&: EquivOffset);
3379 return new ICmpInst(
3380 EquivPred,
3381 EquivOffset.isZero()
3382 ? V
3383 : Builder.CreateAdd(LHS: V, RHS: ConstantInt::get(Ty: NewCmpTy, V: EquivOffset)),
3384 ConstantInt::get(Ty: NewCmpTy, V: EquivInt));
3385 }
3386 }
3387
3388 return nullptr;
3389}
3390
3391bool InstCombinerImpl::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS,
3392 Value *&RHS, ConstantInt *&Less,
3393 ConstantInt *&Equal,
3394 ConstantInt *&Greater) {
3395 // TODO: Generalize this to work with other comparison idioms or ensure
3396 // they get canonicalized into this form.
3397
3398 // select i1 (a == b),
3399 // i32 Equal,
3400 // i32 (select i1 (a < b), i32 Less, i32 Greater)
3401 // where Equal, Less and Greater are placeholders for any three constants.
3402 CmpPredicate PredA;
3403 if (!match(V: SI->getCondition(), P: m_ICmp(Pred&: PredA, L: m_Value(V&: LHS), R: m_Value(V&: RHS))) ||
3404 !ICmpInst::isEquality(P: PredA))
3405 return false;
3406 Value *EqualVal = SI->getTrueValue();
3407 Value *UnequalVal = SI->getFalseValue();
3408 // We still can get non-canonical predicate here, so canonicalize.
3409 if (PredA == ICmpInst::ICMP_NE)
3410 std::swap(a&: EqualVal, b&: UnequalVal);
3411 if (!match(V: EqualVal, P: m_ConstantInt(CI&: Equal)))
3412 return false;
3413 CmpPredicate PredB;
3414 Value *LHS2, *RHS2;
3415 if (!match(V: UnequalVal, P: m_Select(C: m_ICmp(Pred&: PredB, L: m_Value(V&: LHS2), R: m_Value(V&: RHS2)),
3416 L: m_ConstantInt(CI&: Less), R: m_ConstantInt(CI&: Greater))))
3417 return false;
3418 // We can get predicate mismatch here, so canonicalize if possible:
3419 // First, ensure that 'LHS' match.
3420 if (LHS2 != LHS) {
3421 // x sgt y <--> y slt x
3422 std::swap(a&: LHS2, b&: RHS2);
3423 PredB = ICmpInst::getSwappedPredicate(pred: PredB);
3424 }
3425 if (LHS2 != LHS)
3426 return false;
3427 // We also need to canonicalize 'RHS'.
3428 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(Val: RHS2)) {
3429 // x sgt C-1 <--> x sge C <--> not(x slt C)
3430 auto FlippedStrictness =
3431 getFlippedStrictnessPredicateAndConstant(Pred: PredB, C: cast<Constant>(Val: RHS2));
3432 if (!FlippedStrictness)
3433 return false;
3434 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3435 "basic correctness failure");
3436 RHS2 = FlippedStrictness->second;
3437 // And kind-of perform the result swap.
3438 std::swap(a&: Less, b&: Greater);
3439 PredB = ICmpInst::ICMP_SLT;
3440 }
3441 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3442}
3443
3444Instruction *InstCombinerImpl::foldICmpSelectConstant(ICmpInst &Cmp,
3445 SelectInst *Select,
3446 ConstantInt *C) {
3447
3448 assert(C && "Cmp RHS should be a constant int!");
3449 // If we're testing a constant value against the result of a three way
3450 // comparison, the result can be expressed directly in terms of the
3451 // original values being compared. Note: We could possibly be more
3452 // aggressive here and remove the hasOneUse test. The original select is
3453 // really likely to simplify or sink when we remove a test of the result.
3454 Value *OrigLHS, *OrigRHS;
3455 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3456 if (Cmp.hasOneUse() &&
3457 matchThreeWayIntCompare(SI: Select, LHS&: OrigLHS, RHS&: OrigRHS, Less&: C1LessThan, Equal&: C2Equal,
3458 Greater&: C3GreaterThan)) {
3459 assert(C1LessThan && C2Equal && C3GreaterThan);
3460
3461 bool TrueWhenLessThan = ICmpInst::compare(
3462 LHS: C1LessThan->getValue(), RHS: C->getValue(), Pred: Cmp.getPredicate());
3463 bool TrueWhenEqual = ICmpInst::compare(LHS: C2Equal->getValue(), RHS: C->getValue(),
3464 Pred: Cmp.getPredicate());
3465 bool TrueWhenGreaterThan = ICmpInst::compare(
3466 LHS: C3GreaterThan->getValue(), RHS: C->getValue(), Pred: Cmp.getPredicate());
3467
3468 // This generates the new instruction that will replace the original Cmp
3469 // Instruction. Instead of enumerating the various combinations when
3470 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3471 // false, we rely on chaining of ORs and future passes of InstCombine to
3472 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3473
3474 // When none of the three constants satisfy the predicate for the RHS (C),
3475 // the entire original Cmp can be simplified to a false.
3476 Value *Cond = Builder.getFalse();
3477 if (TrueWhenLessThan)
3478 Cond = Builder.CreateOr(
3479 LHS: Cond, RHS: Builder.CreateICmp(P: ICmpInst::ICMP_SLT, LHS: OrigLHS, RHS: OrigRHS));
3480 if (TrueWhenEqual)
3481 Cond = Builder.CreateOr(
3482 LHS: Cond, RHS: Builder.CreateICmp(P: ICmpInst::ICMP_EQ, LHS: OrigLHS, RHS: OrigRHS));
3483 if (TrueWhenGreaterThan)
3484 Cond = Builder.CreateOr(
3485 LHS: Cond, RHS: Builder.CreateICmp(P: ICmpInst::ICMP_SGT, LHS: OrigLHS, RHS: OrigRHS));
3486
3487 return replaceInstUsesWith(I&: Cmp, V: Cond);
3488 }
3489 return nullptr;
3490}
3491
3492Instruction *InstCombinerImpl::foldICmpBitCast(ICmpInst &Cmp) {
3493 auto *Bitcast = dyn_cast<BitCastInst>(Val: Cmp.getOperand(i_nocapture: 0));
3494 if (!Bitcast)
3495 return nullptr;
3496
3497 ICmpInst::Predicate Pred = Cmp.getPredicate();
3498 Value *Op1 = Cmp.getOperand(i_nocapture: 1);
3499 Value *BCSrcOp = Bitcast->getOperand(i_nocapture: 0);
3500 Type *SrcType = Bitcast->getSrcTy();
3501 Type *DstType = Bitcast->getType();
3502
3503 // Make sure the bitcast doesn't change between scalar and vector and
3504 // doesn't change the number of vector elements.
3505 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3506 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3507 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3508 Value *X;
3509 if (match(V: BCSrcOp, P: m_SIToFP(Op: m_Value(V&: X)))) {
3510 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3511 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3512 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3513 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3514 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3515 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3516 match(V: Op1, P: m_Zero()))
3517 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: X->getType()));
3518
3519 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3520 if (Pred == ICmpInst::ICMP_SLT && match(V: Op1, P: m_One()))
3521 return new ICmpInst(Pred, X, ConstantInt::get(Ty: X->getType(), V: 1));
3522
3523 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3524 if (Pred == ICmpInst::ICMP_SGT && match(V: Op1, P: m_AllOnes()))
3525 return new ICmpInst(Pred, X,
3526 ConstantInt::getAllOnesValue(Ty: X->getType()));
3527 }
3528
3529 // Zero-equality checks are preserved through unsigned floating-point casts:
3530 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3531 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3532 if (match(V: BCSrcOp, P: m_UIToFP(Op: m_Value(V&: X))))
3533 if (Cmp.isEquality() && match(V: Op1, P: m_Zero()))
3534 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: X->getType()));
3535
3536 const APInt *C;
3537 bool TrueIfSigned;
3538 if (match(V: Op1, P: m_APInt(Res&: C)) && Bitcast->hasOneUse()) {
3539 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3540 // the FP extend/truncate because that cast does not change the sign-bit.
3541 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3542 // The sign-bit is always the most significant bit in those types.
3543 if (isSignBitCheck(Pred, RHS: *C, TrueIfSigned) &&
3544 (match(V: BCSrcOp, P: m_FPExt(Op: m_Value(V&: X))) ||
3545 match(V: BCSrcOp, P: m_FPTrunc(Op: m_Value(V&: X))))) {
3546 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3547 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3548 Type *XType = X->getType();
3549
3550 // We can't currently handle Power style floating point operations here.
3551 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3552 Type *NewType = Builder.getIntNTy(N: XType->getScalarSizeInBits());
3553 if (auto *XVTy = dyn_cast<VectorType>(Val: XType))
3554 NewType = VectorType::get(ElementType: NewType, EC: XVTy->getElementCount());
3555 Value *NewBitcast = Builder.CreateBitCast(V: X, DestTy: NewType);
3556 if (TrueIfSigned)
3557 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3558 ConstantInt::getNullValue(Ty: NewType));
3559 else
3560 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3561 ConstantInt::getAllOnesValue(Ty: NewType));
3562 }
3563 }
3564
3565 // icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)
3566 Type *FPType = SrcType->getScalarType();
3567 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3568 Kind: Attribute::NoImplicitFloat) &&
3569 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3570 FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();
3571 if (Mask & (fcInf | fcZero)) {
3572 if (Pred == ICmpInst::ICMP_NE)
3573 Mask = ~Mask;
3574 return replaceInstUsesWith(I&: Cmp,
3575 V: Builder.createIsFPClass(FPNum: BCSrcOp, Test: Mask));
3576 }
3577 }
3578 }
3579 }
3580
3581 // Fold the canonicalized form of vector_reduce_or if the arg is
3582 // get_active_lane mask.
3583 // icmp ne (bitcast <N x i1> to iN (get_active_lane_mask(l, h))), 0 ->
3584 // icmp ult l, h
3585 // icmp eq (bitcast <N x i1> to iN (get_active_lane_mask(l, h))), 0 ->
3586 // icmp uge l, h
3587 Value *Upper, *Lower;
3588 if (match(V: BCSrcOp, P: m_Intrinsic<Intrinsic::get_active_lane_mask>(
3589 Ops: m_Value(V&: Lower), Ops: m_Value(V&: Upper))) &&
3590 match(V: Op1, P: m_Zero()) && DstType->isIntegerTy()) {
3591 if (Pred == ICmpInst::ICMP_NE)
3592 return new ICmpInst(ICmpInst::ICMP_ULT, Lower, Upper);
3593 if (Pred == ICmpInst::ICMP_EQ)
3594 return new ICmpInst(ICmpInst::ICMP_UGE, Lower, Upper);
3595 }
3596
3597 const APInt *C;
3598 if (!match(V: Cmp.getOperand(i_nocapture: 1), P: m_APInt(Res&: C)) || !DstType->isIntegerTy() ||
3599 !SrcType->isIntOrIntVectorTy())
3600 return nullptr;
3601
3602 // If this is checking if all elements of a vector compare are set or not,
3603 // invert the casted vector equality compare and test if all compare
3604 // elements are clear or not. Compare against zero is generally easier for
3605 // analysis and codegen.
3606 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3607 // Example: are all elements equal? --> are zero elements not equal?
3608 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3609 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3610 if (Value *NotBCSrcOp =
3611 getFreelyInverted(V: BCSrcOp, WillInvertAllUses: BCSrcOp->hasOneUse(), Builder: &Builder)) {
3612 Value *Cast = Builder.CreateBitCast(V: NotBCSrcOp, DestTy: DstType);
3613 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(Ty: DstType));
3614 }
3615 }
3616
3617 // If this is checking if all elements of an extended vector are clear or not,
3618 // compare in a narrow type to eliminate the extend:
3619 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3620 Value *X;
3621 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3622 match(V: BCSrcOp, P: m_ZExtOrSExt(Op: m_Value(V&: X)))) {
3623 if (auto *VecTy = dyn_cast<FixedVectorType>(Val: X->getType())) {
3624 Type *NewType = Builder.getIntNTy(N: VecTy->getPrimitiveSizeInBits());
3625 Value *NewCast = Builder.CreateBitCast(V: X, DestTy: NewType);
3626 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(Ty: NewType));
3627 }
3628 }
3629
3630 // Folding: icmp <pred> iN X, C
3631 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3632 // and C is a splat of a K-bit pattern
3633 // and SC is a constant vector = <C', C', C', ..., C'>
3634 // Into:
3635 // %E = extractelement <M x iK> %vec, i32 C'
3636 // icmp <pred> iK %E, trunc(C)
3637 Value *Vec;
3638 ArrayRef<int> Mask;
3639 if (match(V: BCSrcOp, P: m_Shuffle(v1: m_Value(V&: Vec), v2: m_Undef(), mask: m_Mask(Mask)))) {
3640 // Check whether every element of Mask is the same constant
3641 if (all_equal(Range&: Mask)) {
3642 auto *VecTy = cast<VectorType>(Val: SrcType);
3643 auto *EltTy = cast<IntegerType>(Val: VecTy->getElementType());
3644 if (C->isSplat(SplatSizeInBits: EltTy->getBitWidth())) {
3645 // Fold the icmp based on the value of C
3646 // If C is M copies of an iK sized bit pattern,
3647 // then:
3648 // => %E = extractelement <N x iK> %vec, i64 Elem
3649 // icmp <pred> iK %SplatVal, <pattern>
3650 Value *Extract = Builder.CreateExtractElement(Vec, Idx: Mask[0]);
3651 Value *NewC = ConstantInt::get(Ty: EltTy, V: C->trunc(width: EltTy->getBitWidth()));
3652 return new ICmpInst(Pred, Extract, NewC);
3653 }
3654 }
3655 }
3656 return nullptr;
3657}
3658
3659/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3660/// where X is some kind of instruction.
3661Instruction *InstCombinerImpl::foldICmpInstWithConstant(ICmpInst &Cmp) {
3662 const APInt *C;
3663
3664 if (match(V: Cmp.getOperand(i_nocapture: 1), P: m_APInt(Res&: C))) {
3665 if (auto *BO = dyn_cast<BinaryOperator>(Val: Cmp.getOperand(i_nocapture: 0)))
3666 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, C: *C))
3667 return I;
3668
3669 if (auto *SI = dyn_cast<SelectInst>(Val: Cmp.getOperand(i_nocapture: 0)))
3670 // For now, we only support constant integers while folding the
3671 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3672 // similar to the cases handled by binary ops above.
3673 if (auto *ConstRHS = dyn_cast<ConstantInt>(Val: Cmp.getOperand(i_nocapture: 1)))
3674 if (Instruction *I = foldICmpSelectConstant(Cmp, Select: SI, C: ConstRHS))
3675 return I;
3676
3677 if (auto *TI = dyn_cast<TruncInst>(Val: Cmp.getOperand(i_nocapture: 0)))
3678 if (Instruction *I = foldICmpTruncConstant(Cmp, Trunc: TI, C: *C))
3679 return I;
3680
3681 if (auto *II = dyn_cast<IntrinsicInst>(Val: Cmp.getOperand(i_nocapture: 0)))
3682 if (Instruction *I = foldICmpIntrinsicWithConstant(ICI&: Cmp, II, C: *C))
3683 return I;
3684
3685 {
3686 // icmp slt/sgt (extractvalue (frexp X), 1), C -->
3687 // fcmp olt/oge (fabs X), 2^ExpVal
3688 // slt -> olt, ExpVal = C-1; sgt -> oge, ExpVal = C.
3689 Value *X;
3690 if (match(V: Cmp.getOperand(i_nocapture: 0),
3691 P: m_OneUse(SubPattern: m_ExtractValue<1>(
3692 V: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::frexp>(Ops: m_Value(V&: X))))))) {
3693 ICmpInst::Predicate Pred = Cmp.getPredicate();
3694 APInt Exp;
3695 FCmpInst::Predicate NewPred;
3696 bool ValidPred = true;
3697
3698 switch (Pred) {
3699 case ICmpInst::ICMP_SLT:
3700 NewPred = FCmpInst::FCMP_OLT;
3701 Exp = *C - 1;
3702 break;
3703 case ICmpInst::ICMP_SGT:
3704 NewPred = FCmpInst::FCMP_OGE;
3705 Exp = *C;
3706 break;
3707 default:
3708 ValidPred = false;
3709 break;
3710 }
3711
3712 if (ValidPred) {
3713 const fltSemantics &Sem =
3714 X->getType()->getScalarType()->getFltSemantics();
3715 int MaxExp = APFloat::semanticsMaxExponent(Sem);
3716
3717 if (!Exp.isNegative() && Exp.sle(RHS: MaxExp + 1) &&
3718 isKnownNeverInfOrNaN(V: X, SQ: SQ.getWithInstruction(I: &Cmp))) {
3719 int ExpVal = static_cast<int>(Exp.getSExtValue());
3720 APFloat CmpConst = scalbn(X: APFloat::getOne(Sem), Exp: ExpVal,
3721 RM: APFloat::rmNearestTiesToEven);
3722 Value *Fabs = Builder.CreateFAbs(V: X);
3723 return new FCmpInst(NewPred, Fabs,
3724 ConstantFP::get(Ty: X->getType(), V: CmpConst));
3725 }
3726 }
3727 }
3728 }
3729
3730 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3731 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3732 // TODO: This checks one-use, but that is not strictly necessary.
3733 Value *Cmp0 = Cmp.getOperand(i_nocapture: 0);
3734 Value *X, *Y;
3735 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3736 (match(V: Cmp0,
3737 P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::ssub_with_overflow>(
3738 Ops: m_Value(V&: X), Ops: m_Value(V&: Y)))) ||
3739 match(V: Cmp0,
3740 P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::usub_with_overflow>(
3741 Ops: m_Value(V&: X), Ops: m_Value(V&: Y))))))
3742 return new ICmpInst(Cmp.getPredicate(), X, Y);
3743 }
3744
3745 if (match(V: Cmp.getOperand(i_nocapture: 1), P: m_APIntAllowPoison(Res&: C)))
3746 return foldICmpInstWithConstantAllowPoison(Cmp, C: *C);
3747
3748 return nullptr;
3749}
3750
3751/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3752/// icmp eq/ne BO, C.
3753Instruction *InstCombinerImpl::foldICmpBinOpEqualityWithConstant(
3754 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3755 // TODO: Some of these folds could work with arbitrary constants, but this
3756 // function is limited to scalar and vector splat constants.
3757 if (!Cmp.isEquality())
3758 return nullptr;
3759
3760 ICmpInst::Predicate Pred = Cmp.getPredicate();
3761 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3762 Constant *RHS = cast<Constant>(Val: Cmp.getOperand(i_nocapture: 1));
3763 Value *BOp0 = BO->getOperand(i_nocapture: 0), *BOp1 = BO->getOperand(i_nocapture: 1);
3764
3765 switch (BO->getOpcode()) {
3766 case Instruction::SRem:
3767 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3768 if (C.isZero() && BO->hasOneUse()) {
3769 const APInt *BOC;
3770 if (match(V: BOp1, P: m_APInt(Res&: BOC)) && BOC->sgt(RHS: 1) && BOC->isPowerOf2()) {
3771 Value *NewRem = Builder.CreateURem(LHS: BOp0, RHS: BOp1, Name: BO->getName());
3772 return new ICmpInst(Pred, NewRem,
3773 Constant::getNullValue(Ty: BO->getType()));
3774 }
3775 }
3776 break;
3777 case Instruction::Add: {
3778 // (A + C2) == C --> A == (C - C2)
3779 // (A + C2) != C --> A != (C - C2)
3780 // TODO: Remove the one-use limitation? See discussion in D58633.
3781 if (Constant *C2 = dyn_cast<Constant>(Val: BOp1)) {
3782 if (BO->hasOneUse())
3783 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(C1: RHS, C2));
3784 } else if (C.isZero()) {
3785 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3786 // efficiently invertible, or if the add has just this one use.
3787 if (Value *NegVal = dyn_castNegVal(V: BOp1))
3788 return new ICmpInst(Pred, BOp0, NegVal);
3789 if (Value *NegVal = dyn_castNegVal(V: BOp0))
3790 return new ICmpInst(Pred, NegVal, BOp1);
3791 if (BO->hasOneUse()) {
3792 // (add nuw A, B) != 0 -> (or A, B) != 0
3793 if (match(V: BO, P: m_NUWAdd(L: m_Value(), R: m_Value()))) {
3794 Value *Or = Builder.CreateOr(LHS: BOp0, RHS: BOp1);
3795 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty: BO->getType()));
3796 }
3797 Value *Neg = Builder.CreateNeg(V: BOp1);
3798 Neg->takeName(V: BO);
3799 return new ICmpInst(Pred, BOp0, Neg);
3800 }
3801 }
3802 break;
3803 }
3804 case Instruction::Xor:
3805 if (Constant *BOC = dyn_cast<Constant>(Val: BOp1)) {
3806 // For the xor case, we can xor two constants together, eliminating
3807 // the explicit xor.
3808 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(C1: RHS, C2: BOC));
3809 } else if (C.isZero()) {
3810 // Replace ((xor A, B) != 0) with (A != B)
3811 return new ICmpInst(Pred, BOp0, BOp1);
3812 }
3813 break;
3814 case Instruction::Or: {
3815 const APInt *BOC;
3816 if (match(V: BOp1, P: m_APInt(Res&: BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3817 // Comparing if all bits outside of a constant mask are set?
3818 // Replace (X | C) == -1 with (X & ~C) == ~C.
3819 // This removes the -1 constant.
3820 Constant *NotBOC = ConstantExpr::getNot(C: cast<Constant>(Val: BOp1));
3821 Value *And = Builder.CreateAnd(LHS: BOp0, RHS: NotBOC);
3822 return new ICmpInst(Pred, And, NotBOC);
3823 }
3824 // (icmp eq (or (select cond, 0, NonZero), Other), 0)
3825 // -> (and cond, (icmp eq Other, 0))
3826 // (icmp ne (or (select cond, NonZero, 0), Other), 0)
3827 // -> (or cond, (icmp ne Other, 0))
3828 Value *Cond, *TV, *FV, *Other, *Sel;
3829 if (C.isZero() &&
3830 match(V: BO,
3831 P: m_OneUse(SubPattern: m_c_Or(L: m_CombineAnd(Ps: m_Value(V&: Sel),
3832 Ps: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: TV),
3833 R: m_Value(V&: FV))),
3834 R: m_Value(V&: Other)))) &&
3835 Cond->getType() == Cmp.getType()) {
3836 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
3837 // Easy case is if eq/ne matches whether 0 is trueval/falseval.
3838 if (Pred == ICmpInst::ICMP_EQ
3839 ? (match(V: TV, P: m_Zero()) && isKnownNonZero(V: FV, Q))
3840 : (match(V: FV, P: m_Zero()) && isKnownNonZero(V: TV, Q))) {
3841 Value *Cmp = Builder.CreateICmp(
3842 P: Pred, LHS: Other, RHS: Constant::getNullValue(Ty: Other->getType()));
3843 return BinaryOperator::Create(
3844 Op: Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, S1: Cmp,
3845 S2: Cond);
3846 }
3847 // Harder case is if eq/ne matches whether 0 is falseval/trueval. In this
3848 // case we need to invert the select condition so we need to be careful to
3849 // avoid creating extra instructions.
3850 // (icmp ne (or (select cond, 0, NonZero), Other), 0)
3851 // -> (or (not cond), (icmp ne Other, 0))
3852 // (icmp eq (or (select cond, NonZero, 0), Other), 0)
3853 // -> (and (not cond), (icmp eq Other, 0))
3854 //
3855 // Only do this if the inner select has one use, in which case we are
3856 // replacing `select` with `(not cond)`. Otherwise, we will create more
3857 // uses. NB: Trying to freely invert cond doesn't make sense here, as if
3858 // cond was freely invertable, the select arms would have been inverted.
3859 if (Sel->hasOneUse() &&
3860 (Pred == ICmpInst::ICMP_EQ
3861 ? (match(V: FV, P: m_Zero()) && isKnownNonZero(V: TV, Q))
3862 : (match(V: TV, P: m_Zero()) && isKnownNonZero(V: FV, Q)))) {
3863 Value *NotCond = Builder.CreateNot(V: Cond);
3864 Value *Cmp = Builder.CreateICmp(
3865 P: Pred, LHS: Other, RHS: Constant::getNullValue(Ty: Other->getType()));
3866 return BinaryOperator::Create(
3867 Op: Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, S1: Cmp,
3868 S2: NotCond);
3869 }
3870 }
3871 break;
3872 }
3873 case Instruction::UDiv:
3874 case Instruction::SDiv:
3875 if (BO->isExact()) {
3876 // div exact X, Y eq/ne 0 -> X eq/ne 0
3877 // div exact X, Y eq/ne 1 -> X eq/ne Y
3878 // div exact X, Y eq/ne C ->
3879 // if Y * C never-overflow && OneUse:
3880 // -> Y * C eq/ne X
3881 if (C.isZero())
3882 return new ICmpInst(Pred, BOp0, Constant::getNullValue(Ty: BO->getType()));
3883 else if (C.isOne())
3884 return new ICmpInst(Pred, BOp0, BOp1);
3885 else if (BO->hasOneUse()) {
3886 OverflowResult OR = computeOverflow(
3887 BinaryOp: Instruction::Mul, IsSigned: BO->getOpcode() == Instruction::SDiv, LHS: BOp1,
3888 RHS: Cmp.getOperand(i_nocapture: 1), CtxI: BO);
3889 if (OR == OverflowResult::NeverOverflows) {
3890 Value *YC =
3891 Builder.CreateMul(LHS: BOp1, RHS: ConstantInt::get(Ty: BO->getType(), V: C));
3892 return new ICmpInst(Pred, YC, BOp0);
3893 }
3894 }
3895 }
3896 if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3897 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3898 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3899 return new ICmpInst(NewPred, BOp1, BOp0);
3900 }
3901 break;
3902 default:
3903 break;
3904 }
3905 return nullptr;
3906}
3907
3908static Instruction *foldCtpopPow2Test(ICmpInst &I, IntrinsicInst *CtpopLhs,
3909 const APInt &CRhs,
3910 InstCombiner::BuilderTy &Builder,
3911 const SimplifyQuery &Q) {
3912 assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3913 "Non-ctpop intrin in ctpop fold");
3914 if (!CtpopLhs->hasOneUse())
3915 return nullptr;
3916
3917 // Power of 2 test:
3918 // isPow2OrZero : ctpop(X) u< 2
3919 // isPow2 : ctpop(X) == 1
3920 // NotPow2OrZero: ctpop(X) u> 1
3921 // NotPow2 : ctpop(X) != 1
3922 // If we know any bit of X can be folded to:
3923 // IsPow2 : X & (~Bit) == 0
3924 // NotPow2 : X & (~Bit) != 0
3925 const ICmpInst::Predicate Pred = I.getPredicate();
3926 if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3927 (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3928 Value *Op = CtpopLhs->getArgOperand(i: 0);
3929 KnownBits OpKnown = computeKnownBits(V: Op, DL: Q.DL, AC: Q.AC, CtxI: Q.CtxI, DT: Q.DT);
3930 // No need to check for count > 1, that should be already constant folded.
3931 if (OpKnown.countMinPopulation() == 1) {
3932 Value *And = Builder.CreateAnd(
3933 LHS: Op, RHS: Constant::getIntegerValue(Ty: Op->getType(), V: ~(OpKnown.One)));
3934 return new ICmpInst(
3935 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3936 ? ICmpInst::ICMP_EQ
3937 : ICmpInst::ICMP_NE,
3938 And, Constant::getNullValue(Ty: Op->getType()));
3939 }
3940 }
3941
3942 return nullptr;
3943}
3944
3945/// Fold an equality icmp with LLVM intrinsic and constant operand.
3946Instruction *InstCombinerImpl::foldICmpEqIntrinsicWithConstant(
3947 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3948 Type *Ty = II->getType();
3949 unsigned BitWidth = C.getBitWidth();
3950 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3951
3952 switch (II->getIntrinsicID()) {
3953 case Intrinsic::abs:
3954 // abs(A) == 0 -> A == 0
3955 // abs(A) == INT_MIN -> A == INT_MIN
3956 if (C.isZero() || C.isMinSignedValue())
3957 return new ICmpInst(Pred, II->getArgOperand(i: 0), ConstantInt::get(Ty, V: C));
3958 break;
3959
3960 case Intrinsic::bswap:
3961 // bswap(A) == C -> A == bswap(C)
3962 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3963 ConstantInt::get(Ty, V: C.byteSwap()));
3964
3965 case Intrinsic::bitreverse:
3966 // bitreverse(A) == C -> A == bitreverse(C)
3967 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3968 ConstantInt::get(Ty, V: C.reverseBits()));
3969
3970 case Intrinsic::ctlz:
3971 case Intrinsic::cttz: {
3972 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3973 if (C == BitWidth)
3974 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3975 ConstantInt::getNullValue(Ty));
3976
3977 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3978 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3979 // Limit to one use to ensure we don't increase instruction count.
3980 unsigned Num = C.getLimitedValue(Limit: BitWidth);
3981 if (Num != BitWidth && II->hasOneUse()) {
3982 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3983 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: Num + 1)
3984 : APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: Num + 1);
3985 APInt Mask2 = IsTrailing
3986 ? APInt::getOneBitSet(numBits: BitWidth, BitNo: Num)
3987 : APInt::getOneBitSet(numBits: BitWidth, BitNo: BitWidth - Num - 1);
3988 return new ICmpInst(Pred, Builder.CreateAnd(LHS: II->getArgOperand(i: 0), RHS: Mask1),
3989 ConstantInt::get(Ty, V: Mask2));
3990 }
3991 break;
3992 }
3993
3994 case Intrinsic::ctpop: {
3995 // popcount(A) == 0 -> A == 0 and likewise for !=
3996 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3997 bool IsZero = C.isZero();
3998 if (IsZero || C == BitWidth)
3999 return new ICmpInst(Pred, II->getArgOperand(i: 0),
4000 IsZero ? Constant::getNullValue(Ty)
4001 : Constant::getAllOnesValue(Ty));
4002
4003 break;
4004 }
4005
4006 case Intrinsic::fshl:
4007 case Intrinsic::fshr:
4008 if (II->getArgOperand(i: 0) == II->getArgOperand(i: 1)) {
4009 const APInt *RotAmtC;
4010 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
4011 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
4012 if (match(V: II->getArgOperand(i: 2), P: m_APInt(Res&: RotAmtC)))
4013 return new ICmpInst(Pred, II->getArgOperand(i: 0),
4014 II->getIntrinsicID() == Intrinsic::fshl
4015 ? ConstantInt::get(Ty, V: C.rotr(rotateAmt: *RotAmtC))
4016 : ConstantInt::get(Ty, V: C.rotl(rotateAmt: *RotAmtC)));
4017 }
4018 break;
4019
4020 case Intrinsic::umax:
4021 case Intrinsic::uadd_sat: {
4022 // uadd.sat(a, b) == 0 -> (a | b) == 0
4023 // umax(a, b) == 0 -> (a | b) == 0
4024 if (C.isZero() && II->hasOneUse()) {
4025 Value *Or = Builder.CreateOr(LHS: II->getArgOperand(i: 0), RHS: II->getArgOperand(i: 1));
4026 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
4027 }
4028 break;
4029 }
4030
4031 case Intrinsic::ssub_sat:
4032 // ssub.sat(a, b) == 0 -> a == b
4033 //
4034 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4035 // (because 1 saturates to 0). Just skip the optimization for i1.
4036 if (C.isZero() && II->getType()->getScalarSizeInBits() > 1)
4037 return new ICmpInst(Pred, II->getArgOperand(i: 0), II->getArgOperand(i: 1));
4038 break;
4039 case Intrinsic::usub_sat: {
4040 // usub.sat(a, b) == 0 -> a <= b
4041 if (C.isZero()) {
4042 ICmpInst::Predicate NewPred =
4043 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
4044 return new ICmpInst(NewPred, II->getArgOperand(i: 0), II->getArgOperand(i: 1));
4045 }
4046 break;
4047 }
4048 default:
4049 break;
4050 }
4051
4052 return nullptr;
4053}
4054
4055/// Fold an icmp with LLVM intrinsics
4056static Instruction *
4057foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp,
4058 InstCombiner::BuilderTy &Builder) {
4059 assert(Cmp.isEquality());
4060
4061 ICmpInst::Predicate Pred = Cmp.getPredicate();
4062 Value *Op0 = Cmp.getOperand(i_nocapture: 0);
4063 Value *Op1 = Cmp.getOperand(i_nocapture: 1);
4064 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Val: Op0);
4065 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Val: Op1);
4066 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
4067 return nullptr;
4068
4069 switch (IIOp0->getIntrinsicID()) {
4070 case Intrinsic::bswap:
4071 case Intrinsic::bitreverse:
4072 // If both operands are byte-swapped or bit-reversed, just compare the
4073 // original values.
4074 return new ICmpInst(Pred, IIOp0->getOperand(i_nocapture: 0), IIOp1->getOperand(i_nocapture: 0));
4075 case Intrinsic::fshl:
4076 case Intrinsic::fshr: {
4077 // If both operands are rotated by same amount, just compare the
4078 // original values.
4079 if (IIOp0->getOperand(i_nocapture: 0) != IIOp0->getOperand(i_nocapture: 1))
4080 break;
4081 if (IIOp1->getOperand(i_nocapture: 0) != IIOp1->getOperand(i_nocapture: 1))
4082 break;
4083 if (IIOp0->getOperand(i_nocapture: 2) == IIOp1->getOperand(i_nocapture: 2))
4084 return new ICmpInst(Pred, IIOp0->getOperand(i_nocapture: 0), IIOp1->getOperand(i_nocapture: 0));
4085
4086 // rotate(X, AmtX) == rotate(Y, AmtY)
4087 // -> rotate(X, AmtX - AmtY) == Y
4088 // Do this if either both rotates have one use or if only one has one use
4089 // and AmtX/AmtY are constants.
4090 const unsigned BW = IIOp0->getType()->getScalarSizeInBits();
4091 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
4092 if (OneUses == 2 ||
4093 (OneUses == 1 && match(V: IIOp0->getOperand(i_nocapture: 2), P: m_ImmConstant()) &&
4094 match(V: IIOp1->getOperand(i_nocapture: 2), P: m_ImmConstant()))) {
4095
4096 // Only valid assuming (2**BW) % BW == 0, which only holds for powers
4097 // of two.
4098 if (isPowerOf2_32(Value: BW)) {
4099 Value *SubAmt =
4100 Builder.CreateSub(LHS: IIOp0->getOperand(i_nocapture: 2), RHS: IIOp1->getOperand(i_nocapture: 2));
4101 Value *CombinedRotate = Builder.CreateIntrinsic(
4102 RetTy: Op0->getType(), ID: IIOp0->getIntrinsicID(),
4103 Args: {IIOp0->getOperand(i_nocapture: 0), IIOp0->getOperand(i_nocapture: 0), SubAmt});
4104 return new ICmpInst(Pred, IIOp1->getOperand(i_nocapture: 0), CombinedRotate);
4105 }
4106 }
4107 } break;
4108 default:
4109 break;
4110 }
4111
4112 return nullptr;
4113}
4114
4115/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
4116/// where X is some kind of instruction and C is AllowPoison.
4117/// TODO: Move more folds which allow poison to this function.
4118Instruction *
4119InstCombinerImpl::foldICmpInstWithConstantAllowPoison(ICmpInst &Cmp,
4120 const APInt &C) {
4121 const ICmpInst::Predicate Pred = Cmp.getPredicate();
4122 if (auto *II = dyn_cast<IntrinsicInst>(Val: Cmp.getOperand(i_nocapture: 0))) {
4123 switch (II->getIntrinsicID()) {
4124 default:
4125 break;
4126 case Intrinsic::fshl:
4127 case Intrinsic::fshr:
4128 if (Cmp.isEquality() && II->getArgOperand(i: 0) == II->getArgOperand(i: 1)) {
4129 // (rot X, ?) == 0/-1 --> X == 0/-1
4130 if (C.isZero() || C.isAllOnes())
4131 return new ICmpInst(Pred, II->getArgOperand(i: 0), Cmp.getOperand(i_nocapture: 1));
4132 }
4133 break;
4134 }
4135 }
4136
4137 return nullptr;
4138}
4139
4140/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
4141Instruction *InstCombinerImpl::foldICmpBinOpWithConstant(ICmpInst &Cmp,
4142 BinaryOperator *BO,
4143 const APInt &C) {
4144 switch (BO->getOpcode()) {
4145 case Instruction::Xor:
4146 if (Instruction *I = foldICmpXorConstant(Cmp, Xor: BO, C))
4147 return I;
4148 break;
4149 case Instruction::And:
4150 if (Instruction *I = foldICmpAndConstant(Cmp, And: BO, C))
4151 return I;
4152 break;
4153 case Instruction::Or:
4154 if (Instruction *I = foldICmpOrConstant(Cmp, Or: BO, C))
4155 return I;
4156 break;
4157 case Instruction::Mul:
4158 if (Instruction *I = foldICmpMulConstant(Cmp, Mul: BO, C))
4159 return I;
4160 break;
4161 case Instruction::Shl:
4162 if (Instruction *I = foldICmpShlConstant(Cmp, Shl: BO, C))
4163 return I;
4164 break;
4165 case Instruction::LShr:
4166 case Instruction::AShr:
4167 if (Instruction *I = foldICmpShrConstant(Cmp, Shr: BO, C))
4168 return I;
4169 break;
4170 case Instruction::SRem:
4171 if (Instruction *I = foldICmpSRemConstant(Cmp, SRem: BO, C))
4172 return I;
4173 break;
4174 case Instruction::UDiv:
4175 if (Instruction *I = foldICmpUDivConstant(Cmp, UDiv: BO, C))
4176 return I;
4177 [[fallthrough]];
4178 case Instruction::SDiv:
4179 if (Instruction *I = foldICmpDivConstant(Cmp, Div: BO, C))
4180 return I;
4181 break;
4182 case Instruction::Sub:
4183 if (Instruction *I = foldICmpSubConstant(Cmp, Sub: BO, C))
4184 return I;
4185 break;
4186 case Instruction::Add:
4187 if (Instruction *I = foldICmpAddConstant(Cmp, Add: BO, C))
4188 return I;
4189 break;
4190 default:
4191 break;
4192 }
4193
4194 // TODO: These folds could be refactored to be part of the above calls.
4195 if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, C))
4196 return I;
4197
4198 // Fall back to handling `icmp pred (select A ? C1 : C2) binop (select B ? C3
4199 // : C4), C5` pattern, by computing a truth table of the four constant
4200 // variants.
4201 return foldICmpBinOpWithConstantViaTruthTable(Cmp, BO, C);
4202}
4203
4204static Instruction *
4205foldICmpUSubSatOrUAddSatWithConstant(CmpPredicate Pred, SaturatingInst *II,
4206 const APInt &C,
4207 InstCombiner::BuilderTy &Builder) {
4208 // This transform may end up producing more than one instruction for the
4209 // intrinsic, so limit it to one user of the intrinsic.
4210 if (!II->hasOneUse())
4211 return nullptr;
4212
4213 // Let Y = [add/sub]_sat(X, C) pred C2
4214 // SatVal = The saturating value for the operation
4215 // WillWrap = Whether or not the operation will underflow / overflow
4216 // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
4217 // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
4218 //
4219 // When (SatVal pred C2) is true, then
4220 // Y = WillWrap ? true : ((X binop C) pred C2)
4221 // => Y = WillWrap || ((X binop C) pred C2)
4222 // else
4223 // Y = WillWrap ? false : ((X binop C) pred C2)
4224 // => Y = !WillWrap ? ((X binop C) pred C2) : false
4225 // => Y = !WillWrap && ((X binop C) pred C2)
4226 Value *Op0 = II->getOperand(i_nocapture: 0);
4227 Value *Op1 = II->getOperand(i_nocapture: 1);
4228
4229 const APInt *COp1;
4230 // This transform only works when the intrinsic has an integral constant or
4231 // splat vector as the second operand.
4232 if (!match(V: Op1, P: m_APInt(Res&: COp1)))
4233 return nullptr;
4234
4235 APInt SatVal;
4236 switch (II->getIntrinsicID()) {
4237 default:
4238 llvm_unreachable(
4239 "This function only works with usub_sat and uadd_sat for now!");
4240 case Intrinsic::uadd_sat:
4241 SatVal = APInt::getAllOnes(numBits: C.getBitWidth());
4242 break;
4243 case Intrinsic::usub_sat:
4244 SatVal = APInt::getZero(numBits: C.getBitWidth());
4245 break;
4246 }
4247
4248 // Check (SatVal pred C2)
4249 bool SatValCheck = ICmpInst::compare(LHS: SatVal, RHS: C, Pred);
4250
4251 // !WillWrap.
4252 ConstantRange C1 = ConstantRange::makeExactNoWrapRegion(
4253 BinOp: II->getBinaryOp(), Other: *COp1, NoWrapKind: II->getNoWrapKind());
4254
4255 // WillWrap.
4256 if (SatValCheck)
4257 C1 = C1.inverse();
4258
4259 ConstantRange C2 = ConstantRange::makeExactICmpRegion(Pred, Other: C);
4260 if (II->getBinaryOp() == Instruction::Add)
4261 C2 = C2.sub(Other: *COp1);
4262 else
4263 C2 = C2.add(Other: *COp1);
4264
4265 Instruction::BinaryOps CombiningOp =
4266 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4267
4268 std::optional<ConstantRange> Combination;
4269 if (CombiningOp == Instruction::BinaryOps::Or)
4270 Combination = C1.exactUnionWith(CR: C2);
4271 else /* CombiningOp == Instruction::BinaryOps::And */
4272 Combination = C1.exactIntersectWith(CR: C2);
4273
4274 if (!Combination)
4275 return nullptr;
4276
4277 CmpInst::Predicate EquivPred;
4278 APInt EquivInt;
4279 APInt EquivOffset;
4280
4281 Combination->getEquivalentICmp(Pred&: EquivPred, RHS&: EquivInt, Offset&: EquivOffset);
4282
4283 return new ICmpInst(
4284 EquivPred,
4285 Builder.CreateAdd(LHS: Op0, RHS: ConstantInt::get(Ty: Op1->getType(), V: EquivOffset)),
4286 ConstantInt::get(Ty: Op1->getType(), V: EquivInt));
4287}
4288
4289static Instruction *
4290foldICmpOfCmpIntrinsicWithConstant(CmpPredicate Pred, IntrinsicInst *I,
4291 const APInt &C,
4292 InstCombiner::BuilderTy &Builder) {
4293 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4294 switch (Pred) {
4295 case ICmpInst::ICMP_EQ:
4296 case ICmpInst::ICMP_NE:
4297 if (C.isZero())
4298 NewPredicate = Pred;
4299 else if (C.isOne())
4300 NewPredicate =
4301 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
4302 else if (C.isAllOnes())
4303 NewPredicate =
4304 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
4305 break;
4306
4307 case ICmpInst::ICMP_SGT:
4308 if (C.isAllOnes())
4309 NewPredicate = ICmpInst::ICMP_UGE;
4310 else if (C.isZero())
4311 NewPredicate = ICmpInst::ICMP_UGT;
4312 break;
4313
4314 case ICmpInst::ICMP_SLT:
4315 if (C.isZero())
4316 NewPredicate = ICmpInst::ICMP_ULT;
4317 else if (C.isOne())
4318 NewPredicate = ICmpInst::ICMP_ULE;
4319 break;
4320
4321 case ICmpInst::ICMP_ULT:
4322 if (C.ugt(RHS: 1))
4323 NewPredicate = ICmpInst::ICMP_UGE;
4324 break;
4325
4326 case ICmpInst::ICMP_UGT:
4327 if (!C.isZero() && !C.isAllOnes())
4328 NewPredicate = ICmpInst::ICMP_ULT;
4329 break;
4330
4331 default:
4332 break;
4333 }
4334
4335 if (!NewPredicate)
4336 return nullptr;
4337
4338 if (I->getIntrinsicID() == Intrinsic::scmp)
4339 NewPredicate = ICmpInst::getSignedPredicate(Pred: *NewPredicate);
4340 Value *LHS = I->getOperand(i_nocapture: 0);
4341 Value *RHS = I->getOperand(i_nocapture: 1);
4342 return new ICmpInst(*NewPredicate, LHS, RHS);
4343}
4344
4345/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
4346Instruction *InstCombinerImpl::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
4347 IntrinsicInst *II,
4348 const APInt &C) {
4349 ICmpInst::Predicate Pred = Cmp.getPredicate();
4350
4351 // Handle folds that apply for any kind of icmp.
4352 switch (II->getIntrinsicID()) {
4353 default:
4354 break;
4355 case Intrinsic::uadd_sat:
4356 case Intrinsic::usub_sat:
4357 if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(
4358 Pred, II: cast<SaturatingInst>(Val: II), C, Builder))
4359 return Folded;
4360 break;
4361 case Intrinsic::ctpop: {
4362 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
4363 if (Instruction *R = foldCtpopPow2Test(I&: Cmp, CtpopLhs: II, CRhs: C, Builder, Q))
4364 return R;
4365 } break;
4366 case Intrinsic::scmp:
4367 case Intrinsic::ucmp:
4368 if (auto *Folded = foldICmpOfCmpIntrinsicWithConstant(Pred, I: II, C, Builder))
4369 return Folded;
4370 break;
4371 }
4372
4373 if (Cmp.isEquality())
4374 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
4375
4376 Type *Ty = II->getType();
4377 unsigned BitWidth = C.getBitWidth();
4378 switch (II->getIntrinsicID()) {
4379 case Intrinsic::ctpop: {
4380 // (ctpop X > BitWidth - 1) --> X == -1
4381 Value *X = II->getArgOperand(i: 0);
4382 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
4383 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_EQ, S1: X,
4384 S2: ConstantInt::getAllOnesValue(Ty));
4385 // (ctpop X < BitWidth) --> X != -1
4386 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
4387 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_NE, S1: X,
4388 S2: ConstantInt::getAllOnesValue(Ty));
4389 break;
4390 }
4391 case Intrinsic::ctlz: {
4392 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
4393 if (Pred == ICmpInst::ICMP_UGT && C.ult(RHS: BitWidth)) {
4394 unsigned Num = C.getLimitedValue();
4395 APInt Limit = APInt::getOneBitSet(numBits: BitWidth, BitNo: BitWidth - Num - 1);
4396 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_ULT,
4397 S1: II->getArgOperand(i: 0), S2: ConstantInt::get(Ty, V: Limit));
4398 }
4399
4400 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
4401 if (Pred == ICmpInst::ICMP_ULT && C.uge(RHS: 1) && C.ule(RHS: BitWidth)) {
4402 unsigned Num = C.getLimitedValue();
4403 APInt Limit = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: BitWidth - Num);
4404 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_UGT,
4405 S1: II->getArgOperand(i: 0), S2: ConstantInt::get(Ty, V: Limit));
4406 }
4407 break;
4408 }
4409 case Intrinsic::cttz: {
4410 // Limit to one use to ensure we don't increase instruction count.
4411 if (!II->hasOneUse())
4412 return nullptr;
4413
4414 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
4415 if (Pred == ICmpInst::ICMP_UGT && C.ult(RHS: BitWidth)) {
4416 APInt Mask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: C.getLimitedValue() + 1);
4417 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_EQ,
4418 S1: Builder.CreateAnd(LHS: II->getArgOperand(i: 0), RHS: Mask),
4419 S2: ConstantInt::getNullValue(Ty));
4420 }
4421
4422 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
4423 if (Pred == ICmpInst::ICMP_ULT && C.uge(RHS: 1) && C.ule(RHS: BitWidth)) {
4424 APInt Mask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: C.getLimitedValue());
4425 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_NE,
4426 S1: Builder.CreateAnd(LHS: II->getArgOperand(i: 0), RHS: Mask),
4427 S2: ConstantInt::getNullValue(Ty));
4428 }
4429 break;
4430 }
4431 case Intrinsic::ssub_sat:
4432 // ssub.sat(a, b) spred 0 -> a spred b
4433 //
4434 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4435 // (because 1 saturates to 0). Just skip the optimization for i1.
4436 if (ICmpInst::isSigned(Pred) && C.getBitWidth() > 1) {
4437 if (C.isZero())
4438 return new ICmpInst(Pred, II->getArgOperand(i: 0), II->getArgOperand(i: 1));
4439 // X s<= 0 is cannonicalized to X s< 1
4440 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
4441 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(i: 0),
4442 II->getArgOperand(i: 1));
4443 // X s>= 0 is cannonicalized to X s> -1
4444 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
4445 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(i: 0),
4446 II->getArgOperand(i: 1));
4447 }
4448 break;
4449 case Intrinsic::abs: {
4450 if (!II->hasOneUse())
4451 return nullptr;
4452
4453 Value *X = II->getArgOperand(i: 0);
4454
4455 // If C >= 0:
4456 // abs(X) u> C --> X + C u> 2 * C
4457 if (Pred == CmpInst::ICMP_UGT && C.isNonNegative()) {
4458 return new ICmpInst(ICmpInst::ICMP_UGT,
4459 Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: C)),
4460 ConstantInt::get(Ty, V: 2 * C));
4461 }
4462
4463 // If C >= 1:
4464 // abs(X) u< C --> X + (C - 1) u<= 2 * (C - 1)
4465 if (Pred == CmpInst::ICMP_ULT && C.sge(RHS: 1))
4466 return new ICmpInst(ICmpInst::ICMP_ULE,
4467 Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: C - 1)),
4468 ConstantInt::get(Ty, V: 2 * (C - 1)));
4469
4470 break;
4471 }
4472 default:
4473 break;
4474 }
4475
4476 return nullptr;
4477}
4478
4479/// Handle icmp with constant (but not simple integer constant) RHS.
4480Instruction *InstCombinerImpl::foldICmpInstWithConstantNotInt(ICmpInst &I) {
4481 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
4482 Constant *RHSC = dyn_cast<Constant>(Val: Op1);
4483 Instruction *LHSI = dyn_cast<Instruction>(Val: Op0);
4484 if (!RHSC || !LHSI)
4485 return nullptr;
4486
4487 switch (LHSI->getOpcode()) {
4488 case Instruction::IntToPtr:
4489 // icmp pred inttoptr(X), null -> icmp pred X, null pointer value
4490 if (isa<ConstantPointerNull>(Val: RHSC)) {
4491 Type *IntPtrTy = DL.getIntPtrType(RHSC->getType());
4492 if (IntPtrTy == LHSI->getOperand(i: 0)->getType()) {
4493 APInt NullPtrValue =
4494 DL.getNullPtrValue(AS: RHSC->getType()->getPointerAddressSpace());
4495 return new ICmpInst(I.getPredicate(), LHSI->getOperand(i: 0),
4496 Constant::getIntegerValue(Ty: IntPtrTy, V: NullPtrValue));
4497 }
4498 }
4499 break;
4500
4501 case Instruction::Load:
4502 // Try to optimize things like "A[i] > 4" to index computations.
4503 if (GetElementPtrInst *GEP =
4504 dyn_cast<GetElementPtrInst>(Val: LHSI->getOperand(i: 0)))
4505 if (Instruction *Res =
4506 foldCmpLoadFromIndexedGlobal(LI: cast<LoadInst>(Val: LHSI), GEP, ICI&: I))
4507 return Res;
4508 break;
4509 }
4510
4511 return nullptr;
4512}
4513
4514Instruction *InstCombinerImpl::foldSelectICmp(CmpPredicate Pred, SelectInst *SI,
4515 Value *RHS, const ICmpInst &I) {
4516 // Try to fold the comparison into the select arms, which will cause the
4517 // select to be converted into a logical and/or.
4518 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
4519 if (Value *Res = simplifyICmpInst(Pred, LHS: Op, RHS, Q: SQ))
4520 return Res;
4521 if (std::optional<bool> Impl = isImpliedCondition(
4522 LHS: SI->getCondition(), RHSPred: Pred, RHSOp0: Op, RHSOp1: RHS, DL, LHSIsTrue: SelectCondIsTrue))
4523 return ConstantInt::get(Ty: I.getType(), V: *Impl);
4524 return nullptr;
4525 };
4526
4527 ConstantInt *CI = nullptr;
4528 Value *Op1 = SimplifyOp(SI->getOperand(i_nocapture: 1), true);
4529 if (Op1)
4530 CI = dyn_cast<ConstantInt>(Val: Op1);
4531
4532 Value *Op2 = SimplifyOp(SI->getOperand(i_nocapture: 2), false);
4533 if (Op2)
4534 CI = dyn_cast<ConstantInt>(Val: Op2);
4535
4536 auto Simplifies = [&](Value *Op, unsigned Idx) {
4537 // A comparison of ucmp/scmp with a constant will fold into an icmp.
4538 const APInt *Dummy;
4539 return Op ||
4540 (isa<CmpIntrinsic>(Val: SI->getOperand(i_nocapture: Idx)) &&
4541 SI->getOperand(i_nocapture: Idx)->hasOneUse() && match(V: RHS, P: m_APInt(Res&: Dummy)));
4542 };
4543
4544 // We only want to perform this transformation if it will not lead to
4545 // additional code. This is true if either both sides of the select
4546 // fold to a constant (in which case the icmp is replaced with a select
4547 // which will usually simplify) or this is the only user of the
4548 // select (in which case we are trading a select+icmp for a simpler
4549 // select+icmp) or all uses of the select can be replaced based on
4550 // dominance information ("Global cases").
4551 bool Transform = false;
4552 if (Op1 && Op2)
4553 Transform = true;
4554 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4555 // Local case
4556 if (SI->hasOneUse())
4557 Transform = true;
4558 // Global cases
4559 else if (CI && !CI->isZero())
4560 // When Op1 is constant try replacing select with second operand.
4561 // Otherwise Op2 is constant and try replacing select with first
4562 // operand.
4563 Transform = replacedSelectWithOperand(SI, Icmp: &I, SIOpd: Op1 ? 2 : 1);
4564 }
4565 if (Transform) {
4566 if (!Op1)
4567 Op1 = Builder.CreateICmp(P: Pred, LHS: SI->getOperand(i_nocapture: 1), RHS, Name: I.getName());
4568 if (!Op2)
4569 Op2 = Builder.CreateICmp(P: Pred, LHS: SI->getOperand(i_nocapture: 2), RHS, Name: I.getName());
4570 return SelectInst::Create(C: SI->getOperand(i_nocapture: 0), S1: Op1, S2: Op2, NameStr: "", InsertBefore: nullptr, MDFrom: SI);
4571 }
4572
4573 // Fold icmp eq/ne X, select(icmp pred X, P, C1, C2)
4574 // When the select condition compares X with a constant P and the select
4575 // arms are constants C1/C2, we can fold to a set membership test.
4576 // Example: X == select(X >s 0, 2, 0) -> (X == 2) | (X == 0)
4577 // This is valid when C1 satisfies the condition (C1 >s 0) and C2 does not.
4578 if (ICmpInst::isEquality(P: Pred)) {
4579 CmpPredicate CondPred;
4580 const APInt *C1, *C2, *P;
4581 if (match(V: SI,
4582 P: m_OneUse(SubPattern: m_Select(C: m_ICmp(Pred&: CondPred, L: m_Specific(V: RHS), R: m_APInt(Res&: P)),
4583 L: m_APInt(Res&: C1), R: m_APInt(Res&: C2))))) {
4584 bool C1SatisfiesCond = ICmpInst::compare(LHS: *C1, RHS: *P, Pred: CondPred);
4585 bool C2SatisfiesCond = ICmpInst::compare(LHS: *C2, RHS: *P, Pred: CondPred);
4586
4587 if (C1SatisfiesCond && !C2SatisfiesCond) {
4588 // X == select(cond, C1, C2) -> (X == C1) | (X == C2)
4589 // X != select(cond, C1, C2) -> (X != C1) & (X != C2)
4590 Value *Cmp1 = Builder.CreateICmp(P: Pred, LHS: RHS, RHS: SI->getTrueValue());
4591 Value *Cmp2 = Builder.CreateICmp(P: Pred, LHS: RHS, RHS: SI->getFalseValue());
4592 if (Pred == ICmpInst::ICMP_EQ)
4593 return BinaryOperator::CreateOr(V1: Cmp1, V2: Cmp2);
4594 return BinaryOperator::CreateAnd(V1: Cmp1, V2: Cmp2);
4595 }
4596 }
4597 }
4598
4599 return nullptr;
4600}
4601
4602// Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)
4603static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,
4604 unsigned Depth = 0) {
4605 if (Not ? match(V, P: m_NegatedPower2OrZero()) : match(V, P: m_LowBitMaskOrZero()))
4606 return true;
4607 if (V->getType()->getScalarSizeInBits() == 1)
4608 return true;
4609 if (Depth++ >= MaxAnalysisRecursionDepth)
4610 return false;
4611 Value *X;
4612 const Instruction *I = dyn_cast<Instruction>(Val: V);
4613 if (!I)
4614 return false;
4615 switch (I->getOpcode()) {
4616 case Instruction::ZExt:
4617 // ZExt(Mask) is a Mask.
4618 return !Not && isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4619 case Instruction::SExt:
4620 // SExt(Mask) is a Mask.
4621 // SExt(~Mask) is a ~Mask.
4622 return isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4623 case Instruction::And:
4624 case Instruction::Or:
4625 // Mask0 | Mask1 is a Mask.
4626 // Mask0 & Mask1 is a Mask.
4627 // ~Mask0 | ~Mask1 is a ~Mask.
4628 // ~Mask0 & ~Mask1 is a ~Mask.
4629 return isMaskOrZero(V: I->getOperand(i: 1), Not, Q, Depth) &&
4630 isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4631 case Instruction::Xor:
4632 if (match(V, P: m_Not(V: m_Value(V&: X))))
4633 return isMaskOrZero(V: X, Not: !Not, Q, Depth);
4634
4635 // (X ^ -X) is a ~Mask
4636 if (Not)
4637 return match(V, P: m_c_Xor(L: m_Value(V&: X), R: m_Neg(V: m_Deferred(V: X))));
4638 // (X ^ (X - 1)) is a Mask
4639 else
4640 return match(V, P: m_c_Xor(L: m_Value(V&: X), R: m_Add(L: m_Deferred(V: X), R: m_AllOnes())));
4641 case Instruction::Select:
4642 // c ? Mask0 : Mask1 is a Mask.
4643 return isMaskOrZero(V: I->getOperand(i: 1), Not, Q, Depth) &&
4644 isMaskOrZero(V: I->getOperand(i: 2), Not, Q, Depth);
4645 case Instruction::Shl:
4646 // (~Mask) << X is a ~Mask.
4647 return Not && isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4648 case Instruction::LShr:
4649 // Mask >> X is a Mask.
4650 return !Not && isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4651 case Instruction::AShr:
4652 // Mask s>> X is a Mask.
4653 // ~Mask s>> X is a ~Mask.
4654 return isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4655 case Instruction::Add:
4656 // Pow2 - 1 is a Mask.
4657 if (!Not && match(V: I->getOperand(i: 1), P: m_AllOnes()))
4658 return isKnownToBeAPowerOfTwo(V: I->getOperand(i: 0), DL: Q.DL, /*OrZero*/ true,
4659 AC: Q.AC, CtxI: Q.CtxI, DT: Q.DT, UseInstrInfo: Depth);
4660 break;
4661 case Instruction::Sub:
4662 // -Pow2 is a ~Mask.
4663 if (Not && match(V: I->getOperand(i: 0), P: m_Zero()))
4664 return isKnownToBeAPowerOfTwo(V: I->getOperand(i: 1), DL: Q.DL, /*OrZero*/ true,
4665 AC: Q.AC, CtxI: Q.CtxI, DT: Q.DT, UseInstrInfo: Depth);
4666 break;
4667 case Instruction::Call: {
4668 if (auto *II = dyn_cast<IntrinsicInst>(Val: I)) {
4669 switch (II->getIntrinsicID()) {
4670 // min/max(Mask0, Mask1) is a Mask.
4671 // min/max(~Mask0, ~Mask1) is a ~Mask.
4672 case Intrinsic::umax:
4673 case Intrinsic::smax:
4674 case Intrinsic::umin:
4675 case Intrinsic::smin:
4676 return isMaskOrZero(V: II->getArgOperand(i: 1), Not, Q, Depth) &&
4677 isMaskOrZero(V: II->getArgOperand(i: 0), Not, Q, Depth);
4678
4679 // In the context of masks, bitreverse(Mask) == ~Mask
4680 case Intrinsic::bitreverse:
4681 return isMaskOrZero(V: II->getArgOperand(i: 0), Not: !Not, Q, Depth);
4682 default:
4683 break;
4684 }
4685 }
4686 break;
4687 }
4688 default:
4689 break;
4690 }
4691 return false;
4692}
4693
4694/// Some comparisons can be simplified.
4695/// In this case, we are looking for comparisons that look like
4696/// a check for a lossy truncation.
4697/// Folds:
4698/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
4699/// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask
4700/// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask
4701/// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask
4702/// Where Mask is some pattern that produces all-ones in low bits:
4703/// (-1 >> y)
4704/// ((-1 << y) >> y) <- non-canonical, has extra uses
4705/// ~(-1 << y)
4706/// ((1 << y) + (-1)) <- non-canonical, has extra uses
4707/// The Mask can be a constant, too.
4708/// For some predicates, the operands are commutative.
4709/// For others, x can only be on a specific side.
4710static Value *foldICmpWithLowBitMaskedVal(CmpPredicate Pred, Value *Op0,
4711 Value *Op1, const SimplifyQuery &Q,
4712 InstCombiner &IC) {
4713
4714 ICmpInst::Predicate DstPred;
4715 switch (Pred) {
4716 case ICmpInst::Predicate::ICMP_EQ:
4717 // x & Mask == x
4718 // x & ~Mask == 0
4719 // ~x | Mask == -1
4720 // -> x u<= Mask
4721 // x & ~Mask == ~Mask
4722 // -> ~Mask u<= x
4723 DstPred = ICmpInst::Predicate::ICMP_ULE;
4724 break;
4725 case ICmpInst::Predicate::ICMP_NE:
4726 // x & Mask != x
4727 // x & ~Mask != 0
4728 // ~x | Mask != -1
4729 // -> x u> Mask
4730 // x & ~Mask != ~Mask
4731 // -> ~Mask u> x
4732 DstPred = ICmpInst::Predicate::ICMP_UGT;
4733 break;
4734 case ICmpInst::Predicate::ICMP_ULT:
4735 // x & Mask u< x
4736 // -> x u> Mask
4737 // x & ~Mask u< ~Mask
4738 // -> ~Mask u> x
4739 DstPred = ICmpInst::Predicate::ICMP_UGT;
4740 break;
4741 case ICmpInst::Predicate::ICMP_UGE:
4742 // x & Mask u>= x
4743 // -> x u<= Mask
4744 // x & ~Mask u>= ~Mask
4745 // -> ~Mask u<= x
4746 DstPred = ICmpInst::Predicate::ICMP_ULE;
4747 break;
4748 case ICmpInst::Predicate::ICMP_SLT:
4749 // x & Mask s< x [iff Mask s>= 0]
4750 // -> x s> Mask
4751 // x & ~Mask s< ~Mask [iff ~Mask != 0]
4752 // -> ~Mask s> x
4753 DstPred = ICmpInst::Predicate::ICMP_SGT;
4754 break;
4755 case ICmpInst::Predicate::ICMP_SGE:
4756 // x & Mask s>= x [iff Mask s>= 0]
4757 // -> x s<= Mask
4758 // x & ~Mask s>= ~Mask [iff ~Mask != 0]
4759 // -> ~Mask s<= x
4760 DstPred = ICmpInst::Predicate::ICMP_SLE;
4761 break;
4762 default:
4763 // We don't support sgt,sle
4764 // ult/ugt are simplified to true/false respectively.
4765 return nullptr;
4766 }
4767
4768 Value *X, *M;
4769 // Put search code in lambda for early positive returns.
4770 auto IsLowBitMask = [&]() {
4771 if (match(V: Op0, P: m_c_And(L: m_Specific(V: Op1), R: m_Value(V&: M)))) {
4772 X = Op1;
4773 // Look for: x & Mask pred x
4774 if (isMaskOrZero(V: M, /*Not=*/false, Q)) {
4775 return !ICmpInst::isSigned(Pred) ||
4776 (match(V: M, P: m_NonNegative()) || isKnownNonNegative(V: M, SQ: Q));
4777 }
4778
4779 // Look for: x & ~Mask pred ~Mask
4780 if (isMaskOrZero(V: X, /*Not=*/true, Q)) {
4781 return !ICmpInst::isSigned(Pred) || isKnownNonZero(V: X, Q);
4782 }
4783 return false;
4784 }
4785 if (ICmpInst::isEquality(P: Pred) && match(V: Op1, P: m_AllOnes()) &&
4786 match(V: Op0, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: X), R: m_Value(V&: M))))) {
4787
4788 auto Check = [&]() {
4789 // Look for: ~x | Mask == -1
4790 if (isMaskOrZero(V: M, /*Not=*/false, Q)) {
4791 if (Value *NotX =
4792 IC.getFreelyInverted(V: X, WillInvertAllUses: X->hasOneUse(), Builder: &IC.Builder)) {
4793 X = NotX;
4794 return true;
4795 }
4796 }
4797 return false;
4798 };
4799 if (Check())
4800 return true;
4801 std::swap(a&: X, b&: M);
4802 return Check();
4803 }
4804 if (ICmpInst::isEquality(P: Pred) && match(V: Op1, P: m_Zero()) &&
4805 match(V: Op0, P: m_OneUse(SubPattern: m_And(L: m_Value(V&: X), R: m_Value(V&: M))))) {
4806 auto Check = [&]() {
4807 // Look for: x & ~Mask == 0
4808 if (isMaskOrZero(V: M, /*Not=*/true, Q)) {
4809 if (Value *NotM =
4810 IC.getFreelyInverted(V: M, WillInvertAllUses: M->hasOneUse(), Builder: &IC.Builder)) {
4811 M = NotM;
4812 return true;
4813 }
4814 }
4815 return false;
4816 };
4817 if (Check())
4818 return true;
4819 std::swap(a&: X, b&: M);
4820 return Check();
4821 }
4822 return false;
4823 };
4824
4825 if (!IsLowBitMask())
4826 return nullptr;
4827
4828 return IC.Builder.CreateICmp(P: DstPred, LHS: X, RHS: M);
4829}
4830
4831/// Some comparisons can be simplified.
4832/// In this case, we are looking for comparisons that look like
4833/// a check for a lossy signed truncation.
4834/// Folds: (MaskedBits is a constant.)
4835/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4836/// Into:
4837/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4838/// Where KeptBits = bitwidth(%x) - MaskedBits
4839static Value *
4840foldICmpWithTruncSignExtendedVal(ICmpInst &I,
4841 InstCombiner::BuilderTy &Builder) {
4842 CmpPredicate SrcPred;
4843 Value *X;
4844 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4845 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4846 if (!match(V: &I, P: m_c_ICmp(Pred&: SrcPred,
4847 L: m_OneUse(SubPattern: m_AShr(L: m_Shl(L: m_Value(V&: X), R: m_APInt(Res&: C0)),
4848 R: m_APInt(Res&: C1))),
4849 R: m_Deferred(V: X))))
4850 return nullptr;
4851
4852 // Potential handling of non-splats: for each element:
4853 // * if both are undef, replace with constant 0.
4854 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4855 // * if both are not undef, and are different, bailout.
4856 // * else, only one is undef, then pick the non-undef one.
4857
4858 // The shift amount must be equal.
4859 if (*C0 != *C1)
4860 return nullptr;
4861 const APInt &MaskedBits = *C0;
4862 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4863
4864 ICmpInst::Predicate DstPred;
4865 switch (SrcPred) {
4866 case ICmpInst::Predicate::ICMP_EQ:
4867 // ((%x << MaskedBits) a>> MaskedBits) == %x
4868 // =>
4869 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4870 DstPred = ICmpInst::Predicate::ICMP_ULT;
4871 break;
4872 case ICmpInst::Predicate::ICMP_NE:
4873 // ((%x << MaskedBits) a>> MaskedBits) != %x
4874 // =>
4875 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4876 DstPred = ICmpInst::Predicate::ICMP_UGE;
4877 break;
4878 // FIXME: are more folds possible?
4879 default:
4880 return nullptr;
4881 }
4882
4883 auto *XType = X->getType();
4884 const unsigned XBitWidth = XType->getScalarSizeInBits();
4885 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4886 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4887
4888 // KeptBits = bitwidth(%x) - MaskedBits
4889 const APInt KeptBits = BitWidth - MaskedBits;
4890 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4891 // ICmpCst = (1 << KeptBits)
4892 const APInt ICmpCst = APInt(XBitWidth, 1).shl(ShiftAmt: KeptBits);
4893 assert(ICmpCst.isPowerOf2());
4894 // AddCst = (1 << (KeptBits-1))
4895 const APInt AddCst = ICmpCst.lshr(shiftAmt: 1);
4896 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4897
4898 // T0 = add %x, AddCst
4899 Value *T0 = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty: XType, V: AddCst));
4900 // T1 = T0 DstPred ICmpCst
4901 Value *T1 = Builder.CreateICmp(P: DstPred, LHS: T0, RHS: ConstantInt::get(Ty: XType, V: ICmpCst));
4902
4903 return T1;
4904}
4905
4906// Given pattern:
4907// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4908// we should move shifts to the same hand of 'and', i.e. rewrite as
4909// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4910// We are only interested in opposite logical shifts here.
4911// One of the shifts can be truncated.
4912// If we can, we want to end up creating 'lshr' shift.
4913static Value *
4914foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ,
4915 InstCombiner::BuilderTy &Builder) {
4916 if (!I.isEquality() || !match(V: I.getOperand(i_nocapture: 1), P: m_Zero()) ||
4917 !I.getOperand(i_nocapture: 0)->hasOneUse())
4918 return nullptr;
4919
4920 auto m_AnyLogicalShift = m_LogicalShift(L: m_Value(), R: m_Value());
4921
4922 // Look for an 'and' of two logical shifts, one of which may be truncated.
4923 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4924 Instruction *XShift, *MaybeTruncation, *YShift;
4925 if (!match(
4926 V: I.getOperand(i_nocapture: 0),
4927 P: m_c_And(L: m_CombineAnd(Ps: m_AnyLogicalShift, Ps: m_Instruction(I&: XShift)),
4928 R: m_CombineAnd(Ps: m_TruncOrSelf(Op: m_CombineAnd(
4929 Ps: m_AnyLogicalShift, Ps: m_Instruction(I&: YShift))),
4930 Ps: m_Instruction(I&: MaybeTruncation)))))
4931 return nullptr;
4932
4933 // We potentially looked past 'trunc', but only when matching YShift,
4934 // therefore YShift must have the widest type.
4935 Instruction *WidestShift = YShift;
4936 // Therefore XShift must have the shallowest type.
4937 // Or they both have identical types if there was no truncation.
4938 Instruction *NarrowestShift = XShift;
4939
4940 Type *WidestTy = WidestShift->getType();
4941 Type *NarrowestTy = NarrowestShift->getType();
4942 assert(NarrowestTy == I.getOperand(0)->getType() &&
4943 "We did not look past any shifts while matching XShift though.");
4944 bool HadTrunc = WidestTy != I.getOperand(i_nocapture: 0)->getType();
4945
4946 // If YShift is a 'lshr', swap the shifts around.
4947 if (match(V: YShift, P: m_LShr(L: m_Value(), R: m_Value())))
4948 std::swap(a&: XShift, b&: YShift);
4949
4950 // The shifts must be in opposite directions.
4951 auto XShiftOpcode = XShift->getOpcode();
4952 if (XShiftOpcode == YShift->getOpcode())
4953 return nullptr; // Do not care about same-direction shifts here.
4954
4955 Value *X, *XShAmt, *Y, *YShAmt;
4956 match(V: XShift, P: m_BinOp(L: m_Value(V&: X), R: m_ZExtOrSelf(Op: m_Value(V&: XShAmt))));
4957 match(V: YShift, P: m_BinOp(L: m_Value(V&: Y), R: m_ZExtOrSelf(Op: m_Value(V&: YShAmt))));
4958
4959 // If one of the values being shifted is a constant, then we will end with
4960 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4961 // however, we will need to ensure that we won't increase instruction count.
4962 if (!isa<Constant>(Val: X) && !isa<Constant>(Val: Y)) {
4963 // At least one of the hands of the 'and' should be one-use shift.
4964 if (!match(V: I.getOperand(i_nocapture: 0),
4965 P: m_c_And(L: m_OneUse(SubPattern: m_AnyLogicalShift), R: m_Value())))
4966 return nullptr;
4967 if (HadTrunc) {
4968 // Due to the 'trunc', we will need to widen X. For that either the old
4969 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4970 if (!MaybeTruncation->hasOneUse() &&
4971 !NarrowestShift->getOperand(i: 1)->hasOneUse())
4972 return nullptr;
4973 }
4974 }
4975
4976 // We have two shift amounts from two different shifts. The types of those
4977 // shift amounts may not match. If that's the case let's bailout now.
4978 if (XShAmt->getType() != YShAmt->getType())
4979 return nullptr;
4980
4981 // As input, we have the following pattern:
4982 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4983 // We want to rewrite that as:
4984 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4985 // While we know that originally (Q+K) would not overflow
4986 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
4987 // shift amounts. so it may now overflow in smaller bitwidth.
4988 // To ensure that does not happen, we need to ensure that the total maximal
4989 // shift amount is still representable in that smaller bit width.
4990 unsigned MaximalPossibleTotalShiftAmount =
4991 (WidestTy->getScalarSizeInBits() - 1) +
4992 (NarrowestTy->getScalarSizeInBits() - 1);
4993 APInt MaximalRepresentableShiftAmount =
4994 APInt::getAllOnes(numBits: XShAmt->getType()->getScalarSizeInBits());
4995 if (MaximalRepresentableShiftAmount.ult(RHS: MaximalPossibleTotalShiftAmount))
4996 return nullptr;
4997
4998 // Can we fold (XShAmt+YShAmt) ?
4999 auto *NewShAmt = dyn_cast_or_null<Constant>(
5000 Val: simplifyAddInst(LHS: XShAmt, RHS: YShAmt, /*isNSW=*/IsNSW: false,
5001 /*isNUW=*/IsNUW: false, Q: SQ.getWithInstruction(I: &I)));
5002 if (!NewShAmt)
5003 return nullptr;
5004 if (NewShAmt->getType() != WidestTy) {
5005 NewShAmt =
5006 ConstantFoldCastOperand(Opcode: Instruction::ZExt, C: NewShAmt, DestTy: WidestTy, DL: SQ.DL);
5007 if (!NewShAmt)
5008 return nullptr;
5009 }
5010 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
5011
5012 // Is the new shift amount smaller than the bit width?
5013 // FIXME: could also rely on ConstantRange.
5014 if (!match(V: NewShAmt,
5015 P: m_SpecificInt_ICMP(Predicate: ICmpInst::Predicate::ICMP_ULT,
5016 Threshold: APInt(WidestBitWidth, WidestBitWidth))))
5017 return nullptr;
5018
5019 // An extra legality check is needed if we had trunc-of-lshr.
5020 if (HadTrunc && match(V: WidestShift, P: m_LShr(L: m_Value(), R: m_Value()))) {
5021 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
5022 WidestShift]() {
5023 // It isn't obvious whether it's worth it to analyze non-constants here.
5024 // Also, let's basically give up on non-splat cases, pessimizing vectors.
5025 // If *any* of these preconditions matches we can perform the fold.
5026 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
5027 ? NewShAmt->getSplatValue()
5028 : NewShAmt;
5029 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
5030 if (NewShAmtSplat &&
5031 (NewShAmtSplat->isNullValue() ||
5032 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
5033 return true;
5034 // We consider *min* leading zeros so a single outlier
5035 // blocks the transform as opposed to allowing it.
5036 if (auto *C = dyn_cast<Constant>(Val: NarrowestShift->getOperand(i: 0))) {
5037 KnownBits Known = computeKnownBits(V: C, DL: SQ.DL);
5038 unsigned MinLeadZero = Known.countMinLeadingZeros();
5039 // If the value being shifted has at most lowest bit set we can fold.
5040 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5041 if (MaxActiveBits <= 1)
5042 return true;
5043 // Precondition: NewShAmt u<= countLeadingZeros(C)
5044 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(RHS: MinLeadZero))
5045 return true;
5046 }
5047 if (auto *C = dyn_cast<Constant>(Val: WidestShift->getOperand(i: 0))) {
5048 KnownBits Known = computeKnownBits(V: C, DL: SQ.DL);
5049 unsigned MinLeadZero = Known.countMinLeadingZeros();
5050 // If the value being shifted has at most lowest bit set we can fold.
5051 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5052 if (MaxActiveBits <= 1)
5053 return true;
5054 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
5055 if (NewShAmtSplat) {
5056 APInt AdjNewShAmt =
5057 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
5058 if (AdjNewShAmt.ule(RHS: MinLeadZero))
5059 return true;
5060 }
5061 }
5062 return false; // Can't tell if it's ok.
5063 };
5064 if (!CanFold())
5065 return nullptr;
5066 }
5067
5068 // All good, we can do this fold.
5069 X = Builder.CreateZExt(V: X, DestTy: WidestTy);
5070 Y = Builder.CreateZExt(V: Y, DestTy: WidestTy);
5071 // The shift is the same that was for X.
5072 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
5073 ? Builder.CreateLShr(LHS: X, RHS: NewShAmt)
5074 : Builder.CreateShl(LHS: X, RHS: NewShAmt);
5075 Value *T1 = Builder.CreateAnd(LHS: T0, RHS: Y);
5076 return Builder.CreateICmp(P: I.getPredicate(), LHS: T1,
5077 RHS: Constant::getNullValue(Ty: WidestTy));
5078}
5079
5080/// Fold
5081/// (-1 u/ x) u< y
5082/// ((x * y) ?/ x) != y
5083/// to
5084/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
5085/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
5086/// will mean that we are looking for the opposite answer.
5087Value *InstCombinerImpl::foldMultiplicationOverflowCheck(ICmpInst &I) {
5088 CmpPredicate Pred;
5089 Value *X, *Y;
5090 Instruction *Mul;
5091 Instruction *Div;
5092 bool NeedNegation;
5093 // Look for: (-1 u/ x) u</u>= y
5094 if (!I.isEquality() &&
5095 match(V: &I, P: m_c_ICmp(Pred,
5096 L: m_CombineAnd(Ps: m_OneUse(SubPattern: m_UDiv(L: m_AllOnes(), R: m_Value(V&: X))),
5097 Ps: m_Instruction(I&: Div)),
5098 R: m_Value(V&: Y)))) {
5099 Mul = nullptr;
5100
5101 // Are we checking that overflow does not happen, or does happen?
5102 switch (Pred) {
5103 case ICmpInst::Predicate::ICMP_ULT:
5104 NeedNegation = false;
5105 break; // OK
5106 case ICmpInst::Predicate::ICMP_UGE:
5107 NeedNegation = true;
5108 break; // OK
5109 default:
5110 return nullptr; // Wrong predicate.
5111 }
5112 } else // Look for: ((x * y) / x) !=/== y
5113 if (I.isEquality() &&
5114 match(V: &I, P: m_c_ICmp(Pred, L: m_Value(V&: Y),
5115 R: m_CombineAnd(Ps: m_OneUse(SubPattern: m_IDiv(
5116 L: m_CombineAnd(Ps: m_c_Mul(L: m_Deferred(V: Y),
5117 R: m_Value(V&: X)),
5118 Ps: m_Instruction(I&: Mul)),
5119 R: m_Deferred(V: X))),
5120 Ps: m_Instruction(I&: Div))))) {
5121 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
5122 } else
5123 return nullptr;
5124
5125 BuilderTy::InsertPointGuard Guard(Builder);
5126 // If the pattern included (x * y), we'll want to insert new instructions
5127 // right before that original multiplication so that we can replace it.
5128 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
5129 if (MulHadOtherUses)
5130 Builder.SetInsertPoint(Mul);
5131
5132 Value *Call = Builder.CreateIntrinsic(
5133 ID: Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
5134 : Intrinsic::smul_with_overflow,
5135 OverloadTypes: X->getType(), Args: {X, Y}, /*FMFSource=*/nullptr, Name: "mul");
5136
5137 // If the multiplication was used elsewhere, to ensure that we don't leave
5138 // "duplicate" instructions, replace uses of that original multiplication
5139 // with the multiplication result from the with.overflow intrinsic.
5140 if (MulHadOtherUses)
5141 replaceInstUsesWith(I&: *Mul, V: Builder.CreateExtractValue(Agg: Call, Idxs: 0, Name: "mul.val"));
5142
5143 Value *Res = Builder.CreateExtractValue(Agg: Call, Idxs: 1, Name: "mul.ov");
5144 if (NeedNegation) // This technically increases instruction count.
5145 Res = Builder.CreateNot(V: Res, Name: "mul.not.ov");
5146
5147 // If we replaced the mul, erase it. Do this after all uses of Builder,
5148 // as the mul is used as insertion point.
5149 if (MulHadOtherUses)
5150 eraseInstFromFunction(I&: *Mul);
5151
5152 return Res;
5153}
5154
5155static Instruction *foldICmpXNegX(ICmpInst &I,
5156 InstCombiner::BuilderTy &Builder) {
5157 CmpPredicate Pred;
5158 Value *X;
5159 if (match(V: &I, P: m_c_ICmp(Pred, L: m_NSWNeg(V: m_Value(V&: X)), R: m_Deferred(V: X)))) {
5160
5161 if (ICmpInst::isSigned(Pred))
5162 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5163 else if (ICmpInst::isUnsigned(Pred))
5164 Pred = ICmpInst::getSignedPredicate(Pred);
5165 // else for equality-comparisons just keep the predicate.
5166
5167 return ICmpInst::Create(Op: Instruction::ICmp, Pred, S1: X,
5168 S2: Constant::getNullValue(Ty: X->getType()), Name: I.getName());
5169 }
5170
5171 // A value is not equal to its negation unless that value is 0 or
5172 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
5173 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))) &&
5174 ICmpInst::isEquality(P: Pred)) {
5175 Type *Ty = X->getType();
5176 uint32_t BitWidth = Ty->getScalarSizeInBits();
5177 Constant *MaxSignedVal =
5178 ConstantInt::get(Ty, V: APInt::getSignedMaxValue(numBits: BitWidth));
5179 Value *And = Builder.CreateAnd(LHS: X, RHS: MaxSignedVal);
5180 Constant *Zero = Constant::getNullValue(Ty);
5181 return CmpInst::Create(Op: Instruction::ICmp, Pred, S1: And, S2: Zero);
5182 }
5183
5184 return nullptr;
5185}
5186
5187static Instruction *foldICmpAndXX(ICmpInst &I, const SimplifyQuery &Q,
5188 InstCombinerImpl &IC) {
5189 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *A;
5190 // Normalize and operand as operand 0.
5191 CmpInst::Predicate Pred = I.getPredicate();
5192 if (match(V: Op1, P: m_c_And(L: m_Specific(V: Op0), R: m_Value()))) {
5193 std::swap(a&: Op0, b&: Op1);
5194 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5195 }
5196
5197 if (!match(V: Op0, P: m_c_And(L: m_Specific(V: Op1), R: m_Value(V&: A))))
5198 return nullptr;
5199
5200 // (icmp (X & Y) u< X --> (X & Y) != X
5201 if (Pred == ICmpInst::ICMP_ULT)
5202 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5203
5204 // (icmp (X & Y) u>= X --> (X & Y) == X
5205 if (Pred == ICmpInst::ICMP_UGE)
5206 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5207
5208 if (ICmpInst::isEquality(P: Pred) && Op0->hasOneUse()) {
5209 // icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and
5210 // Y is non-constant. If Y is constant the `X & C == C` form is preferable
5211 // so don't do this fold.
5212 if (!match(V: Op1, P: m_ImmConstant()))
5213 if (auto *NotOp1 =
5214 IC.getFreelyInverted(V: Op1, WillInvertAllUses: !Op1->hasNUsesOrMore(N: 3), Builder: &IC.Builder))
5215 return new ICmpInst(Pred, IC.Builder.CreateOr(LHS: A, RHS: NotOp1),
5216 Constant::getAllOnesValue(Ty: Op1->getType()));
5217 // icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.
5218 if (auto *NotA = IC.getFreelyInverted(V: A, WillInvertAllUses: A->hasOneUse(), Builder: &IC.Builder))
5219 return new ICmpInst(Pred, IC.Builder.CreateAnd(LHS: Op1, RHS: NotA),
5220 Constant::getNullValue(Ty: Op1->getType()));
5221 }
5222
5223 if (!ICmpInst::isSigned(Pred))
5224 return nullptr;
5225
5226 KnownBits KnownY = IC.computeKnownBits(V: A, CtxI: &I);
5227 // (X & NegY) spred X --> (X & NegY) upred X
5228 if (KnownY.isNegative())
5229 return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);
5230
5231 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGT)
5232 return nullptr;
5233
5234 if (KnownY.isNonNegative())
5235 // (X & PosY) s<= X --> X s>= 0
5236 // (X & PosY) s> X --> X s< 0
5237 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
5238 Constant::getNullValue(Ty: Op1->getType()));
5239
5240 if (isKnownNegative(V: Op1, SQ: IC.getSimplifyQuery().getWithInstruction(I: &I)))
5241 // (NegX & Y) s<= NegX --> Y s< 0
5242 // (NegX & Y) s> NegX --> Y s>= 0
5243 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), A,
5244 Constant::getNullValue(Ty: A->getType()));
5245
5246 return nullptr;
5247}
5248
5249static Instruction *foldICmpOrXX(ICmpInst &I, const SimplifyQuery &Q,
5250 InstCombinerImpl &IC) {
5251 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *A;
5252
5253 // Normalize or operand as operand 0.
5254 CmpInst::Predicate Pred = I.getPredicate();
5255 if (match(V: Op1, P: m_c_Or(L: m_Specific(V: Op0), R: m_Value(V&: A)))) {
5256 std::swap(a&: Op0, b&: Op1);
5257 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5258 } else if (!match(V: Op0, P: m_c_Or(L: m_Specific(V: Op1), R: m_Value(V&: A)))) {
5259 return nullptr;
5260 }
5261
5262 // icmp (X | Y) u<= X --> (X | Y) == X
5263 if (Pred == ICmpInst::ICMP_ULE)
5264 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5265
5266 // icmp (X | Y) u> X --> (X | Y) != X
5267 if (Pred == ICmpInst::ICMP_UGT)
5268 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5269
5270 if (ICmpInst::isEquality(P: Pred) && Op0->hasOneUse()) {
5271 // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
5272 if (Value *NotOp1 = IC.getFreelyInverted(
5273 V: Op1, WillInvertAllUses: !isa<Constant>(Val: Op1) && !Op1->hasNUsesOrMore(N: 3), Builder: &IC.Builder))
5274 return new ICmpInst(Pred, IC.Builder.CreateAnd(LHS: A, RHS: NotOp1),
5275 Constant::getNullValue(Ty: Op1->getType()));
5276 // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.
5277 if (Value *NotA = IC.getFreelyInverted(V: A, WillInvertAllUses: A->hasOneUse(), Builder: &IC.Builder))
5278 return new ICmpInst(Pred, IC.Builder.CreateOr(LHS: Op1, RHS: NotA),
5279 Constant::getAllOnesValue(Ty: Op1->getType()));
5280 }
5281 return nullptr;
5282}
5283
5284static Instruction *foldICmpXorXX(ICmpInst &I, const SimplifyQuery &Q,
5285 InstCombinerImpl &IC) {
5286 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *A;
5287 // Normalize xor operand as operand 0.
5288 CmpInst::Predicate Pred = I.getPredicate();
5289 if (match(V: Op1, P: m_c_Xor(L: m_Specific(V: Op0), R: m_Value()))) {
5290 std::swap(a&: Op0, b&: Op1);
5291 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5292 }
5293 if (!match(V: Op0, P: m_c_Xor(L: m_Specific(V: Op1), R: m_Value(V&: A))))
5294 return nullptr;
5295
5296 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
5297 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
5298 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
5299 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
5300 CmpInst::Predicate PredOut = CmpInst::getStrictPredicate(pred: Pred);
5301 if (PredOut != Pred && isKnownNonZero(V: A, Q))
5302 return new ICmpInst(PredOut, Op0, Op1);
5303
5304 // These transform work when A is negative.
5305 // X s< X^A, X s<= X^A, X u> X^A, X u>= X^A --> X s< 0
5306 // X s> X^A, X s>= X^A, X u< X^A, X u<= X^A --> X s>= 0
5307 if (match(V: A, P: m_Negative())) {
5308 CmpInst::Predicate NewPred;
5309 switch (ICmpInst::getStrictPredicate(pred: Pred)) {
5310 default:
5311 return nullptr;
5312 case ICmpInst::ICMP_SLT:
5313 case ICmpInst::ICMP_UGT:
5314 NewPred = ICmpInst::ICMP_SLT;
5315 break;
5316 case ICmpInst::ICMP_SGT:
5317 case ICmpInst::ICMP_ULT:
5318 NewPred = ICmpInst::ICMP_SGE;
5319 break;
5320 }
5321 Constant *Const = Constant::getNullValue(Ty: Op0->getType());
5322 return new ICmpInst(NewPred, Op0, Const);
5323 }
5324
5325 return nullptr;
5326}
5327
5328/// Return true if X is a multiple of C.
5329/// TODO: Handle non-power-of-2 factors.
5330static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q) {
5331 if (C.isOne())
5332 return true;
5333
5334 if (!C.isPowerOf2())
5335 return false;
5336
5337 return MaskedValueIsZero(V: X, Mask: C - 1, SQ: Q);
5338}
5339
5340/// Try to fold icmp (binop), X or icmp X, (binop).
5341/// TODO: A large part of this logic is duplicated in InstSimplify's
5342/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
5343/// duplication.
5344Instruction *InstCombinerImpl::foldICmpBinOp(ICmpInst &I,
5345 const SimplifyQuery &SQ) {
5346 const SimplifyQuery Q = SQ.getWithInstruction(I: &I);
5347 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
5348
5349 // Special logic for binary operators.
5350 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Val: Op0);
5351 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Val: Op1);
5352 if (!BO0 && !BO1)
5353 return nullptr;
5354
5355 if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
5356 return NewICmp;
5357
5358 const CmpInst::Predicate Pred = I.getPredicate();
5359
5360 // (X urem Y) == X --> X u< Y
5361 // (X urem Y) != X --> X u>= Y
5362 Value *Dividend, *Divisor;
5363 if (I.isEquality() &&
5364 match(V: &I, P: m_c_ICmp(L: m_URem(L: m_Value(V&: Dividend), R: m_Value(V&: Divisor)),
5365 R: m_Deferred(V: Dividend)))) {
5366 CmpInst::Predicate NewPred =
5367 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
5368 return new ICmpInst(NewPred, Dividend, Divisor);
5369 }
5370
5371 Value *X;
5372
5373 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
5374 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
5375 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: Op1), R: m_Value(V&: X)))) &&
5376 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5377 return new ICmpInst(Pred, Builder.CreateNot(V: Op1), X);
5378 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
5379 if (match(V: Op1, P: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: Op0), R: m_Value(V&: X)))) &&
5380 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5381 return new ICmpInst(Pred, X, Builder.CreateNot(V: Op0));
5382
5383 {
5384 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
5385 Constant *C;
5386 if (match(V: Op0, P: m_OneUse(SubPattern: m_Add(L: m_c_Add(L: m_Specific(V: Op1), R: m_Value(V&: X)),
5387 R: m_ImmConstant(C)))) &&
5388 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
5389 Constant *C2 = ConstantExpr::getNot(C);
5390 return new ICmpInst(Pred, Builder.CreateSub(LHS: C2, RHS: X), Op1);
5391 }
5392 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
5393 if (match(V: Op1, P: m_OneUse(SubPattern: m_Add(L: m_c_Add(L: m_Specific(V: Op0), R: m_Value(V&: X)),
5394 R: m_ImmConstant(C)))) &&
5395 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
5396 Constant *C2 = ConstantExpr::getNot(C);
5397 return new ICmpInst(Pred, Op0, Builder.CreateSub(LHS: C2, RHS: X));
5398 }
5399 }
5400
5401 // (icmp eq/ne (X, -P2), INT_MIN)
5402 // -> (icmp slt/sge X, INT_MIN + P2)
5403 if (ICmpInst::isEquality(P: Pred) && BO0 &&
5404 match(V: I.getOperand(i_nocapture: 1), P: m_SignMask()) &&
5405 match(V: BO0, P: m_And(L: m_Value(), R: m_NegatedPower2OrZero()))) {
5406 // Will Constant fold.
5407 Value *NewC = Builder.CreateSub(LHS: I.getOperand(i_nocapture: 1), RHS: BO0->getOperand(i_nocapture: 1));
5408 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SLT
5409 : ICmpInst::ICMP_SGE,
5410 BO0->getOperand(i_nocapture: 0), NewC);
5411 }
5412
5413 {
5414 // Similar to above: an unsigned overflow comparison may use offset + mask:
5415 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
5416 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
5417 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
5418 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
5419 BinaryOperator *BO;
5420 const APInt *C;
5421 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
5422 match(V: Op0, P: m_And(L: m_BinOp(I&: BO), R: m_LowBitMask(V&: C))) &&
5423 match(V: BO, P: m_Add(L: m_Specific(V: Op1), R: m_SpecificIntAllowPoison(V: *C)))) {
5424 CmpInst::Predicate NewPred =
5425 Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
5426 Constant *Zero = ConstantInt::getNullValue(Ty: Op1->getType());
5427 return new ICmpInst(NewPred, Op1, Zero);
5428 }
5429
5430 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5431 match(V: Op1, P: m_And(L: m_BinOp(I&: BO), R: m_LowBitMask(V&: C))) &&
5432 match(V: BO, P: m_Add(L: m_Specific(V: Op0), R: m_SpecificIntAllowPoison(V: *C)))) {
5433 CmpInst::Predicate NewPred =
5434 Pred == ICmpInst::ICMP_UGT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
5435 Constant *Zero = ConstantInt::getNullValue(Ty: Op1->getType());
5436 return new ICmpInst(NewPred, Op0, Zero);
5437 }
5438 }
5439
5440 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
5441 bool Op0HasNUW = false, Op1HasNUW = false;
5442 bool Op0HasNSW = false, Op1HasNSW = false;
5443 // Analyze the case when either Op0 or Op1 is an add instruction.
5444 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
5445 auto hasNoWrapProblem = [](const BinaryOperator &BO, CmpInst::Predicate Pred,
5446 bool &HasNSW, bool &HasNUW) -> bool {
5447 if (isa<OverflowingBinaryOperator>(Val: BO)) {
5448 HasNUW = BO.hasNoUnsignedWrap();
5449 HasNSW = BO.hasNoSignedWrap();
5450 return ICmpInst::isEquality(P: Pred) ||
5451 (CmpInst::isUnsigned(Pred) && HasNUW) ||
5452 (CmpInst::isSigned(Pred) && HasNSW);
5453 } else if (BO.getOpcode() == Instruction::Or) {
5454 // The invariant here is that we are handling m_AddLike instructions,
5455 // which can only be a or disjoint, which is equivalent to an add nuw nsw.
5456 HasNUW = true;
5457 HasNSW = true;
5458 return true;
5459 } else {
5460 return false;
5461 }
5462 };
5463 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5464
5465 if (BO0) {
5466 match(V: BO0, P: m_AddLike(L: m_Value(V&: A), R: m_Value(V&: B)));
5467 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5468 }
5469 if (BO1) {
5470 match(V: BO1, P: m_AddLike(L: m_Value(V&: C), R: m_Value(V&: D)));
5471 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5472 }
5473
5474 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5475 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5476 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5477 return new ICmpInst(Pred, A == Op1 ? B : A,
5478 Constant::getNullValue(Ty: Op1->getType()));
5479
5480 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5481 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5482 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5483 return new ICmpInst(Pred, Constant::getNullValue(Ty: Op0->getType()),
5484 C == Op0 ? D : C);
5485
5486 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
5487 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
5488 NoOp1WrapProblem) {
5489 // Determine Y and Z in the form icmp (X+Y), (X+Z).
5490 Value *Y, *Z;
5491 if (A == C) {
5492 // C + B == C + D -> B == D
5493 Y = B;
5494 Z = D;
5495 } else if (A == D) {
5496 // D + B == C + D -> B == C
5497 Y = B;
5498 Z = C;
5499 } else if (B == C) {
5500 // A + C == C + D -> A == D
5501 Y = A;
5502 Z = D;
5503 } else {
5504 assert(B == D);
5505 // A + D == C + D -> A == C
5506 Y = A;
5507 Z = C;
5508 }
5509 return new ICmpInst(Pred, Y, Z);
5510 }
5511
5512 if (ICmpInst::isRelational(P: Pred)) {
5513 // Return if both X and Y is divisible by Z/-Z.
5514 // TODO: Generalize to check if (X - Y) is divisible by Z/-Z.
5515 auto ShareCommonDivisor = [&Q](Value *X, Value *Y, Value *Z,
5516 bool IsNegative) -> bool {
5517 const APInt *OffsetC;
5518 if (!match(V: Z, P: m_APInt(Res&: OffsetC)))
5519 return false;
5520
5521 // Fast path for Z == 1/-1.
5522 if (IsNegative ? OffsetC->isAllOnes() : OffsetC->isOne())
5523 return true;
5524
5525 APInt C = *OffsetC;
5526 if (IsNegative)
5527 C.negate();
5528 // Note: -INT_MIN is also negative.
5529 if (!C.isStrictlyPositive())
5530 return false;
5531
5532 return isMultipleOf(X, C, Q) && isMultipleOf(X: Y, C, Q);
5533 };
5534
5535 // The subtraction-related identities (A -nuw B) shown below require that
5536 // the subtraction does not wrap unsigned (i.e., A >=u B). Canonicalization
5537 // from (A -nuw 1) to (A + -1) means that such combinations ought to never
5538 // occur, as sub nuw ops should have been canonicalized to add ones. It may
5539 // however appear in the form of a or disjoint. Though, or disjoint A, -B
5540 // requires proving A <u B, for which the nowrap precondition can never be
5541 // satisfied. These are therefore skipped.
5542 //
5543 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5544 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5545 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5546 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5547
5548 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5549 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5550 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5551 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5552 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5553 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5554 bool IsNegative = ICmpInst::isLT(P: Pred) || ICmpInst::isGE(P: Pred);
5555 bool IsAddOrSignedPred = !IsNegative || ICmpInst::isSigned(Pred);
5556 if (A && NoOp0WrapProblem && IsAddOrSignedPred &&
5557 ShareCommonDivisor(A, Op1, B, IsNegative))
5558 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), A,
5559 Op1);
5560
5561 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5562 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5563 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5564 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5565 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5566 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5567 if (C && NoOp1WrapProblem &&
5568 ShareCommonDivisor(Op0, C, D,
5569 ICmpInst::isGT(P: Pred) || ICmpInst::isLE(P: Pred)))
5570 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), Op0,
5571 C);
5572 }
5573
5574 // if C1 has greater magnitude than C2:
5575 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5576 // s.t. C3 = C1 - C2
5577 //
5578 // if C2 has greater magnitude than C1:
5579 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5580 // s.t. C3 = C2 - C1
5581 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5582 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5583 const APInt *AP1, *AP2;
5584 // TODO: Support non-uniform vectors.
5585 // TODO: Allow poison passthrough if B or D's element is poison.
5586 if (match(V: B, P: m_APIntAllowPoison(Res&: AP1)) &&
5587 match(V: D, P: m_APIntAllowPoison(Res&: AP2)) &&
5588 AP1->isNegative() == AP2->isNegative()) {
5589 APInt AP1Abs = AP1->abs();
5590 APInt AP2Abs = AP2->abs();
5591 if (AP1Abs.uge(RHS: AP2Abs)) {
5592 APInt Diff = *AP1 - *AP2;
5593 Constant *C3 = Constant::getIntegerValue(Ty: BO0->getType(), V: Diff);
5594 Value *NewAdd = Builder.CreateAdd(
5595 LHS: A, RHS: C3, Name: "", HasNUW: Op0HasNUW && Diff.ule(RHS: *AP1), HasNSW: Op0HasNSW);
5596 return new ICmpInst(Pred, NewAdd, C);
5597 } else {
5598 APInt Diff = *AP2 - *AP1;
5599 Constant *C3 = Constant::getIntegerValue(Ty: BO0->getType(), V: Diff);
5600 Value *NewAdd = Builder.CreateAdd(
5601 LHS: C, RHS: C3, Name: "", HasNUW: Op1HasNUW && Diff.ule(RHS: *AP2), HasNSW: Op1HasNSW);
5602 return new ICmpInst(Pred, A, NewAdd);
5603 }
5604 }
5605 Constant *Cst1, *Cst2;
5606 if (match(V: B, P: m_ImmConstant(C&: Cst1)) && match(V: D, P: m_ImmConstant(C&: Cst2)) &&
5607 ICmpInst::isEquality(P: Pred)) {
5608 Constant *Diff = ConstantExpr::getSub(C1: Cst2, C2: Cst1);
5609 Value *NewAdd = Builder.CreateAdd(LHS: C, RHS: Diff);
5610 return new ICmpInst(Pred, A, NewAdd);
5611 }
5612 }
5613
5614 // Analyze the case when either Op0 or Op1 is a sub instruction.
5615 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5616 A = nullptr;
5617 B = nullptr;
5618 C = nullptr;
5619 D = nullptr;
5620 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5621 A = BO0->getOperand(i_nocapture: 0);
5622 B = BO0->getOperand(i_nocapture: 1);
5623 }
5624 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5625 C = BO1->getOperand(i_nocapture: 0);
5626 D = BO1->getOperand(i_nocapture: 1);
5627 }
5628
5629 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5630 if (A == Op1 && NoOp0WrapProblem)
5631 return new ICmpInst(Pred, Constant::getNullValue(Ty: Op1->getType()), B);
5632 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5633 if (C == Op0 && NoOp1WrapProblem)
5634 return new ICmpInst(Pred, D, Constant::getNullValue(Ty: Op0->getType()));
5635
5636 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5637 // (A - B) u>/u<= A --> B u>/u<= A
5638 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5639 return new ICmpInst(Pred, B, A);
5640 // C u</u>= (C - D) --> C u</u>= D
5641 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5642 return new ICmpInst(Pred, C, D);
5643 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5644 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5645 isKnownNonZero(V: B, Q))
5646 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(pred: Pred), B, A);
5647 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5648 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5649 isKnownNonZero(V: D, Q))
5650 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(pred: Pred), C, D);
5651
5652 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
5653 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
5654 return new ICmpInst(Pred, A, C);
5655
5656 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
5657 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
5658 return new ICmpInst(Pred, D, B);
5659
5660 // icmp (0-X) < cst --> x > -cst
5661 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
5662 Value *X;
5663 if (match(V: BO0, P: m_Neg(V: m_Value(V&: X))))
5664 if (Constant *RHSC = dyn_cast<Constant>(Val: Op1))
5665 if (RHSC->isNotMinSignedValue())
5666 return new ICmpInst(I.getSwappedPredicate(), X,
5667 ConstantExpr::getNeg(C: RHSC));
5668 }
5669
5670 if (Instruction *R = foldICmpXorXX(I, Q, IC&: *this))
5671 return R;
5672 if (Instruction *R = foldICmpOrXX(I, Q, IC&: *this))
5673 return R;
5674
5675 {
5676 // Try to remove shared multiplier from comparison:
5677 // X * Z pred Y * Z
5678 Value *X, *Y, *Z;
5679 if ((match(V: Op0, P: m_Mul(L: m_Value(V&: X), R: m_Value(V&: Z))) &&
5680 match(V: Op1, P: m_c_Mul(L: m_Specific(V: Z), R: m_Value(V&: Y)))) ||
5681 (match(V: Op0, P: m_Mul(L: m_Value(V&: Z), R: m_Value(V&: X))) &&
5682 match(V: Op1, P: m_c_Mul(L: m_Specific(V: Z), R: m_Value(V&: Y))))) {
5683 if (ICmpInst::isSigned(Pred)) {
5684 if (Op0HasNSW && Op1HasNSW) {
5685 KnownBits ZKnown = computeKnownBits(V: Z, CtxI: &I);
5686 if (ZKnown.isStrictlyPositive())
5687 return new ICmpInst(Pred, X, Y);
5688 if (ZKnown.isNegative())
5689 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), X, Y);
5690 Value *LessThan = simplifyICmpInst(Pred: ICmpInst::ICMP_SLT, LHS: X, RHS: Y,
5691 Q: SQ.getWithInstruction(I: &I));
5692 if (LessThan && match(V: LessThan, P: m_One()))
5693 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Z,
5694 Constant::getNullValue(Ty: Z->getType()));
5695 Value *GreaterThan = simplifyICmpInst(Pred: ICmpInst::ICMP_SGT, LHS: X, RHS: Y,
5696 Q: SQ.getWithInstruction(I: &I));
5697 if (GreaterThan && match(V: GreaterThan, P: m_One()))
5698 return new ICmpInst(Pred, Z, Constant::getNullValue(Ty: Z->getType()));
5699 }
5700 } else {
5701 bool NonZero;
5702 if (ICmpInst::isEquality(P: Pred)) {
5703 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5704 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5705 isKnownNonEqual(V1: X, V2: Y, SQ))
5706 return new ICmpInst(Pred, Z, Constant::getNullValue(Ty: Z->getType()));
5707
5708 KnownBits ZKnown = computeKnownBits(V: Z, CtxI: &I);
5709 // if Z % 2 != 0
5710 // X * Z eq/ne Y * Z -> X eq/ne Y
5711 if (ZKnown.countMaxTrailingZeros() == 0)
5712 return new ICmpInst(Pred, X, Y);
5713 NonZero = !ZKnown.One.isZero() || isKnownNonZero(V: Z, Q);
5714 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5715 // X * Z eq/ne Y * Z -> X eq/ne Y
5716 if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)
5717 return new ICmpInst(Pred, X, Y);
5718 } else
5719 NonZero = isKnownNonZero(V: Z, Q);
5720
5721 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5722 // X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
5723 if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)
5724 return new ICmpInst(Pred, X, Y);
5725 }
5726 }
5727 }
5728
5729 BinaryOperator *SRem = nullptr;
5730 // icmp (srem X, Y), Y
5731 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(i_nocapture: 1))
5732 SRem = BO0;
5733 // icmp Y, (srem X, Y)
5734 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5735 Op0 == BO1->getOperand(i_nocapture: 1))
5736 SRem = BO1;
5737 if (SRem) {
5738 // We don't check hasOneUse to avoid increasing register pressure because
5739 // the value we use is the same value this instruction was already using.
5740 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(pred: Pred) : Pred) {
5741 default:
5742 break;
5743 case ICmpInst::ICMP_EQ:
5744 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
5745 case ICmpInst::ICMP_NE:
5746 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
5747 case ICmpInst::ICMP_SGT:
5748 case ICmpInst::ICMP_SGE:
5749 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(i_nocapture: 1),
5750 Constant::getAllOnesValue(Ty: SRem->getType()));
5751 case ICmpInst::ICMP_SLT:
5752 case ICmpInst::ICMP_SLE:
5753 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(i_nocapture: 1),
5754 Constant::getNullValue(Ty: SRem->getType()));
5755 }
5756 }
5757
5758 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5759 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5760 BO0->getOperand(i_nocapture: 1) == BO1->getOperand(i_nocapture: 1)) {
5761 switch (BO0->getOpcode()) {
5762 default:
5763 break;
5764 case Instruction::Add:
5765 case Instruction::Sub:
5766 case Instruction::Xor: {
5767 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5768 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5769
5770 const APInt *C;
5771 if (match(V: BO0->getOperand(i_nocapture: 1), P: m_APInt(Res&: C))) {
5772 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5773 if (C->isSignMask()) {
5774 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5775 return new ICmpInst(NewPred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5776 }
5777
5778 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5779 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5780 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5781 NewPred = I.getSwappedPredicate(pred: NewPred);
5782 return new ICmpInst(NewPred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5783 }
5784 }
5785 break;
5786 }
5787 case Instruction::Mul: {
5788 if (!I.isEquality())
5789 break;
5790
5791 const APInt *C;
5792 if (match(V: BO0->getOperand(i_nocapture: 1), P: m_APInt(Res&: C)) && !C->isZero() &&
5793 !C->isOne()) {
5794 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5795 // Mask = -1 >> count-trailing-zeros(C).
5796 if (unsigned TZs = C->countr_zero()) {
5797 Constant *Mask = ConstantInt::get(
5798 Ty: BO0->getType(),
5799 V: APInt::getLowBitsSet(numBits: C->getBitWidth(), loBitsSet: C->getBitWidth() - TZs));
5800 Value *And1 = Builder.CreateAnd(LHS: BO0->getOperand(i_nocapture: 0), RHS: Mask);
5801 Value *And2 = Builder.CreateAnd(LHS: BO1->getOperand(i_nocapture: 0), RHS: Mask);
5802 return new ICmpInst(Pred, And1, And2);
5803 }
5804 }
5805 break;
5806 }
5807 case Instruction::UDiv:
5808 case Instruction::LShr:
5809 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
5810 break;
5811 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5812
5813 case Instruction::SDiv:
5814 if (!(I.isEquality() || match(V: BO0->getOperand(i_nocapture: 1), P: m_NonNegative())) ||
5815 !BO0->isExact() || !BO1->isExact())
5816 break;
5817 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5818
5819 case Instruction::AShr:
5820 if (!BO0->isExact() || !BO1->isExact())
5821 break;
5822 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5823
5824 case Instruction::Shl: {
5825 bool NUW = Op0HasNUW && Op1HasNUW;
5826 bool NSW = Op0HasNSW && Op1HasNSW;
5827 if (!NUW && !NSW)
5828 break;
5829 if (!NSW && I.isSigned())
5830 break;
5831 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5832 }
5833 }
5834 }
5835
5836 if (BO0) {
5837 // Transform A & (L - 1) `ult` L --> L != 0
5838 auto LSubOne = m_Add(L: m_Specific(V: Op1), R: m_AllOnes());
5839 auto BitwiseAnd = m_c_And(L: m_Value(), R: LSubOne);
5840
5841 if (match(V: BO0, P: BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5842 auto *Zero = Constant::getNullValue(Ty: BO0->getType());
5843 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5844 }
5845 }
5846
5847 // For unsigned predicates / eq / ne:
5848 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5849 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5850 if (!ICmpInst::isSigned(Pred)) {
5851 if (match(V: Op0, P: m_Shl(L: m_Specific(V: Op1), R: m_One())))
5852 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5853 Constant::getNullValue(Ty: Op1->getType()));
5854 else if (match(V: Op1, P: m_Shl(L: m_Specific(V: Op0), R: m_One())))
5855 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5856 Constant::getNullValue(Ty: Op0->getType()), Op0);
5857 }
5858
5859 if (Value *V = foldMultiplicationOverflowCheck(I))
5860 return replaceInstUsesWith(I, V);
5861
5862 if (Instruction *R = foldICmpAndXX(I, Q, IC&: *this))
5863 return R;
5864
5865 if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder))
5866 return replaceInstUsesWith(I, V);
5867
5868 if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder))
5869 return replaceInstUsesWith(I, V);
5870
5871 return nullptr;
5872}
5873
5874/// Fold icmp Pred min|max(X, Y), Z.
5875Instruction *InstCombinerImpl::foldICmpWithMinMax(Instruction &I,
5876 MinMaxIntrinsic *MinMax,
5877 Value *Z, CmpPredicate Pred) {
5878 Value *X = MinMax->getLHS();
5879 Value *Y = MinMax->getRHS();
5880 if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5881 return nullptr;
5882 if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {
5883 // Revert the transform signed pred -> unsigned pred
5884 // TODO: We can flip the signedness of predicate if both operands of icmp
5885 // are negative.
5886 if (isKnownNonNegative(V: Z, SQ: SQ.getWithInstruction(I: &I)) &&
5887 isKnownNonNegative(V: MinMax, SQ: SQ.getWithInstruction(I: &I))) {
5888 Pred = ICmpInst::getFlippedSignednessPredicate(Pred);
5889 } else
5890 return nullptr;
5891 }
5892 SimplifyQuery Q = SQ.getWithInstruction(I: &I);
5893 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5894 if (!Val)
5895 return std::nullopt;
5896 if (match(V: Val, P: m_One()))
5897 return true;
5898 if (match(V: Val, P: m_Zero()))
5899 return false;
5900 return std::nullopt;
5901 };
5902 // Remove samesign here since it is illegal to keep it when we speculatively
5903 // execute comparisons. For example, `icmp samesign ult umax(X, -46), -32`
5904 // cannot be decomposed into `(icmp samesign ult X, -46) or (icmp samesign ult
5905 // -46, -32)`. `X` is allowed to be non-negative here.
5906 Pred = Pred.dropSameSign();
5907 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, LHS: X, RHS: Z, Q));
5908 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, LHS: Y, RHS: Z, Q));
5909 if (!CmpXZ.has_value() && !CmpYZ.has_value())
5910 return nullptr;
5911 if (!CmpXZ.has_value()) {
5912 std::swap(a&: X, b&: Y);
5913 std::swap(lhs&: CmpXZ, rhs&: CmpYZ);
5914 }
5915
5916 auto FoldIntoCmpYZ = [&]() -> Instruction * {
5917 if (CmpYZ.has_value())
5918 return replaceInstUsesWith(I, V: ConstantInt::getBool(Ty: I.getType(), V: *CmpYZ));
5919 return ICmpInst::Create(Op: Instruction::ICmp, Pred, S1: Y, S2: Z);
5920 };
5921
5922 switch (Pred) {
5923 case ICmpInst::ICMP_EQ:
5924 case ICmpInst::ICMP_NE: {
5925 // If X == Z:
5926 // Expr Result
5927 // min(X, Y) == Z X <= Y
5928 // max(X, Y) == Z X >= Y
5929 // min(X, Y) != Z X > Y
5930 // max(X, Y) != Z X < Y
5931 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5932 ICmpInst::Predicate NewPred =
5933 ICmpInst::getNonStrictPredicate(pred: MinMax->getPredicate());
5934 if (Pred == ICmpInst::ICMP_NE)
5935 NewPred = ICmpInst::getInversePredicate(pred: NewPred);
5936 return ICmpInst::Create(Op: Instruction::ICmp, Pred: NewPred, S1: X, S2: Y);
5937 }
5938 // Otherwise (X != Z):
5939 ICmpInst::Predicate NewPred = MinMax->getPredicate();
5940 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred: NewPred, LHS: X, RHS: Z, Q));
5941 if (!MinMaxCmpXZ.has_value()) {
5942 std::swap(a&: X, b&: Y);
5943 std::swap(lhs&: CmpXZ, rhs&: CmpYZ);
5944 // Re-check pre-condition X != Z
5945 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5946 break;
5947 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred: NewPred, LHS: X, RHS: Z, Q));
5948 }
5949 if (!MinMaxCmpXZ.has_value())
5950 break;
5951 if (*MinMaxCmpXZ) {
5952 // Expr Fact Result
5953 // min(X, Y) == Z X < Z false
5954 // max(X, Y) == Z X > Z false
5955 // min(X, Y) != Z X < Z true
5956 // max(X, Y) != Z X > Z true
5957 return replaceInstUsesWith(
5958 I, V: ConstantInt::getBool(Ty: I.getType(), V: Pred == ICmpInst::ICMP_NE));
5959 } else {
5960 // Expr Fact Result
5961 // min(X, Y) == Z X > Z Y == Z
5962 // max(X, Y) == Z X < Z Y == Z
5963 // min(X, Y) != Z X > Z Y != Z
5964 // max(X, Y) != Z X < Z Y != Z
5965 return FoldIntoCmpYZ();
5966 }
5967 break;
5968 }
5969 case ICmpInst::ICMP_SLT:
5970 case ICmpInst::ICMP_ULT:
5971 case ICmpInst::ICMP_SLE:
5972 case ICmpInst::ICMP_ULE:
5973 case ICmpInst::ICMP_SGT:
5974 case ICmpInst::ICMP_UGT:
5975 case ICmpInst::ICMP_SGE:
5976 case ICmpInst::ICMP_UGE: {
5977 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(pred: Pred);
5978 if (*CmpXZ) {
5979 if (IsSame) {
5980 // Expr Fact Result
5981 // min(X, Y) < Z X < Z true
5982 // min(X, Y) <= Z X <= Z true
5983 // max(X, Y) > Z X > Z true
5984 // max(X, Y) >= Z X >= Z true
5985 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
5986 } else {
5987 // Expr Fact Result
5988 // max(X, Y) < Z X < Z Y < Z
5989 // max(X, Y) <= Z X <= Z Y <= Z
5990 // min(X, Y) > Z X > Z Y > Z
5991 // min(X, Y) >= Z X >= Z Y >= Z
5992 return FoldIntoCmpYZ();
5993 }
5994 } else {
5995 if (IsSame) {
5996 // Expr Fact Result
5997 // min(X, Y) < Z X >= Z Y < Z
5998 // min(X, Y) <= Z X > Z Y <= Z
5999 // max(X, Y) > Z X <= Z Y > Z
6000 // max(X, Y) >= Z X < Z Y >= Z
6001 return FoldIntoCmpYZ();
6002 } else {
6003 // Expr Fact Result
6004 // max(X, Y) < Z X >= Z false
6005 // max(X, Y) <= Z X > Z false
6006 // min(X, Y) > Z X <= Z false
6007 // min(X, Y) >= Z X < Z false
6008 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
6009 }
6010 }
6011 break;
6012 }
6013 default:
6014 break;
6015 }
6016
6017 return nullptr;
6018}
6019
6020/// Match and fold patterns like:
6021/// icmp eq/ne X, min(max(X, Lo), Hi)
6022/// which represents a range check and can be represented as a ConstantRange.
6023///
6024/// For icmp eq, build ConstantRange [Lo, Hi + 1) and convert to:
6025/// (X - Lo) u< (Hi + 1 - Lo)
6026/// For icmp ne, build ConstantRange [Hi + 1, Lo) and convert to:
6027/// (X - (Hi + 1)) u< (Lo - (Hi + 1))
6028Instruction *InstCombinerImpl::foldICmpWithClamp(ICmpInst &I, Value *X,
6029 MinMaxIntrinsic *Min) {
6030 if (!I.isEquality() || !Min->hasOneUse() || !Min->isMin())
6031 return nullptr;
6032
6033 const APInt *Lo = nullptr, *Hi = nullptr;
6034 if (Min->isSigned()) {
6035 if (!match(V: Min->getLHS(), P: m_OneUse(SubPattern: m_SMax(Op0: m_Specific(V: X), Op1: m_APInt(Res&: Lo)))) ||
6036 !match(V: Min->getRHS(), P: m_APInt(Res&: Hi)) || !Lo->slt(RHS: *Hi))
6037 return nullptr;
6038 } else {
6039 if (!match(V: Min->getLHS(), P: m_OneUse(SubPattern: m_UMax(Op0: m_Specific(V: X), Op1: m_APInt(Res&: Lo)))) ||
6040 !match(V: Min->getRHS(), P: m_APInt(Res&: Hi)) || !Lo->ult(RHS: *Hi))
6041 return nullptr;
6042 }
6043
6044 ConstantRange CR = ConstantRange::getNonEmpty(Lower: *Lo, Upper: *Hi + 1);
6045 ICmpInst::Predicate Pred;
6046 APInt C, Offset;
6047 if (I.getPredicate() == ICmpInst::ICMP_EQ)
6048 CR.getEquivalentICmp(Pred, RHS&: C, Offset);
6049 else
6050 CR.inverse().getEquivalentICmp(Pred, RHS&: C, Offset);
6051
6052 if (!Offset.isZero())
6053 X = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: Offset));
6054
6055 return replaceInstUsesWith(
6056 I, V: Builder.CreateICmp(P: Pred, LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: C)));
6057}
6058
6059// Canonicalize checking for a power-of-2-or-zero value:
6060static Instruction *foldICmpPow2Test(ICmpInst &I,
6061 InstCombiner::BuilderTy &Builder) {
6062 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
6063 const CmpInst::Predicate Pred = I.getPredicate();
6064 Value *A = nullptr;
6065 bool CheckIs;
6066 if (I.isEquality()) {
6067 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
6068 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
6069 if (!match(V: Op0, P: m_OneUse(SubPattern: m_c_And(L: m_Add(L: m_Value(V&: A), R: m_AllOnes()),
6070 R: m_Deferred(V: A)))) ||
6071 !match(V: Op1, P: m_ZeroInt()))
6072 A = nullptr;
6073
6074 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
6075 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
6076 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_And(L: m_Neg(V: m_Specific(V: Op1)), R: m_Specific(V: Op1)))))
6077 A = Op1;
6078 else if (match(V: Op1,
6079 P: m_OneUse(SubPattern: m_c_And(L: m_Neg(V: m_Specific(V: Op0)), R: m_Specific(V: Op0)))))
6080 A = Op0;
6081
6082 CheckIs = Pred == ICmpInst::ICMP_EQ;
6083 } else if (ICmpInst::isUnsigned(Pred)) {
6084 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
6085 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
6086
6087 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
6088 match(V: Op0, P: m_OneUse(SubPattern: m_c_Xor(L: m_Add(L: m_Specific(V: Op1), R: m_AllOnes()),
6089 R: m_Specific(V: Op1))))) {
6090 A = Op1;
6091 CheckIs = Pred == ICmpInst::ICMP_UGE;
6092 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
6093 match(V: Op1, P: m_OneUse(SubPattern: m_c_Xor(L: m_Add(L: m_Specific(V: Op0), R: m_AllOnes()),
6094 R: m_Specific(V: Op0))))) {
6095 A = Op0;
6096 CheckIs = Pred == ICmpInst::ICMP_ULE;
6097 }
6098 }
6099
6100 if (A) {
6101 Type *Ty = A->getType();
6102 Value *CtPop = Builder.CreateUnaryIntrinsic(ID: Intrinsic::ctpop, Op: A);
6103 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
6104 ConstantInt::get(Ty, V: 2))
6105 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
6106 ConstantInt::get(Ty, V: 1));
6107 }
6108
6109 return nullptr;
6110}
6111
6112/// Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
6113using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
6114static void collectOffsetOp(Value *V, SmallVectorImpl<OffsetOp> &Offsets,
6115 bool AllowRecursion) {
6116 Instruction *Inst = dyn_cast<Instruction>(Val: V);
6117 if (!Inst || !Inst->hasOneUse())
6118 return;
6119
6120 switch (Inst->getOpcode()) {
6121 case Instruction::Add:
6122 Offsets.emplace_back(Args: Instruction::Sub, Args: Inst->getOperand(i: 1));
6123 Offsets.emplace_back(Args: Instruction::Sub, Args: Inst->getOperand(i: 0));
6124 break;
6125 case Instruction::Sub:
6126 Offsets.emplace_back(Args: Instruction::Add, Args: Inst->getOperand(i: 1));
6127 break;
6128 case Instruction::Xor:
6129 Offsets.emplace_back(Args: Instruction::Xor, Args: Inst->getOperand(i: 1));
6130 Offsets.emplace_back(Args: Instruction::Xor, Args: Inst->getOperand(i: 0));
6131 break;
6132 case Instruction::Shl:
6133 if (Inst->hasNoSignedWrap())
6134 Offsets.emplace_back(Args: Instruction::AShr, Args: Inst->getOperand(i: 1));
6135 if (Inst->hasNoUnsignedWrap())
6136 Offsets.emplace_back(Args: Instruction::LShr, Args: Inst->getOperand(i: 1));
6137 break;
6138 case Instruction::Select:
6139 if (AllowRecursion) {
6140 collectOffsetOp(V: Inst->getOperand(i: 1), Offsets, /*AllowRecursion=*/false);
6141 collectOffsetOp(V: Inst->getOperand(i: 2), Offsets, /*AllowRecursion=*/false);
6142 }
6143 break;
6144 default:
6145 break;
6146 }
6147}
6148
6149enum class OffsetKind { Invalid, Value, Select };
6150
6151struct OffsetResult {
6152 OffsetKind Kind;
6153 Value *V0, *V1, *V2;
6154 Instruction *MDFrom;
6155
6156 static OffsetResult invalid() {
6157 return {.Kind: OffsetKind::Invalid, .V0: nullptr, .V1: nullptr, .V2: nullptr, .MDFrom: nullptr};
6158 }
6159 static OffsetResult value(Value *V) {
6160 return {.Kind: OffsetKind::Value, .V0: V, .V1: nullptr, .V2: nullptr, .MDFrom: nullptr};
6161 }
6162 static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV,
6163 Instruction *MDFrom) {
6164 return {.Kind: OffsetKind::Select, .V0: Cond, .V1: TrueV, .V2: FalseV, .MDFrom: MDFrom};
6165 }
6166 bool isValid() const { return Kind != OffsetKind::Invalid; }
6167 Value *materialize(InstCombiner::BuilderTy &Builder) const {
6168 switch (Kind) {
6169 case OffsetKind::Invalid:
6170 llvm_unreachable("Invalid offset result");
6171 case OffsetKind::Value:
6172 return V0;
6173 case OffsetKind::Select:
6174 return Builder.CreateSelect(C: V0, True: V1, False: V2, Name: "", MDFrom);
6175 }
6176 llvm_unreachable("Unknown OffsetKind enum");
6177 }
6178};
6179
6180/// Offset both sides of an equality icmp to see if we can save some
6181/// instructions: icmp eq/ne X, Y -> icmp eq/ne X op Z, Y op Z.
6182/// Note: This operation should not introduce poison.
6183static Instruction *foldICmpEqualityWithOffset(ICmpInst &I,
6184 InstCombiner::BuilderTy &Builder,
6185 const SimplifyQuery &SQ) {
6186 assert(I.isEquality() && "Expected an equality icmp");
6187 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
6188 if (!Op0->getType()->isIntOrIntVectorTy())
6189 return nullptr;
6190
6191 SmallVector<OffsetOp, 4> OffsetOps;
6192 collectOffsetOp(V: Op0, Offsets&: OffsetOps, /*AllowRecursion=*/true);
6193 collectOffsetOp(V: Op1, Offsets&: OffsetOps, /*AllowRecursion=*/true);
6194
6195 auto ApplyOffsetImpl = [&](Value *V, unsigned BinOpc, Value *RHS) -> Value * {
6196 switch (BinOpc) {
6197 // V = shl nsw X, RHS => X = ashr V, RHS
6198 case Instruction::AShr: {
6199 const APInt *CV, *CRHS;
6200 if (!(match(V, P: m_APInt(Res&: CV)) && match(V: RHS, P: m_APInt(Res&: CRHS)) &&
6201 CV->ashr(ShiftAmt: *CRHS).shl(ShiftAmt: *CRHS) == *CV) &&
6202 !match(V, P: m_NSWShl(L: m_Value(), R: m_Specific(V: RHS))))
6203 return nullptr;
6204 break;
6205 }
6206 // V = shl nuw X, RHS => X = lshr V, RHS
6207 case Instruction::LShr: {
6208 const APInt *CV, *CRHS;
6209 if (!(match(V, P: m_APInt(Res&: CV)) && match(V: RHS, P: m_APInt(Res&: CRHS)) &&
6210 CV->lshr(ShiftAmt: *CRHS).shl(ShiftAmt: *CRHS) == *CV) &&
6211 !match(V, P: m_NUWShl(L: m_Value(), R: m_Specific(V: RHS))))
6212 return nullptr;
6213 break;
6214 }
6215 default:
6216 break;
6217 }
6218
6219 Value *Simplified = simplifyBinOp(Opcode: BinOpc, LHS: V, RHS, Q: SQ);
6220 if (!Simplified)
6221 return nullptr;
6222 // Reject constant expressions as they don't simplify things.
6223 if (isa<Constant>(Val: Simplified) && !match(V: Simplified, P: m_ImmConstant()))
6224 return nullptr;
6225 // Check if the transformation introduces poison.
6226 return impliesPoison(ValAssumedPoison: RHS, V) ? Simplified : nullptr;
6227 };
6228
6229 auto ApplyOffset = [&](Value *V, unsigned BinOpc,
6230 Value *RHS) -> OffsetResult {
6231 if (auto *Sel = dyn_cast<SelectInst>(Val: V)) {
6232 if (!Sel->hasOneUse())
6233 return OffsetResult::invalid();
6234 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc, RHS);
6235 if (!TrueVal)
6236 return OffsetResult::invalid();
6237 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc, RHS);
6238 if (!FalseVal)
6239 return OffsetResult::invalid();
6240 return OffsetResult::select(Cond: Sel->getCondition(), TrueV: TrueVal, FalseV: FalseVal, MDFrom: Sel);
6241 }
6242 if (Value *Simplified = ApplyOffsetImpl(V, BinOpc, RHS))
6243 return OffsetResult::value(V: Simplified);
6244 return OffsetResult::invalid();
6245 };
6246
6247 for (auto [BinOp, RHS] : OffsetOps) {
6248 auto BinOpc = static_cast<unsigned>(BinOp);
6249
6250 auto Op0Result = ApplyOffset(Op0, BinOpc, RHS);
6251 if (!Op0Result.isValid())
6252 continue;
6253 auto Op1Result = ApplyOffset(Op1, BinOpc, RHS);
6254 if (!Op1Result.isValid())
6255 continue;
6256
6257 Value *NewLHS = Op0Result.materialize(Builder);
6258 Value *NewRHS = Op1Result.materialize(Builder);
6259 return new ICmpInst(I.getPredicate(), NewLHS, NewRHS);
6260 }
6261
6262 return nullptr;
6263}
6264
6265Instruction *InstCombinerImpl::foldICmpEquality(ICmpInst &I) {
6266 if (!I.isEquality())
6267 return nullptr;
6268
6269 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
6270 const CmpInst::Predicate Pred = I.getPredicate();
6271 Value *A, *B, *C, *D;
6272 if (match(V: Op0, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B)))) {
6273 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6274 Value *OtherVal = A == Op1 ? B : A;
6275 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(Ty: A->getType()));
6276 }
6277
6278 if (match(V: Op1, P: m_Xor(L: m_Value(V&: C), R: m_Value(V&: D)))) {
6279 // A^c1 == C^c2 --> A == C^(c1^c2)
6280 ConstantInt *C1, *C2;
6281 if (match(V: B, P: m_ConstantInt(CI&: C1)) && match(V: D, P: m_ConstantInt(CI&: C2)) &&
6282 Op1->hasOneUse()) {
6283 Constant *NC = Builder.getInt(AI: C1->getValue() ^ C2->getValue());
6284 Value *Xor = Builder.CreateXor(LHS: C, RHS: NC);
6285 return new ICmpInst(Pred, A, Xor);
6286 }
6287
6288 // A^B == A^D -> B == D
6289 if (A == C)
6290 return new ICmpInst(Pred, B, D);
6291 if (A == D)
6292 return new ICmpInst(Pred, B, C);
6293 if (B == C)
6294 return new ICmpInst(Pred, A, D);
6295 if (B == D)
6296 return new ICmpInst(Pred, A, C);
6297 }
6298 }
6299
6300 if (match(V: Op1, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))) && (A == Op0 || B == Op0)) {
6301 // A == (A^B) -> B == 0
6302 Value *OtherVal = A == Op0 ? B : A;
6303 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(Ty: A->getType()));
6304 }
6305
6306 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6307 if (match(V: Op0, P: m_And(L: m_Value(V&: A), R: m_Value(V&: B))) &&
6308 match(V: Op1, P: m_And(L: m_Value(V&: C), R: m_Value(V&: D)))) {
6309 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
6310
6311 if (A == C) {
6312 X = B;
6313 Y = D;
6314 Z = A;
6315 } else if (A == D) {
6316 X = B;
6317 Y = C;
6318 Z = A;
6319 } else if (B == C) {
6320 X = A;
6321 Y = D;
6322 Z = B;
6323 } else if (B == D) {
6324 X = A;
6325 Y = C;
6326 Z = B;
6327 }
6328
6329 if (X) {
6330 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
6331 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
6332 // instructions.
6333 const APInt *C0, *C1;
6334 bool XorIsNegP2 = match(V: X, P: m_APInt(Res&: C0)) && match(V: Y, P: m_APInt(Res&: C1)) &&
6335 (*C0 ^ *C1).isNegatedPowerOf2();
6336
6337 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
6338 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
6339 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
6340 int UseCnt =
6341 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
6342 (int(match(V: X, P: m_ImmConstant()) && match(V: Y, P: m_ImmConstant())));
6343 if (XorIsNegP2 || UseCnt >= 2) {
6344 // Build (X^Y) & Z
6345 Op1 = Builder.CreateXor(LHS: X, RHS: Y);
6346 Op1 = Builder.CreateAnd(LHS: Op1, RHS: Z);
6347 return new ICmpInst(Pred, Op1, Constant::getNullValue(Ty: Op1->getType()));
6348 }
6349 }
6350 }
6351
6352 {
6353 // Similar to above, but specialized for constant because invert is needed:
6354 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
6355 Value *X, *Y;
6356 Constant *C;
6357 if (match(V: Op0, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: X), R: m_Constant(C)))) &&
6358 match(V: Op1, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: Y), R: m_Specific(V: C))))) {
6359 Value *Xor = Builder.CreateXor(LHS: X, RHS: Y);
6360 Value *And = Builder.CreateAnd(LHS: Xor, RHS: ConstantExpr::getNot(C));
6361 return new ICmpInst(Pred, And, Constant::getNullValue(Ty: And->getType()));
6362 }
6363 }
6364
6365 if (match(V: Op1, P: m_ZExt(Op: m_Value(V&: A))) &&
6366 (Op0->hasOneUse() || Op1->hasOneUse())) {
6367 // (B & (Pow2C-1)) == zext A --> A == trunc B
6368 // (B & (Pow2C-1)) != zext A --> A != trunc B
6369 const APInt *MaskC;
6370 if (match(V: Op0, P: m_And(L: m_Value(V&: B), R: m_LowBitMask(V&: MaskC))) &&
6371 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
6372 return new ICmpInst(Pred, A, Builder.CreateTrunc(V: B, DestTy: A->getType()));
6373 }
6374
6375 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
6376 // For lshr and ashr pairs.
6377 const APInt *AP1, *AP2;
6378 if ((match(V: Op0, P: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: A), R: m_APIntAllowPoison(Res&: AP1)))) &&
6379 match(V: Op1, P: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: B), R: m_APIntAllowPoison(Res&: AP2))))) ||
6380 (match(V: Op0, P: m_OneUse(SubPattern: m_AShr(L: m_Value(V&: A), R: m_APIntAllowPoison(Res&: AP1)))) &&
6381 match(V: Op1, P: m_OneUse(SubPattern: m_AShr(L: m_Value(V&: B), R: m_APIntAllowPoison(Res&: AP2)))))) {
6382 if (*AP1 != *AP2)
6383 return nullptr;
6384 unsigned TypeBits = AP1->getBitWidth();
6385 unsigned ShAmt = AP1->getLimitedValue(Limit: TypeBits);
6386 if (ShAmt < TypeBits && ShAmt != 0) {
6387 ICmpInst::Predicate NewPred =
6388 Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6389 Value *Xor = Builder.CreateXor(LHS: A, RHS: B, Name: I.getName() + ".unshifted");
6390 APInt CmpVal = APInt::getOneBitSet(numBits: TypeBits, BitNo: ShAmt);
6391 return new ICmpInst(NewPred, Xor, ConstantInt::get(Ty: A->getType(), V: CmpVal));
6392 }
6393 }
6394
6395 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
6396 ConstantInt *Cst1;
6397 if (match(V: Op0, P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: A), R: m_ConstantInt(CI&: Cst1)))) &&
6398 match(V: Op1, P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: B), R: m_Specific(V: Cst1))))) {
6399 unsigned TypeBits = Cst1->getBitWidth();
6400 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(Limit: TypeBits);
6401 if (ShAmt < TypeBits && ShAmt != 0) {
6402 Value *Xor = Builder.CreateXor(LHS: A, RHS: B, Name: I.getName() + ".unshifted");
6403 APInt AndVal = APInt::getLowBitsSet(numBits: TypeBits, loBitsSet: TypeBits - ShAmt);
6404 Value *And =
6405 Builder.CreateAnd(LHS: Xor, RHS: Builder.getInt(AI: AndVal), Name: I.getName() + ".mask");
6406 return new ICmpInst(Pred, And, Constant::getNullValue(Ty: Cst1->getType()));
6407 }
6408 }
6409
6410 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
6411 // "icmp (and X, mask), cst"
6412 uint64_t ShAmt = 0;
6413 if (Op0->hasOneUse() &&
6414 match(V: Op0, P: m_Trunc(Op: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: A), R: m_ConstantInt(V&: ShAmt))))) &&
6415 match(V: Op1, P: m_ConstantInt(CI&: Cst1)) &&
6416 // Only do this when A has multiple uses. This is most important to do
6417 // when it exposes other optimizations.
6418 !A->hasOneUse()) {
6419 unsigned ASize = cast<IntegerType>(Val: A->getType())->getPrimitiveSizeInBits();
6420
6421 if (ShAmt < ASize) {
6422 APInt MaskV =
6423 APInt::getLowBitsSet(numBits: ASize, loBitsSet: Op0->getType()->getPrimitiveSizeInBits());
6424 MaskV <<= ShAmt;
6425
6426 APInt CmpV = Cst1->getValue().zext(width: ASize);
6427 CmpV <<= ShAmt;
6428
6429 Value *Mask = Builder.CreateAnd(LHS: A, RHS: Builder.getInt(AI: MaskV));
6430 return new ICmpInst(Pred, Mask, Builder.getInt(AI: CmpV));
6431 }
6432 }
6433
6434 if (Instruction *ICmp = foldICmpIntrinsicWithIntrinsic(Cmp&: I, Builder))
6435 return ICmp;
6436
6437 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
6438 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
6439 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
6440 // few steps of instcombine.
6441 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6442 if (match(V: Op0, P: m_AShr(L: m_Trunc(Op: m_Value(V&: A)), R: m_SpecificInt(V: BitWidth - 1))) &&
6443 match(V: Op1, P: m_Trunc(Op: m_LShr(L: m_Specific(V: A), R: m_SpecificInt(V: BitWidth)))) &&
6444 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
6445 (I.getOperand(i_nocapture: 0)->hasOneUse() || I.getOperand(i_nocapture: 1)->hasOneUse())) {
6446 APInt C = APInt::getOneBitSet(numBits: BitWidth * 2, BitNo: BitWidth - 1);
6447 Value *Add = Builder.CreateAdd(LHS: A, RHS: ConstantInt::get(Ty: A->getType(), V: C));
6448 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
6449 : ICmpInst::ICMP_UGE,
6450 Add, ConstantInt::get(Ty: A->getType(), V: C.shl(shiftAmt: 1)));
6451 }
6452
6453 // Canonicalize:
6454 // Assume B_Pow2 != 0
6455 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
6456 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
6457 if (match(V: Op0, P: m_c_And(L: m_Specific(V: Op1), R: m_Value())) &&
6458 isKnownToBeAPowerOfTwo(V: Op1, /* OrZero */ false, CtxI: &I))
6459 return new ICmpInst(CmpInst::getInversePredicate(pred: Pred), Op0,
6460 ConstantInt::getNullValue(Ty: Op0->getType()));
6461
6462 if (match(V: Op1, P: m_c_And(L: m_Specific(V: Op0), R: m_Value())) &&
6463 isKnownToBeAPowerOfTwo(V: Op0, /* OrZero */ false, CtxI: &I))
6464 return new ICmpInst(CmpInst::getInversePredicate(pred: Pred), Op1,
6465 ConstantInt::getNullValue(Ty: Op1->getType()));
6466
6467 // Canonicalize:
6468 // icmp eq/ne X, OneUse(rotate-right(X))
6469 // -> icmp eq/ne X, rotate-left(X)
6470 // We generally try to convert rotate-right -> rotate-left, this just
6471 // canonicalizes another case.
6472 if (match(V: &I, P: m_c_ICmp(L: m_Value(V&: A),
6473 R: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::fshr>(
6474 Ops: m_Deferred(V: A), Ops: m_Deferred(V: A), Ops: m_Value(V&: B))))))
6475 return new ICmpInst(
6476 Pred, A,
6477 Builder.CreateIntrinsic(RetTy: Op0->getType(), ID: Intrinsic::fshl, Args: {A, A, B}));
6478
6479 // Canonicalize:
6480 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
6481 Constant *Cst;
6482 if (match(V: &I, P: m_c_ICmp(L: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: A), R: m_ImmConstant(C&: Cst))),
6483 R: m_CombineAnd(Ps: m_Value(V&: B), Ps: m_Unless(P: m_ImmConstant())))))
6484 return new ICmpInst(Pred, Builder.CreateXor(LHS: A, RHS: B), Cst);
6485
6486 {
6487 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6488 auto m_Matcher =
6489 m_CombineOr(Ps: m_CombineOr(Ps: m_c_Add(L: m_Value(V&: B), R: m_Deferred(V: A)),
6490 Ps: m_c_Xor(L: m_Value(V&: B), R: m_Deferred(V: A))),
6491 Ps: m_Sub(L: m_Value(V&: B), R: m_Deferred(V: A)));
6492 std::optional<bool> IsZero = std::nullopt;
6493 if (match(V: &I, P: m_c_ICmp(L: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: A), R: m_Matcher)),
6494 R: m_Deferred(V: A))))
6495 IsZero = false;
6496 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6497 else if (match(V: &I,
6498 P: m_ICmp(L: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: A), R: m_Matcher)), R: m_Zero())))
6499 IsZero = true;
6500
6501 if (IsZero && isKnownToBeAPowerOfTwo(V: A, /* OrZero */ true, CtxI: &I))
6502 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6503 // -> (icmp eq/ne (and X, P2), 0)
6504 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6505 // -> (icmp eq/ne (and X, P2), P2)
6506 return new ICmpInst(Pred, Builder.CreateAnd(LHS: B, RHS: A),
6507 *IsZero ? A
6508 : ConstantInt::getNullValue(Ty: A->getType()));
6509 }
6510
6511 if (auto *Res = foldICmpEqualityWithOffset(
6512 I, Builder, SQ: getSimplifyQuery().getWithInstruction(I: &I)))
6513 return Res;
6514
6515 return nullptr;
6516}
6517
6518Instruction *InstCombinerImpl::foldICmpWithTrunc(ICmpInst &ICmp) {
6519 ICmpInst::Predicate Pred = ICmp.getPredicate();
6520 Value *Op0 = ICmp.getOperand(i_nocapture: 0), *Op1 = ICmp.getOperand(i_nocapture: 1);
6521
6522 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6523 // The trunc masks high bits while the compare may effectively mask low bits.
6524 Value *X;
6525 const APInt *C;
6526 if (!match(V: Op0, P: m_OneUse(SubPattern: m_Trunc(Op: m_Value(V&: X)))) || !match(V: Op1, P: m_APInt(Res&: C)))
6527 return nullptr;
6528
6529 // This matches patterns corresponding to tests of the signbit as well as:
6530 // (trunc X) pred C2 --> (X & Mask) == C
6531 if (auto Res = decomposeBitTestICmp(LHS: Op0, RHS: Op1, Pred, /*LookThroughTrunc=*/true,
6532 /*AllowNonZeroC=*/true)) {
6533 Value *And = Builder.CreateAnd(LHS: Res->X, RHS: Res->Mask);
6534 Constant *C = ConstantInt::get(Ty: Res->X->getType(), V: Res->C);
6535 return new ICmpInst(Res->Pred, And, C);
6536 }
6537
6538 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6539 if (auto *II = dyn_cast<IntrinsicInst>(Val: X)) {
6540 if (II->getIntrinsicID() == Intrinsic::cttz ||
6541 II->getIntrinsicID() == Intrinsic::ctlz) {
6542 unsigned MaxRet = SrcBits;
6543 // If the "is_zero_poison" argument is set, then we know at least
6544 // one bit is set in the input, so the result is always at least one
6545 // less than the full bitwidth of that input.
6546 if (match(V: II->getArgOperand(i: 1), P: m_One()))
6547 MaxRet--;
6548
6549 // Make sure the destination is wide enough to hold the largest output of
6550 // the intrinsic.
6551 if (llvm::Log2_32(Value: MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6552 if (Instruction *I =
6553 foldICmpIntrinsicWithConstant(Cmp&: ICmp, II, C: C->zext(width: SrcBits)))
6554 return I;
6555 }
6556 }
6557
6558 return nullptr;
6559}
6560
6561Instruction *InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst &ICmp) {
6562 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6563 auto *CastOp0 = cast<CastInst>(Val: ICmp.getOperand(i_nocapture: 0));
6564 Value *X;
6565 if (!match(V: CastOp0, P: m_ZExtOrSExt(Op: m_Value(V&: X))))
6566 return nullptr;
6567
6568 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6569 bool IsSignedCmp = ICmp.isSigned();
6570
6571 // icmp Pred (ext X), (ext Y)
6572 Value *Y;
6573 if (match(V: ICmp.getOperand(i_nocapture: 1), P: m_ZExtOrSExt(Op: m_Value(V&: Y)))) {
6574 bool IsZext0 = isa<ZExtInst>(Val: ICmp.getOperand(i_nocapture: 0));
6575 bool IsZext1 = isa<ZExtInst>(Val: ICmp.getOperand(i_nocapture: 1));
6576
6577 if (IsZext0 != IsZext1) {
6578 // If X and Y and both i1
6579 // (icmp eq/ne (zext X) (sext Y))
6580 // eq -> (icmp eq (or X, Y), 0)
6581 // ne -> (icmp ne (or X, Y), 0)
6582 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(BitWidth: 1) &&
6583 Y->getType()->isIntOrIntVectorTy(BitWidth: 1))
6584 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(LHS: X, RHS: Y),
6585 Constant::getNullValue(Ty: X->getType()));
6586
6587 // If we have mismatched casts and zext has the nneg flag, we can
6588 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6589
6590 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(Val: ICmp.getOperand(i_nocapture: 0));
6591 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(Val: ICmp.getOperand(i_nocapture: 1));
6592
6593 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6594 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6595
6596 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6597 IsSignedExt = true;
6598 else
6599 return nullptr;
6600 }
6601
6602 // Not an extension from the same type?
6603 Type *XTy = X->getType(), *YTy = Y->getType();
6604 if (XTy != YTy) {
6605 // One of the casts must have one use because we are creating a new cast.
6606 if (!ICmp.getOperand(i_nocapture: 0)->hasOneUse() && !ICmp.getOperand(i_nocapture: 1)->hasOneUse())
6607 return nullptr;
6608 // Extend the narrower operand to the type of the wider operand.
6609 CastInst::CastOps CastOpcode =
6610 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6611 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6612 X = Builder.CreateCast(Op: CastOpcode, V: X, DestTy: YTy);
6613 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6614 Y = Builder.CreateCast(Op: CastOpcode, V: Y, DestTy: XTy);
6615 else
6616 return nullptr;
6617 }
6618
6619 // (zext X) == (zext Y) --> X == Y
6620 // (sext X) == (sext Y) --> X == Y
6621 if (ICmp.isEquality())
6622 return new ICmpInst(ICmp.getPredicate(), X, Y);
6623
6624 // A signed comparison of sign extended values simplifies into a
6625 // signed comparison.
6626 if (IsSignedCmp && IsSignedExt)
6627 return new ICmpInst(ICmp.getPredicate(), X, Y);
6628
6629 // The other three cases all fold into an unsigned comparison.
6630 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6631 }
6632
6633 // Below here, we are only folding a compare with constant.
6634 auto *C = dyn_cast<Constant>(Val: ICmp.getOperand(i_nocapture: 1));
6635 if (!C)
6636 return nullptr;
6637
6638 // If a lossless truncate is possible...
6639 Type *SrcTy = CastOp0->getSrcTy();
6640 Constant *Res = getLosslessInvCast(C, InvCastTo: SrcTy, CastOp: CastOp0->getOpcode(), DL);
6641 if (Res) {
6642 if (ICmp.isEquality())
6643 return new ICmpInst(ICmp.getPredicate(), X, Res);
6644
6645 // A signed comparison of sign extended values simplifies into a
6646 // signed comparison.
6647 if (IsSignedExt && IsSignedCmp)
6648 return new ICmpInst(ICmp.getPredicate(), X, Res);
6649
6650 // The other three cases all fold into an unsigned comparison.
6651 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6652 }
6653
6654 // The re-extended constant changed, partly changed (in the case of a vector),
6655 // or could not be determined to be equal (in the case of a constant
6656 // expression), so the constant cannot be represented in the shorter type.
6657 // All the cases that fold to true or false will have already been handled
6658 // by simplifyICmpInst, so only deal with the tricky case.
6659 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(Val: C))
6660 return nullptr;
6661
6662 // Is source op positive?
6663 // icmp ult (sext X), C --> icmp sgt X, -1
6664 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6665 return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(Ty: SrcTy));
6666
6667 // Is source op negative?
6668 // icmp ugt (sext X), C --> icmp slt X, 0
6669 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6670 return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(Ty: SrcTy));
6671}
6672
6673/// Handle icmp (cast x), (cast or constant).
6674Instruction *InstCombinerImpl::foldICmpWithCastOp(ICmpInst &ICmp) {
6675 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6676 // icmp compares only pointer's value.
6677 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6678 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(Val: ICmp.getOperand(i_nocapture: 0));
6679 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(Val: ICmp.getOperand(i_nocapture: 1));
6680 if (SimplifiedOp0 || SimplifiedOp1)
6681 return new ICmpInst(ICmp.getPredicate(),
6682 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(i_nocapture: 0),
6683 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(i_nocapture: 1));
6684
6685 auto *CastOp0 = dyn_cast<CastInst>(Val: ICmp.getOperand(i_nocapture: 0));
6686 Value *Op1 = ICmp.getOperand(i_nocapture: 1);
6687 if (!CastOp0)
6688 return nullptr;
6689 if (!isa<Constant>(Val: ICmp.getOperand(i_nocapture: 1)) && !isa<CastInst>(Val: ICmp.getOperand(i_nocapture: 1)))
6690 return nullptr;
6691
6692 Value *Op0Src = CastOp0->getOperand(i_nocapture: 0);
6693 Type *SrcTy = CastOp0->getSrcTy();
6694 Type *DestTy = CastOp0->getDestTy();
6695
6696 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6697 // integer type is the same size as the pointer type.
6698 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6699 unsigned IntWidth = IntTy->getScalarType()->getIntegerBitWidth();
6700 unsigned IndexWidth = DL.getAddressSizeInBits(Ty: PtrTy);
6701 unsigned PtrWidth = DL.getPointerTypeSizeInBits(PtrTy);
6702 // For ptrtoint/inttoptr, we must check that IntWidth == IndexWidth and also
6703 // IndexWidth == PtrWidth to (not) handle non-integral pointers.
6704 return IntWidth == IndexWidth && IndexWidth == PtrWidth;
6705 };
6706 if (isa<PtrToIntInst, PtrToAddrInst>(Val: CastOp0)) {
6707 bool HasPtrToInt = isa<PtrToIntInst>(Val: CastOp0);
6708 Value *NewOp1 = nullptr;
6709 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(Val: Op1)) {
6710 NewOp1 = PtrToIntOp1->getOperand(i_nocapture: 0);
6711 HasPtrToInt = true;
6712 } else if (auto *PtrToAddrOp1 = dyn_cast<PtrToAddrOperator>(Val: Op1)) {
6713 NewOp1 = PtrToAddrOp1->getOperand(i_nocapture: 0);
6714 } else if (auto *RHSC = dyn_cast<Constant>(Val: Op1)) {
6715 NewOp1 = ConstantExpr::getIntToPtr(C: RHSC, Ty: SrcTy);
6716 }
6717
6718 // For ptrtoaddr, IntWidth == IndexWidth is implied and we don't need to
6719 // check PtrWidth.
6720 if ((!HasPtrToInt || CompatibleSizes(SrcTy, DestTy)) &&
6721 (NewOp1 && NewOp1->getType() == Op0Src->getType()))
6722 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6723 }
6724
6725 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6726 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6727 CompatibleSizes(DestTy, SrcTy)) {
6728 Value *NewOp1 = nullptr;
6729 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(Val: Op1)) {
6730 Value *IntSrc = IntToPtrOp1->getOperand(i_nocapture: 0);
6731 if (IntSrc->getType() == Op0Src->getType())
6732 NewOp1 = IntToPtrOp1->getOperand(i_nocapture: 0);
6733 } else if (auto *RHSC = dyn_cast<Constant>(Val: Op1)) {
6734 NewOp1 = ConstantFoldConstant(C: ConstantExpr::getPtrToInt(C: RHSC, Ty: SrcTy), DL);
6735 }
6736
6737 if (NewOp1)
6738 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6739 }
6740
6741 if (Instruction *R = foldICmpWithTrunc(ICmp))
6742 return R;
6743
6744 return foldICmpWithZextOrSext(ICmp);
6745}
6746
6747static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS,
6748 bool IsSigned) {
6749 switch (BinaryOp) {
6750 default:
6751 llvm_unreachable("Unsupported binary op");
6752 case Instruction::Add:
6753 case Instruction::Sub:
6754 return match(V: RHS, P: m_Zero());
6755 case Instruction::Mul:
6756 return !(RHS->getType()->isIntOrIntVectorTy(BitWidth: 1) && IsSigned) &&
6757 match(V: RHS, P: m_One());
6758 }
6759}
6760
6761OverflowResult
6762InstCombinerImpl::computeOverflow(Instruction::BinaryOps BinaryOp,
6763 bool IsSigned, Value *LHS, Value *RHS,
6764 Instruction *CtxI) const {
6765 switch (BinaryOp) {
6766 default:
6767 llvm_unreachable("Unsupported binary op");
6768 case Instruction::Add:
6769 if (IsSigned)
6770 return computeOverflowForSignedAdd(LHS, RHS, CtxI);
6771 else
6772 return computeOverflowForUnsignedAdd(LHS, RHS, CtxI);
6773 case Instruction::Sub:
6774 if (IsSigned)
6775 return computeOverflowForSignedSub(LHS, RHS, CtxI);
6776 else
6777 return computeOverflowForUnsignedSub(LHS, RHS, CtxI);
6778 case Instruction::Mul:
6779 if (IsSigned)
6780 return computeOverflowForSignedMul(LHS, RHS, CtxI);
6781 else
6782 return computeOverflowForUnsignedMul(LHS, RHS, CtxI);
6783 }
6784}
6785
6786bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6787 bool IsSigned, Value *LHS,
6788 Value *RHS, Instruction &OrigI,
6789 Value *&Result,
6790 Constant *&Overflow) {
6791 if (OrigI.isCommutative() && isa<Constant>(Val: LHS) && !isa<Constant>(Val: RHS))
6792 std::swap(a&: LHS, b&: RHS);
6793
6794 // If the overflow check was an add followed by a compare, the insertion point
6795 // may be pointing to the compare. We want to insert the new instructions
6796 // before the add in case there are uses of the add between the add and the
6797 // compare.
6798 Builder.SetInsertPoint(&OrigI);
6799
6800 Type *OverflowTy = Type::getInt1Ty(C&: LHS->getContext());
6801 if (auto *LHSTy = dyn_cast<VectorType>(Val: LHS->getType()))
6802 OverflowTy = VectorType::get(ElementType: OverflowTy, EC: LHSTy->getElementCount());
6803
6804 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6805 Result = LHS;
6806 Overflow = ConstantInt::getFalse(Ty: OverflowTy);
6807 return true;
6808 }
6809
6810 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, CtxI: &OrigI)) {
6811 case OverflowResult::MayOverflow:
6812 return false;
6813 case OverflowResult::AlwaysOverflowsLow:
6814 case OverflowResult::AlwaysOverflowsHigh:
6815 Result = Builder.CreateBinOp(Opc: BinaryOp, LHS, RHS);
6816 Result->takeName(V: &OrigI);
6817 Overflow = ConstantInt::getTrue(Ty: OverflowTy);
6818 return true;
6819 case OverflowResult::NeverOverflows:
6820 Result = Builder.CreateBinOp(Opc: BinaryOp, LHS, RHS);
6821 Result->takeName(V: &OrigI);
6822 Overflow = ConstantInt::getFalse(Ty: OverflowTy);
6823 if (auto *Inst = dyn_cast<Instruction>(Val: Result)) {
6824 if (IsSigned)
6825 Inst->setHasNoSignedWrap();
6826 else
6827 Inst->setHasNoUnsignedWrap();
6828 }
6829 return true;
6830 }
6831
6832 llvm_unreachable("Unexpected overflow result");
6833}
6834
6835/// Recognize and process idiom involving test for unsigned
6836/// overflow.
6837///
6838/// The caller has matched a pattern of the form:
6839/// I = cmp u (add(zext A, zext B), V
6840/// I = cmp u (mul(zext A, zext B), V
6841/// The function checks if this is a test for overflow and if so replaces
6842/// addition/multiplication with call to the umul intrinsic or the canonical
6843/// form of uadd overflow.
6844///
6845/// \param I Compare instruction.
6846/// \param Val Result of add/mul instruction. It is one of the arguments of
6847/// the compare instruction. Must be of integer type.
6848/// \param OtherVal The other argument of compare instruction.
6849/// \returns Instruction which must replace the compare instruction, NULL if no
6850/// replacement required.
6851static Instruction *processUZExtIdiom(ICmpInst &I, Value *Val,
6852 const APInt *OtherVal,
6853 InstCombinerImpl &IC) {
6854 // Don't bother doing this transformation for pointers, don't do it for
6855 // vectors.
6856 if (!isa<IntegerType>(Val: Val->getType()))
6857 return nullptr;
6858
6859 auto *Instr = cast<Instruction>(Val);
6860 unsigned Opcode = Instr->getOpcode();
6861 assert(Opcode == Instruction::Add || Opcode == Instruction::Mul);
6862
6863 auto *LHS = cast<ZExtInst>(Val: Instr->getOperand(i: 0)),
6864 *RHS = cast<ZExtInst>(Val: Instr->getOperand(i: 1));
6865 Value *A = LHS->getOperand(i_nocapture: 0), *B = RHS->getOperand(i_nocapture: 0);
6866
6867 // Calculate type and width of the result produced by add/mul.with.overflow.
6868 Type *TyA = A->getType(), *TyB = B->getType();
6869 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6870 WidthB = TyB->getPrimitiveSizeInBits();
6871 unsigned ResultWidth;
6872 Type *ResultType;
6873 if (WidthB > WidthA) {
6874 ResultWidth = WidthB;
6875 ResultType = TyB;
6876 } else {
6877 ResultWidth = WidthA;
6878 ResultType = TyA;
6879 }
6880
6881 // In order to replace the original result with a narrower one, all uses must
6882 // ignore upper bits of the result. The number of used low bits must be not
6883 // greater than the width of add or mul.with.overflow.
6884 if (Val->hasNUsesOrMore(N: 2))
6885 for (User *U : Val->users()) {
6886 if (U == &I)
6887 continue;
6888 if (TruncInst *TI = dyn_cast<TruncInst>(Val: U)) {
6889 // Check if truncation ignores bits above ResultWidth.
6890 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
6891 if (TruncWidth > ResultWidth)
6892 return nullptr;
6893 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: U)) {
6894 // Check if AND ignores bits above ResultWidth.
6895 if (BO->getOpcode() != Instruction::And)
6896 return nullptr;
6897 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: BO->getOperand(i_nocapture: 1))) {
6898 const APInt &CVal = CI->getValue();
6899 if (CVal.getBitWidth() - CVal.countl_zero() > ResultWidth)
6900 return nullptr;
6901 } else {
6902 // In this case we could have the operand of the binary operation
6903 // being defined in another block, and performing the replacement
6904 // could break the dominance relation.
6905 return nullptr;
6906 }
6907 } else {
6908 // Other uses prohibit this transformation.
6909 return nullptr;
6910 }
6911 }
6912
6913 // Recognize patterns
6914 switch (I.getPredicate()) {
6915 case ICmpInst::ICMP_UGT: {
6916 // Recognize pattern:
6917 // val = add/mul(zext A, zext B)
6918 // cmp ugt val, max
6919 APInt MaxVal = APInt::getMaxValue(numBits: ResultWidth);
6920 MaxVal = MaxVal.zext(width: OtherVal->getBitWidth());
6921 if (MaxVal.eq(RHS: *OtherVal))
6922 break; // Recognized
6923 return nullptr;
6924 }
6925
6926 case ICmpInst::ICMP_ULT: {
6927 // Recognize pattern:
6928 // val = add/mul(zext A, zext B)
6929 // cmp ult val, max + 1
6930 APInt MaxVal = APInt::getOneBitSet(numBits: OtherVal->getBitWidth(), BitNo: ResultWidth);
6931 if (MaxVal.eq(RHS: *OtherVal))
6932 break; // Recognized
6933 return nullptr;
6934 }
6935
6936 default:
6937 return nullptr;
6938 }
6939
6940 InstCombiner::BuilderTy &Builder = IC.Builder;
6941 Builder.SetInsertPoint(Instr);
6942
6943 // Replace: add/mul(zext A, zext B) --> canonical add/mul + overflow check
6944 Value *ResultA = A, *ResultB = B;
6945 if (WidthA < ResultWidth)
6946 ResultA = Builder.CreateZExt(V: A, DestTy: ResultType);
6947 if (WidthB < ResultWidth)
6948 ResultB = Builder.CreateZExt(V: B, DestTy: ResultType);
6949
6950 Value *ArithResult;
6951 Value *OverflowCheck;
6952
6953 if (Opcode == Instruction::Add) {
6954 // Canonical add overflow check: add + compare
6955 ArithResult = Builder.CreateAdd(LHS: ResultA, RHS: ResultB, Name: "add");
6956 // Overflow if result < either operand (for unsigned add)
6957 if (I.getPredicate() == ICmpInst::ICMP_ULT)
6958 OverflowCheck =
6959 Builder.CreateICmpUGE(LHS: ArithResult, RHS: ResultA, Name: "not.add.overflow");
6960 else
6961 OverflowCheck =
6962 Builder.CreateICmpULT(LHS: ArithResult, RHS: ResultA, Name: "add.overflow");
6963 } else {
6964 // For multiplication, the intrinsic is actually the canonical form
6965 Value *Call = Builder.CreateIntrinsic(ID: Intrinsic::umul_with_overflow,
6966 OverloadTypes: ResultType, Args: {ResultA, ResultB},
6967 /*FMFSource=*/nullptr, Name: "umul");
6968 ArithResult = Builder.CreateExtractValue(Agg: Call, Idxs: 0, Name: "umul.value");
6969 OverflowCheck = Builder.CreateExtractValue(Agg: Call, Idxs: 1, Name: "umul.overflow");
6970 if (I.getPredicate() == ICmpInst::ICMP_ULT)
6971 OverflowCheck = Builder.CreateNot(V: OverflowCheck);
6972 }
6973
6974 IC.addToWorklist(I: Instr);
6975
6976 // Replace uses of the original add/mul result with the new arithmetic result
6977 if (Val->hasNUsesOrMore(N: 2)) {
6978 for (User *U : make_early_inc_range(Range: Val->users())) {
6979 if (U == &I)
6980 continue;
6981 if (TruncInst *TI = dyn_cast<TruncInst>(Val: U)) {
6982 if (TI->getType()->getPrimitiveSizeInBits() == ResultWidth)
6983 IC.replaceInstUsesWith(I&: *TI, V: ArithResult);
6984 else
6985 TI->setOperand(i_nocapture: 0, Val_nocapture: ArithResult);
6986 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: U)) {
6987 assert(BO->getOpcode() == Instruction::And);
6988 // Replace (ArithResult & mask) --> zext (ArithResult & short_mask)
6989 ConstantInt *CI = cast<ConstantInt>(Val: BO->getOperand(i_nocapture: 1));
6990 APInt ShortMask = CI->getValue().trunc(width: ResultWidth);
6991 Value *ShortAnd = Builder.CreateAnd(LHS: ArithResult, RHS: ShortMask);
6992 Value *Zext = Builder.CreateZExt(V: ShortAnd, DestTy: BO->getType());
6993 IC.replaceInstUsesWith(I&: *BO, V: Zext);
6994 } else {
6995 llvm_unreachable("Unexpected Binary operation");
6996 }
6997 IC.addToWorklist(I: cast<Instruction>(Val: U));
6998 }
6999 }
7000
7001 return IC.replaceInstUsesWith(I, V: OverflowCheck);
7002}
7003
7004/// When performing a comparison against a constant, it is possible that not all
7005/// the bits in the LHS are demanded. This helper method computes the mask that
7006/// IS demanded.
7007static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) {
7008 const APInt *RHS;
7009 if (!match(V: I.getOperand(i_nocapture: 1), P: m_APInt(Res&: RHS)))
7010 return APInt::getAllOnes(numBits: BitWidth);
7011
7012 // If this is a normal comparison, it demands all bits. If it is a sign bit
7013 // comparison, it only demands the sign bit.
7014 bool UnusedBit;
7015 if (isSignBitCheck(Pred: I.getPredicate(), RHS: *RHS, TrueIfSigned&: UnusedBit))
7016 return APInt::getSignMask(BitWidth);
7017
7018 switch (I.getPredicate()) {
7019 // For a UGT comparison, we don't care about any bits that
7020 // correspond to the trailing ones of the comparand. The value of these
7021 // bits doesn't impact the outcome of the comparison, because any value
7022 // greater than the RHS must differ in a bit higher than these due to carry.
7023 case ICmpInst::ICMP_UGT:
7024 return APInt::getBitsSetFrom(numBits: BitWidth, loBit: RHS->countr_one());
7025
7026 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
7027 // Any value less than the RHS must differ in a higher bit because of carries.
7028 case ICmpInst::ICMP_ULT:
7029 return APInt::getBitsSetFrom(numBits: BitWidth, loBit: RHS->countr_zero());
7030
7031 default:
7032 return APInt::getAllOnes(numBits: BitWidth);
7033 }
7034}
7035
7036/// Check that one use is in the same block as the definition and all
7037/// other uses are in blocks dominated by a given block.
7038///
7039/// \param DI Definition
7040/// \param UI Use
7041/// \param DB Block that must dominate all uses of \p DI outside
7042/// the parent block
7043/// \return true when \p UI is the only use of \p DI in the parent block
7044/// and all other uses of \p DI are in blocks dominated by \p DB.
7045///
7046bool InstCombinerImpl::dominatesAllUses(const Instruction *DI,
7047 const Instruction *UI,
7048 const BasicBlock *DB) const {
7049 assert(DI && UI && "Instruction not defined\n");
7050 // Ignore incomplete definitions.
7051 if (!DI->getParent())
7052 return false;
7053 // DI and UI must be in the same block.
7054 if (DI->getParent() != UI->getParent())
7055 return false;
7056 // Protect from self-referencing blocks.
7057 if (DI->getParent() == DB)
7058 return false;
7059 for (const User *U : DI->users()) {
7060 auto *Usr = cast<Instruction>(Val: U);
7061 if (Usr != UI && !DT.dominates(A: DB, B: Usr->getParent()))
7062 return false;
7063 }
7064 return true;
7065}
7066
7067/// Return true when the instruction sequence within a block is select-cmp-br.
7068static bool isChainSelectCmpBranch(const SelectInst *SI) {
7069 const BasicBlock *BB = SI->getParent();
7070 if (!BB)
7071 return false;
7072 auto *BI = dyn_cast_or_null<CondBrInst>(Val: BB->getTerminator());
7073 if (!BI)
7074 return false;
7075 auto *IC = dyn_cast<ICmpInst>(Val: BI->getCondition());
7076 if (!IC || (IC->getOperand(i_nocapture: 0) != SI && IC->getOperand(i_nocapture: 1) != SI))
7077 return false;
7078 return true;
7079}
7080
7081/// True when a select result is replaced by one of its operands
7082/// in select-icmp sequence. This will eventually result in the elimination
7083/// of the select.
7084///
7085/// \param SI Select instruction
7086/// \param Icmp Compare instruction
7087/// \param SIOpd Operand that replaces the select
7088///
7089/// Notes:
7090/// - The replacement is global and requires dominator information
7091/// - The caller is responsible for the actual replacement
7092///
7093/// Example:
7094///
7095/// entry:
7096/// %4 = select i1 %3, %C* %0, %C* null
7097/// %5 = icmp eq %C* %4, null
7098/// br i1 %5, label %9, label %7
7099/// ...
7100/// ; <label>:7 ; preds = %entry
7101/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
7102/// ...
7103///
7104/// can be transformed to
7105///
7106/// %5 = icmp eq %C* %0, null
7107/// %6 = select i1 %3, i1 %5, i1 true
7108/// br i1 %6, label %9, label %7
7109/// ...
7110/// ; <label>:7 ; preds = %entry
7111/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
7112///
7113/// Similar when the first operand of the select is a constant or/and
7114/// the compare is for not equal rather than equal.
7115///
7116/// NOTE: The function is only called when the select and compare constants
7117/// are equal, the optimization can work only for EQ predicates. This is not a
7118/// major restriction since a NE compare should be 'normalized' to an equal
7119/// compare, which usually happens in the combiner and test case
7120/// select-cmp-br.ll checks for it.
7121bool InstCombinerImpl::replacedSelectWithOperand(SelectInst *SI,
7122 const ICmpInst *Icmp,
7123 const unsigned SIOpd) {
7124 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
7125 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
7126 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(Idx: 1);
7127 // The check for the single predecessor is not the best that can be
7128 // done. But it protects efficiently against cases like when SI's
7129 // home block has two successors, Succ and Succ1, and Succ1 predecessor
7130 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
7131 // replaced can be reached on either path. So the uniqueness check
7132 // guarantees that the path all uses of SI (outside SI's parent) are on
7133 // is disjoint from all other paths out of SI. But that information
7134 // is more expensive to compute, and the trade-off here is in favor
7135 // of compile-time. It should also be noticed that we check for a single
7136 // predecessor and not only uniqueness. This to handle the situation when
7137 // Succ and Succ1 points to the same basic block.
7138 if (Succ->getSinglePredecessor() && dominatesAllUses(DI: SI, UI: Icmp, DB: Succ)) {
7139 NumSel++;
7140 SI->replaceUsesOutsideBlock(V: SI->getOperand(i_nocapture: SIOpd), BB: SI->getParent());
7141 return true;
7142 }
7143 }
7144 return false;
7145}
7146
7147/// Try to fold the comparison based on range information we can get by checking
7148/// whether bits are known to be zero or one in the inputs.
7149Instruction *InstCombinerImpl::foldICmpUsingKnownBits(ICmpInst &I) {
7150 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
7151 Type *Ty = Op0->getType();
7152 ICmpInst::Predicate Pred = I.getPredicate();
7153
7154 // Get scalar or pointer size.
7155 unsigned BitWidth = Ty->isIntOrIntVectorTy()
7156 ? Ty->getScalarSizeInBits()
7157 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
7158
7159 if (!BitWidth)
7160 return nullptr;
7161
7162 KnownBits Op0Known(BitWidth);
7163 KnownBits Op1Known(BitWidth);
7164
7165 {
7166 // Don't use dominating conditions when folding icmp using known bits. This
7167 // may convert signed into unsigned predicates in ways that other passes
7168 // (especially IndVarSimplify) may not be able to reliably undo.
7169 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(I: &I);
7170 if (SimplifyDemandedBits(I: &I, Op: 0, DemandedMask: getDemandedBitsLHSMask(I, BitWidth),
7171 Known&: Op0Known, Q))
7172 return &I;
7173
7174 if (SimplifyDemandedBits(I: &I, Op: 1, DemandedMask: APInt::getAllOnes(numBits: BitWidth), Known&: Op1Known, Q))
7175 return &I;
7176 }
7177
7178 // If an unsigned samesign comparison is not poison, both operands have the
7179 // same sign bit. Propagate a known sign bit between the temporary KnownBits
7180 // values so the existing range folds can use that constraint.
7181 if (I.hasSameSign() && I.isUnsigned()) {
7182 auto PropagateSignBit = [](const KnownBits &From, KnownBits &To) {
7183 if (To.isNegative() || To.isNonNegative())
7184 return;
7185 if (From.isNegative())
7186 To.makeNegative();
7187 else if (From.isNonNegative())
7188 To.makeNonNegative();
7189 };
7190 PropagateSignBit(Op0Known, Op1Known);
7191 PropagateSignBit(Op1Known, Op0Known);
7192 }
7193
7194 if (!isa<Constant>(Val: Op0) && Op0Known.isConstant())
7195 return new ICmpInst(
7196 Pred, ConstantExpr::getIntegerValue(Ty, V: Op0Known.getConstant()), Op1);
7197 if (!isa<Constant>(Val: Op1) && Op1Known.isConstant())
7198 return new ICmpInst(
7199 Pred, Op0, ConstantExpr::getIntegerValue(Ty, V: Op1Known.getConstant()));
7200
7201 if (std::optional<bool> Res = ICmpInst::compare(LHS: Op0Known, RHS: Op1Known, Pred))
7202 return replaceInstUsesWith(I, V: ConstantInt::getBool(Ty: I.getType(), V: *Res));
7203
7204 // Given the known and unknown bits, compute a range that the LHS could be
7205 // in. Compute the Min, Max and RHS values based on the known bits. For the
7206 // EQ and NE we use unsigned values.
7207 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
7208 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
7209 if (I.isSigned()) {
7210 Op0Min = Op0Known.getSignedMinValue();
7211 Op0Max = Op0Known.getSignedMaxValue();
7212 Op1Min = Op1Known.getSignedMinValue();
7213 Op1Max = Op1Known.getSignedMaxValue();
7214 } else {
7215 Op0Min = Op0Known.getMinValue();
7216 Op0Max = Op0Known.getMaxValue();
7217 Op1Min = Op1Known.getMinValue();
7218 Op1Max = Op1Known.getMaxValue();
7219 }
7220
7221 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
7222 // min/max canonical compare with some other compare. That could lead to
7223 // conflict with select canonicalization and infinite looping.
7224 // FIXME: This constraint may go away if min/max intrinsics are canonical.
7225 auto isMinMaxCmp = [&](Instruction &Cmp) {
7226 if (!Cmp.hasOneUse())
7227 return false;
7228 Value *A, *B;
7229 SelectPatternFlavor SPF = matchSelectPattern(V: Cmp.user_back(), LHS&: A, RHS&: B).Flavor;
7230 if (!SelectPatternResult::isMinOrMax(SPF))
7231 return false;
7232 return match(V: Op0, P: m_MaxOrMin(Op0: m_Value(), Op1: m_Value())) ||
7233 match(V: Op1, P: m_MaxOrMin(Op0: m_Value(), Op1: m_Value()));
7234 };
7235 if (!isMinMaxCmp(I)) {
7236 switch (Pred) {
7237 default:
7238 break;
7239 case ICmpInst::ICMP_ULT: {
7240 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
7241 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7242 const APInt *CmpC;
7243 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7244 // A <u C -> A == C-1 if min(A)+1 == C
7245 if (*CmpC == Op0Min + 1)
7246 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7247 ConstantInt::get(Ty: Op1->getType(), V: *CmpC - 1));
7248 // X <u C --> X == 0, if the number of zero bits in the bottom of X
7249 // exceeds the log2 of C.
7250 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
7251 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7252 Constant::getNullValue(Ty: Op1->getType()));
7253 }
7254 break;
7255 }
7256 case ICmpInst::ICMP_UGT: {
7257 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
7258 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7259 const APInt *CmpC;
7260 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7261 // A >u C -> A == C+1 if max(a)-1 == C
7262 if (*CmpC == Op0Max - 1)
7263 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7264 ConstantInt::get(Ty: Op1->getType(), V: *CmpC + 1));
7265 // X >u C --> X != 0, if the number of zero bits in the bottom of X
7266 // exceeds the log2 of C.
7267 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
7268 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
7269 Constant::getNullValue(Ty: Op1->getType()));
7270 }
7271 break;
7272 }
7273 case ICmpInst::ICMP_SLT: {
7274 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
7275 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7276 const APInt *CmpC;
7277 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7278 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
7279 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7280 ConstantInt::get(Ty: Op1->getType(), V: *CmpC - 1));
7281 }
7282 break;
7283 }
7284 case ICmpInst::ICMP_SGT: {
7285 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
7286 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7287 const APInt *CmpC;
7288 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7289 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
7290 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7291 ConstantInt::get(Ty: Op1->getType(), V: *CmpC + 1));
7292 }
7293 break;
7294 }
7295 }
7296 }
7297
7298 // Based on the range information we know about the LHS, see if we can
7299 // simplify this comparison. For example, (x&4) < 8 is always true.
7300 switch (Pred) {
7301 default:
7302 break;
7303 case ICmpInst::ICMP_EQ:
7304 case ICmpInst::ICMP_NE: {
7305 // If all bits are known zero except for one, then we know at most one bit
7306 // is set. If the comparison is against zero, then this is a check to see if
7307 // *that* bit is set.
7308 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
7309 if (Op1Known.isZero()) {
7310 // If the LHS is an AND with the same constant, look through it.
7311 Value *LHS = nullptr;
7312 const APInt *LHSC;
7313 if (!match(V: Op0, P: m_And(L: m_Value(V&: LHS), R: m_APInt(Res&: LHSC))) ||
7314 *LHSC != Op0KnownZeroInverted)
7315 LHS = Op0;
7316
7317 Value *X;
7318 const APInt *C1;
7319 if (match(V: LHS, P: m_Shl(L: m_Power2(V&: C1), R: m_Value(V&: X)))) {
7320 Type *XTy = X->getType();
7321 unsigned Log2C1 = C1->countr_zero();
7322 APInt C2 = Op0KnownZeroInverted;
7323 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
7324 if (C2Pow2.isPowerOf2()) {
7325 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
7326 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
7327 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
7328 unsigned Log2C2 = C2Pow2.countr_zero();
7329 auto *CmpC = ConstantInt::get(Ty: XTy, V: Log2C2 - Log2C1);
7330 auto NewPred =
7331 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
7332 return new ICmpInst(NewPred, X, CmpC);
7333 }
7334 }
7335 }
7336
7337 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
7338 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
7339 (Op0Known & Op1Known) == Op0Known)
7340 return new ICmpInst(CmpInst::getInversePredicate(pred: Pred), Op0,
7341 ConstantInt::getNullValue(Ty: Op1->getType()));
7342 break;
7343 }
7344 case ICmpInst::ICMP_SGE:
7345 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
7346 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7347 break;
7348 case ICmpInst::ICMP_SLE:
7349 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
7350 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7351 break;
7352 case ICmpInst::ICMP_UGE:
7353 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
7354 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7355 break;
7356 case ICmpInst::ICMP_ULE:
7357 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
7358 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7359 break;
7360 }
7361
7362 // Turn a signed comparison into an unsigned one if both operands are known to
7363 // have the same sign. Set samesign if possible (except for equality
7364 // predicates).
7365 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
7366 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
7367 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
7368 I.setPredicate(I.getUnsignedPredicate());
7369 I.setSameSign();
7370 return &I;
7371 }
7372
7373 return nullptr;
7374}
7375
7376/// If one operand of an icmp is effectively a bool (value range of {0,1}),
7377/// then try to reduce patterns based on that limit.
7378Instruction *InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst &I) {
7379 Value *X, *Y;
7380 CmpPredicate Pred;
7381
7382 // X must be 0 and bool must be true for "ULT":
7383 // X <u (zext i1 Y) --> (X == 0) & Y
7384 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))))) &&
7385 Y->getType()->isIntOrIntVectorTy(BitWidth: 1) && Pred == ICmpInst::ICMP_ULT)
7386 return BinaryOperator::CreateAnd(V1: Builder.CreateIsNull(Arg: X), V2: Y);
7387
7388 // X must be 0 or bool must be true for "ULE":
7389 // X <=u (sext i1 Y) --> (X == 0) | Y
7390 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))))) &&
7391 Y->getType()->isIntOrIntVectorTy(BitWidth: 1) && Pred == ICmpInst::ICMP_ULE)
7392 return BinaryOperator::CreateOr(V1: Builder.CreateIsNull(Arg: X), V2: Y);
7393
7394 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
7395 CmpPredicate Pred1, Pred2;
7396 const APInt *C;
7397 Instruction *ExtI;
7398 if (match(V: &I, P: m_c_ICmp(Pred&: Pred1, L: m_Value(V&: X),
7399 R: m_CombineAnd(Ps: m_Instruction(I&: ExtI),
7400 Ps: m_ZExtOrSExt(Op: m_ICmp(Pred&: Pred2, L: m_Deferred(V: X),
7401 R: m_APInt(Res&: C)))))) &&
7402 ICmpInst::isEquality(P: Pred1) && ICmpInst::isEquality(P: Pred2)) {
7403 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
7404 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(i: 0)->hasOneUse();
7405 auto CreateRangeCheck = [&] {
7406 Value *CmpV1 =
7407 Builder.CreateICmp(P: Pred1, LHS: X, RHS: Constant::getNullValue(Ty: X->getType()));
7408 Value *CmpV2 = Builder.CreateICmp(
7409 P: Pred1, LHS: X, RHS: ConstantInt::getSigned(Ty: X->getType(), V: IsSExt ? -1 : 1));
7410 return BinaryOperator::Create(
7411 Op: Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
7412 S1: CmpV1, S2: CmpV2);
7413 };
7414 if (C->isZero()) {
7415 if (Pred2 == ICmpInst::ICMP_EQ) {
7416 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
7417 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
7418 return replaceInstUsesWith(
7419 I, V: ConstantInt::getBool(Ty: I.getType(), V: Pred1 == ICmpInst::ICMP_NE));
7420 } else if (!IsSExt || HasOneUse) {
7421 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
7422 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
7423 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
7424 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X != -1
7425 return CreateRangeCheck();
7426 }
7427 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
7428 if (Pred2 == ICmpInst::ICMP_NE) {
7429 // icmp eq X, (zext (icmp ne X, 1)) --> false
7430 // icmp ne X, (zext (icmp ne X, 1)) --> true
7431 // icmp eq X, (sext (icmp ne X, -1)) --> false
7432 // icmp ne X, (sext (icmp ne X, -1)) --> true
7433 return replaceInstUsesWith(
7434 I, V: ConstantInt::getBool(Ty: I.getType(), V: Pred1 == ICmpInst::ICMP_NE));
7435 } else if (!IsSExt || HasOneUse) {
7436 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
7437 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
7438 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
7439 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
7440 return CreateRangeCheck();
7441 }
7442 } else {
7443 // when C != 0 && C != 1:
7444 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
7445 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
7446 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
7447 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
7448 // when C != 0 && C != -1:
7449 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
7450 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
7451 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
7452 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
7453 return ICmpInst::Create(
7454 Op: Instruction::ICmp, Pred: Pred1, S1: X,
7455 S2: ConstantInt::getSigned(Ty: X->getType(), V: Pred2 == ICmpInst::ICMP_NE
7456 ? (IsSExt ? -1 : 1)
7457 : 0));
7458 }
7459 }
7460
7461 return nullptr;
7462}
7463
7464/// If we have an icmp le or icmp ge instruction with a constant operand, turn
7465/// it into the appropriate icmp lt or icmp gt instruction. This transform
7466/// allows them to be folded in visitICmpInst.
7467static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
7468 CmpPredicate Pred = I.getCmpPredicate();
7469 if (ICmpInst::isEquality(P: Pred) || !ICmpInst::isIntPredicate(P: Pred) ||
7470 InstCombiner::isCanonicalPredicate(Pred))
7471 return nullptr;
7472
7473 Value *Op0 = I.getOperand(i_nocapture: 0);
7474 Value *Op1 = I.getOperand(i_nocapture: 1);
7475 auto *Op1C = dyn_cast<Constant>(Val: Op1);
7476 if (!Op1C)
7477 return nullptr;
7478
7479 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, C: Op1C);
7480 if (!FlippedStrictness)
7481 return nullptr;
7482
7483 auto *NewCmp =
7484 new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7485 NewCmp->setSameSign(FlippedStrictness->first.hasSameSign());
7486 return NewCmp;
7487}
7488
7489/// If we have a comparison with a non-canonical predicate, if we can update
7490/// all the users, invert the predicate and adjust all the users.
7491CmpInst *InstCombinerImpl::canonicalizeICmpPredicate(CmpInst &I) {
7492 // Is the predicate already canonical?
7493 CmpInst::Predicate Pred = I.getPredicate();
7494 if (InstCombiner::isCanonicalPredicate(Pred))
7495 return nullptr;
7496
7497 // Can all users be adjusted to predicate inversion?
7498 if (!InstCombiner::canFreelyInvertAllUsersOf(V: &I, /*IgnoredUser=*/nullptr))
7499 return nullptr;
7500
7501 // Ok, we can canonicalize comparison!
7502 // Let's first invert the comparison's predicate.
7503 I.setPredicate(CmpInst::getInversePredicate(pred: Pred));
7504 I.setName(I.getName() + ".not");
7505
7506 // And, adapt users.
7507 freelyInvertAllUsersOf(V: &I);
7508
7509 return &I;
7510}
7511
7512/// Integer compare with boolean values can always be turned into bitwise ops.
7513static Instruction *canonicalizeICmpBool(ICmpInst &I,
7514 InstCombiner::BuilderTy &Builder) {
7515 Value *A = I.getOperand(i_nocapture: 0), *B = I.getOperand(i_nocapture: 1);
7516 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
7517
7518 // A boolean compared to true/false can be simplified to Op0/true/false in
7519 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
7520 // Cases not handled by InstSimplify are always 'not' of Op0.
7521 if (match(V: B, P: m_Zero())) {
7522 switch (I.getPredicate()) {
7523 case CmpInst::ICMP_EQ: // A == 0 -> !A
7524 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
7525 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7526 return BinaryOperator::CreateNot(Op: A);
7527 default:
7528 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7529 }
7530 } else if (match(V: B, P: m_One())) {
7531 switch (I.getPredicate()) {
7532 case CmpInst::ICMP_NE: // A != 1 -> !A
7533 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7534 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7535 return BinaryOperator::CreateNot(Op: A);
7536 default:
7537 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7538 }
7539 }
7540
7541 switch (I.getPredicate()) {
7542 default:
7543 llvm_unreachable("Invalid icmp instruction!");
7544 case ICmpInst::ICMP_EQ:
7545 // icmp eq i1 A, B -> ~(A ^ B)
7546 return BinaryOperator::CreateNot(Op: Builder.CreateXor(LHS: A, RHS: B));
7547
7548 case ICmpInst::ICMP_NE:
7549 // icmp ne i1 A, B -> A ^ B
7550 return BinaryOperator::CreateXor(V1: A, V2: B);
7551
7552 case ICmpInst::ICMP_UGT:
7553 // icmp ugt -> icmp ult
7554 std::swap(a&: A, b&: B);
7555 [[fallthrough]];
7556 case ICmpInst::ICMP_ULT:
7557 // icmp ult i1 A, B -> ~A & B
7558 return BinaryOperator::CreateAnd(V1: Builder.CreateNot(V: A), V2: B);
7559
7560 case ICmpInst::ICMP_SGT:
7561 // icmp sgt -> icmp slt
7562 std::swap(a&: A, b&: B);
7563 [[fallthrough]];
7564 case ICmpInst::ICMP_SLT:
7565 // icmp slt i1 A, B -> A & ~B
7566 return BinaryOperator::CreateAnd(V1: Builder.CreateNot(V: B), V2: A);
7567
7568 case ICmpInst::ICMP_UGE:
7569 // icmp uge -> icmp ule
7570 std::swap(a&: A, b&: B);
7571 [[fallthrough]];
7572 case ICmpInst::ICMP_ULE:
7573 // icmp ule i1 A, B -> ~A | B
7574 return BinaryOperator::CreateOr(V1: Builder.CreateNot(V: A), V2: B);
7575
7576 case ICmpInst::ICMP_SGE:
7577 // icmp sge -> icmp sle
7578 std::swap(a&: A, b&: B);
7579 [[fallthrough]];
7580 case ICmpInst::ICMP_SLE:
7581 // icmp sle i1 A, B -> A | ~B
7582 return BinaryOperator::CreateOr(V1: Builder.CreateNot(V: B), V2: A);
7583 }
7584}
7585
7586// Transform pattern like:
7587// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7588// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7589// Into:
7590// (X l>> Y) != 0
7591// (X l>> Y) == 0
7592static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp,
7593 InstCombiner::BuilderTy &Builder) {
7594 CmpPredicate Pred, NewPred;
7595 Value *X, *Y;
7596 if (match(V: &Cmp,
7597 P: m_c_ICmp(Pred, L: m_OneUse(SubPattern: m_Shl(L: m_One(), R: m_Value(V&: Y))), R: m_Value(V&: X)))) {
7598 switch (Pred) {
7599 case ICmpInst::ICMP_ULE:
7600 NewPred = ICmpInst::ICMP_NE;
7601 break;
7602 case ICmpInst::ICMP_UGT:
7603 NewPred = ICmpInst::ICMP_EQ;
7604 break;
7605 default:
7606 return nullptr;
7607 }
7608 } else if (match(V: &Cmp, P: m_c_ICmp(Pred,
7609 L: m_OneUse(SubPattern: m_CombineOr(
7610 Ps: m_Not(V: m_Shl(L: m_AllOnes(), R: m_Value(V&: Y))),
7611 Ps: m_Add(L: m_Shl(L: m_One(), R: m_Value(V&: Y)),
7612 R: m_AllOnes()))),
7613 R: m_Value(V&: X)))) {
7614 // The variant with 'add' is not canonical, (the variant with 'not' is)
7615 // we only get it because it has extra uses, and can't be canonicalized,
7616
7617 switch (Pred) {
7618 case ICmpInst::ICMP_ULT:
7619 NewPred = ICmpInst::ICMP_NE;
7620 break;
7621 case ICmpInst::ICMP_UGE:
7622 NewPred = ICmpInst::ICMP_EQ;
7623 break;
7624 default:
7625 return nullptr;
7626 }
7627 } else
7628 return nullptr;
7629
7630 Value *NewX = Builder.CreateLShr(LHS: X, RHS: Y, Name: X->getName() + ".highbits");
7631 Constant *Zero = Constant::getNullValue(Ty: NewX->getType());
7632 return CmpInst::Create(Op: Instruction::ICmp, Pred: NewPred, S1: NewX, S2: Zero);
7633}
7634
7635static Instruction *foldVectorCmp(CmpInst &Cmp,
7636 InstCombiner::BuilderTy &Builder) {
7637 const CmpInst::Predicate Pred = Cmp.getPredicate();
7638 Value *LHS = Cmp.getOperand(i_nocapture: 0), *RHS = Cmp.getOperand(i_nocapture: 1);
7639 Value *V1, *V2;
7640
7641 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7642 Value *V = Builder.CreateCmp(Pred, LHS: X, RHS: Y, Name: Cmp.getName());
7643 if (auto *I = dyn_cast<Instruction>(Val: V))
7644 I->copyIRFlags(V: &Cmp);
7645 Module *M = Cmp.getModule();
7646 Function *F = Intrinsic::getOrInsertDeclaration(
7647 M, id: Intrinsic::vector_reverse, OverloadTys: V->getType());
7648 return CallInst::Create(Func: F, Args: V);
7649 };
7650
7651 if (match(V: LHS, P: m_VecReverse(Op0: m_Value(V&: V1)))) {
7652 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7653 if (match(V: RHS, P: m_VecReverse(Op0: m_Value(V&: V2))) &&
7654 (LHS->hasOneUse() || RHS->hasOneUse()))
7655 return createCmpReverse(Pred, V1, V2);
7656
7657 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7658 if (LHS->hasOneUse() && isSplatValue(V: RHS))
7659 return createCmpReverse(Pred, V1, RHS);
7660 }
7661 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7662 else if (isSplatValue(V: LHS) && match(V: RHS, P: m_OneUse(SubPattern: m_VecReverse(Op0: m_Value(V&: V2)))))
7663 return createCmpReverse(Pred, LHS, V2);
7664
7665 ArrayRef<int> M;
7666 if (!match(V: LHS, P: m_Shuffle(v1: m_Value(V&: V1), v2: m_Undef(), mask: m_Mask(M))))
7667 return nullptr;
7668
7669 // If both arguments of the cmp are shuffles that use the same mask and
7670 // shuffle within a single vector, move the shuffle after the cmp:
7671 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7672 Type *V1Ty = V1->getType();
7673 if (match(V: RHS, P: m_Shuffle(v1: m_Value(V&: V2), v2: m_Undef(), mask: m_SpecificMask(M))) &&
7674 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7675 Value *NewCmp = Builder.CreateCmp(Pred, LHS: V1, RHS: V2);
7676 return new ShuffleVectorInst(NewCmp, M);
7677 }
7678
7679 // Try to canonicalize compare with splatted operand and splat constant.
7680 // TODO: We could generalize this for more than splats. See/use the code in
7681 // InstCombiner::foldVectorBinop().
7682 Constant *C;
7683 if (!LHS->hasOneUse() || !match(V: RHS, P: m_Constant(C)))
7684 return nullptr;
7685
7686 // Length-changing splats are ok, so adjust the constants as needed:
7687 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7688 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7689 int MaskSplatIndex;
7690 if (ScalarC && match(Mask: M, P: m_SplatOrPoisonMask(MaskSplatIndex))) {
7691 // We allow poison in matching, but this transform removes it for safety.
7692 // Demanded elements analysis should be able to recover some/all of that.
7693 C = ConstantVector::getSplat(EC: cast<VectorType>(Val: V1Ty)->getElementCount(),
7694 Elt: ScalarC);
7695 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7696 Value *NewCmp = Builder.CreateCmp(Pred, LHS: V1, RHS: C);
7697 return new ShuffleVectorInst(NewCmp, NewM);
7698 }
7699
7700 return nullptr;
7701}
7702
7703// extract(uadd.with.overflow(A, B), 0) ult A
7704// -> extract(uadd.with.overflow(A, B), 1)
7705static Instruction *foldICmpOfUAddOv(ICmpInst &I) {
7706 CmpInst::Predicate Pred = I.getPredicate();
7707 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
7708
7709 Value *UAddOv;
7710 Value *A, *B;
7711 auto UAddOvResultPat = m_ExtractValue<0>(
7712 V: m_Intrinsic<Intrinsic::uadd_with_overflow>(Ops: m_Value(V&: A), Ops: m_Value(V&: B)));
7713 if (match(V: Op0, P: UAddOvResultPat) &&
7714 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7715 (Pred == ICmpInst::ICMP_EQ && match(V: Op1, P: m_ZeroInt()) &&
7716 (match(V: A, P: m_One()) || match(V: B, P: m_One()))) ||
7717 (Pred == ICmpInst::ICMP_NE && match(V: Op1, P: m_AllOnes()) &&
7718 (match(V: A, P: m_AllOnes()) || match(V: B, P: m_AllOnes())))))
7719 // extract(uadd.with.overflow(A, B), 0) < A
7720 // extract(uadd.with.overflow(A, 1), 0) == 0
7721 // extract(uadd.with.overflow(A, -1), 0) != -1
7722 UAddOv = cast<ExtractValueInst>(Val: Op0)->getAggregateOperand();
7723 else if (match(V: Op1, P: UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7724 (Op0 == A || Op0 == B))
7725 // A > extract(uadd.with.overflow(A, B), 0)
7726 UAddOv = cast<ExtractValueInst>(Val: Op1)->getAggregateOperand();
7727 else
7728 return nullptr;
7729
7730 return ExtractValueInst::Create(Agg: UAddOv, Idxs: 1);
7731}
7732
7733static Instruction *foldICmpInvariantGroup(ICmpInst &I) {
7734 if (!I.getOperand(i_nocapture: 0)->getType()->isPointerTy() ||
7735 NullPointerIsDefined(
7736 F: I.getParent()->getParent(),
7737 AS: I.getOperand(i_nocapture: 0)->getType()->getPointerAddressSpace())) {
7738 return nullptr;
7739 }
7740 Value *Ptr;
7741 if (match(V: I.getOperand(i_nocapture: 0),
7742 P: m_Intrinsic<Intrinsic::launder_invariant_group>(Ops: m_Value(V&: Ptr))) &&
7743 match(V: I.getOperand(i_nocapture: 1), P: m_Zero())) {
7744 return ICmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(), S1: Ptr,
7745 S2: I.getOperand(i_nocapture: 1));
7746 }
7747 return nullptr;
7748}
7749
7750static Instruction *foldICmpOfVectorReduce(ICmpInst &I, const DataLayout &DL,
7751 IRBuilderBase &Builder) {
7752 if (!ICmpInst::isEquality(P: I.getPredicate()))
7753 return nullptr;
7754
7755 // The caller puts constants after non-constants.
7756 Value *Op = I.getOperand(i_nocapture: 0);
7757 Value *Const = I.getOperand(i_nocapture: 1);
7758
7759 // For Cond an equality condition, fold
7760 //
7761 // icmp (eq|ne) (vreduce_(or|and) Op), (Zero|AllOnes) ->
7762 // icmp (eq|ne) Op, (Zero|AllOnes)
7763 //
7764 // with a bitcast.
7765 Value *Vec;
7766 if ((match(V: Const, P: m_ZeroInt()) &&
7767 match(V: Op, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_or>(
7768 Ops: m_Value(V&: Vec))))) ||
7769 (match(V: Const, P: m_AllOnes()) &&
7770 match(V: Op, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_and>(
7771 Ops: m_Value(V&: Vec)))))) {
7772 auto *VecTy = dyn_cast<FixedVectorType>(Val: Vec->getType());
7773 if (!VecTy)
7774 return nullptr;
7775 Type *VecEltTy = VecTy->getElementType();
7776 unsigned ScalarBW =
7777 DL.getTypeSizeInBits(Ty: VecEltTy) * VecTy->getNumElements();
7778 if (!DL.fitsInLegalInteger(Width: ScalarBW))
7779 return nullptr;
7780 Type *ScalarTy = IntegerType::get(C&: I.getContext(), NumBits: ScalarBW);
7781 Value *NewConst = match(V: Const, P: m_ZeroInt())
7782 ? ConstantInt::get(Ty: ScalarTy, V: 0)
7783 : ConstantInt::getAllOnesValue(Ty: ScalarTy);
7784 return CmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(),
7785 S1: Builder.CreateBitCast(V: Vec, DestTy: ScalarTy), S2: NewConst);
7786 }
7787 return nullptr;
7788}
7789
7790/// This function folds patterns produced by lowering of reduce idioms, such as
7791/// llvm.vector.reduce.and which are lowered into instruction chains. This code
7792/// attempts to generate fewer number of scalar comparisons instead of vector
7793/// comparisons when possible.
7794static Instruction *foldReductionIdiom(ICmpInst &I,
7795 InstCombiner::BuilderTy &Builder,
7796 const DataLayout &DL) {
7797 if (I.getType()->isVectorTy())
7798 return nullptr;
7799 CmpPredicate OuterPred, InnerPred;
7800 Value *LHS, *RHS;
7801
7802 // Match lowering of @llvm.vector.reduce.and. Turn
7803 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7804 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7805 /// %res = icmp <pred> i8 %scalar_ne, 0
7806 ///
7807 /// into
7808 ///
7809 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7810 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7811 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7812 ///
7813 /// for <pred> in {ne, eq}.
7814 if (!match(V: &I, P: m_ICmp(Pred&: OuterPred,
7815 L: m_OneUse(SubPattern: m_BitCast(Op: m_OneUse(
7816 SubPattern: m_ICmp(Pred&: InnerPred, L: m_Value(V&: LHS), R: m_Value(V&: RHS))))),
7817 R: m_Zero())))
7818 return nullptr;
7819 auto *LHSTy = dyn_cast<FixedVectorType>(Val: LHS->getType());
7820 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7821 return nullptr;
7822 unsigned NumBits =
7823 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7824 // TODO: Relax this to "not wider than max legal integer type"?
7825 if (!DL.isLegalInteger(Width: NumBits))
7826 return nullptr;
7827
7828 if (ICmpInst::isEquality(P: OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7829 auto *ScalarTy = Builder.getIntNTy(N: NumBits);
7830 LHS = Builder.CreateBitCast(V: LHS, DestTy: ScalarTy, Name: LHS->getName() + ".scalar");
7831 RHS = Builder.CreateBitCast(V: RHS, DestTy: ScalarTy, Name: RHS->getName() + ".scalar");
7832 return ICmpInst::Create(Op: Instruction::ICmp, Pred: OuterPred, S1: LHS, S2: RHS,
7833 Name: I.getName());
7834 }
7835
7836 return nullptr;
7837}
7838
7839// This helper will be called with icmp operands in both orders.
7840Instruction *InstCombinerImpl::foldICmpCommutative(CmpPredicate Pred,
7841 Value *Op0, Value *Op1,
7842 ICmpInst &CtxI) {
7843 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7844 if (auto *GEP = dyn_cast<GEPOperator>(Val: Op0))
7845 if (Instruction *NI = foldGEPICmp(GEPLHS: GEP, RHS: Op1, Cond: Pred, I&: CtxI))
7846 return NI;
7847
7848 if (auto *SI = dyn_cast<SelectInst>(Val: Op0))
7849 if (Instruction *NI = foldSelectICmp(Pred, SI, RHS: Op1, I: CtxI))
7850 return NI;
7851
7852 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Val: Op0)) {
7853 if (Instruction *Res = foldICmpWithMinMax(I&: CtxI, MinMax, Z: Op1, Pred))
7854 return Res;
7855
7856 if (Instruction *Res = foldICmpWithClamp(I&: CtxI, X: Op1, Min: MinMax))
7857 return Res;
7858 }
7859
7860 {
7861 Value *X;
7862 const APInt *C;
7863 // icmp X+Cst, X
7864 if (match(V: Op0, P: m_Add(L: m_Value(V&: X), R: m_APInt(Res&: C))) && Op1 == X)
7865 return foldICmpAddOpConst(X, C: *C, Pred);
7866 }
7867
7868 // abs(X) >= X --> true
7869 // abs(X) u<= X --> true
7870 // abs(X) < X --> false
7871 // abs(X) u> X --> false
7872 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7873 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7874 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7875 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7876 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7877 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7878 {
7879 Value *X;
7880 Constant *C;
7881 if (match(V: Op0, P: m_Intrinsic<Intrinsic::abs>(Ops: m_Value(V&: X), Ops: m_Constant(C))) &&
7882 match(V: Op1, P: m_Specific(V: X))) {
7883 Value *NullValue = Constant::getNullValue(Ty: X->getType());
7884 Value *AllOnesValue = Constant::getAllOnesValue(Ty: X->getType());
7885 const APInt SMin =
7886 APInt::getSignedMinValue(numBits: X->getType()->getScalarSizeInBits());
7887 bool IsIntMinPosion = C->isAllOnesValue();
7888 switch (Pred) {
7889 case CmpInst::ICMP_ULE:
7890 case CmpInst::ICMP_SGE:
7891 return replaceInstUsesWith(I&: CtxI, V: ConstantInt::getTrue(Ty: CtxI.getType()));
7892 case CmpInst::ICMP_UGT:
7893 case CmpInst::ICMP_SLT:
7894 return replaceInstUsesWith(I&: CtxI, V: ConstantInt::getFalse(Ty: CtxI.getType()));
7895 case CmpInst::ICMP_UGE:
7896 case CmpInst::ICMP_SLE:
7897 case CmpInst::ICMP_EQ: {
7898 return replaceInstUsesWith(
7899 I&: CtxI, V: IsIntMinPosion
7900 ? Builder.CreateICmpSGT(LHS: X, RHS: AllOnesValue)
7901 : Builder.CreateICmpULT(
7902 LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: SMin + 1)));
7903 }
7904 case CmpInst::ICMP_ULT:
7905 case CmpInst::ICMP_SGT:
7906 case CmpInst::ICMP_NE: {
7907 return replaceInstUsesWith(
7908 I&: CtxI, V: IsIntMinPosion
7909 ? Builder.CreateICmpSLT(LHS: X, RHS: NullValue)
7910 : Builder.CreateICmpUGT(
7911 LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: SMin)));
7912 }
7913 default:
7914 llvm_unreachable("Invalid predicate!");
7915 }
7916 }
7917 }
7918
7919 {
7920 // For a nonzero constant C:
7921 // usub.sat(X, C) == X --> X == 0
7922 // usub.sat(X, C) != X --> X != 0
7923 // usub.sat(X, C) < X --> X != 0
7924 if (match(V: Op0, P: m_Intrinsic<Intrinsic::usub_sat>(Ops: m_Specific(V: Op1),
7925 Ops: m_NonZeroInt())) &&
7926 (CmpInst::isEquality(pred: Pred) || Pred == ICmpInst::ICMP_ULT)) {
7927 ICmpInst::Predicate NewPred =
7928 CmpInst::isEquality(pred: Pred) ? Pred.dropSameSign() : ICmpInst::ICMP_NE;
7929 return new ICmpInst(NewPred, Op1, Constant::getNullValue(Ty: Op1->getType()));
7930 }
7931 }
7932
7933 const SimplifyQuery Q = SQ.getWithInstruction(I: &CtxI);
7934 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, IC&: *this))
7935 return replaceInstUsesWith(I&: CtxI, V);
7936
7937 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
7938 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(RHS: 1); };
7939 {
7940 if (match(V: Op0, P: m_UDiv(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckUGT1)))) {
7941 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7942 Constant::getNullValue(Ty: Op1->getType()));
7943 }
7944
7945 if (!ICmpInst::isUnsigned(Pred) &&
7946 match(V: Op0, P: m_SDiv(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckUGT1)))) {
7947 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7948 Constant::getNullValue(Ty: Op1->getType()));
7949 }
7950 }
7951
7952 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
7953 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
7954 {
7955 if (match(V: Op0, P: m_LShr(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckNE0)))) {
7956 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7957 Constant::getNullValue(Ty: Op1->getType()));
7958 }
7959
7960 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
7961 match(V: Op0, P: m_AShr(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckNE0)))) {
7962 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7963 Constant::getNullValue(Ty: Op1->getType()));
7964 }
7965 }
7966
7967 // icmp (shl nsw/nuw X, L), (add nsw/nuw (shl nsw/nuw Y, L), K)
7968 // -> icmp X, (add nsw/nuw Y, K >> L)
7969 // We use AShr for nsw and LShr for nuw to safely peel off the shift.
7970 Value *X;
7971 uint64_t ShAmt;
7972 if (match(V: Op0, P: m_NUWShl(L: m_Value(V&: X), R: m_ConstantInt(V&: ShAmt))) &&
7973 !CtxI.isSigned()) {
7974 if (ShAmt >= X->getType()->getScalarSizeInBits())
7975 return nullptr;
7976 if (canEvaluateShifted(V: Op1, NumBits: ShAmt, /*IsLeftShift=*/false,
7977 Semantics: ShiftSemantics::Unsigned, CtxI: &CtxI)) {
7978 Value *NewOp1 = getShiftedValue(V: Op1, NumBits: ShAmt, /*IsLeftShift=*/false,
7979 Semantics: ShiftSemantics::Unsigned);
7980 return new ICmpInst(Pred, X, NewOp1);
7981 }
7982 }
7983
7984 if (match(V: Op0, P: m_NSWShl(L: m_Value(V&: X), R: m_ConstantInt(V&: ShAmt))) &&
7985 !CtxI.isUnsigned()) {
7986 if (ShAmt >= X->getType()->getScalarSizeInBits())
7987 return nullptr;
7988 if (canEvaluateShifted(V: Op1, NumBits: ShAmt, /*IsLeftShift=*/false,
7989 Semantics: ShiftSemantics::Signed, CtxI: &CtxI)) {
7990 Value *NewOp1 = getShiftedValue(V: Op1, NumBits: ShAmt, /*IsLeftShift=*/false,
7991 Semantics: ShiftSemantics::Signed);
7992 return new ICmpInst(Pred, X, NewOp1);
7993 }
7994 }
7995 return nullptr;
7996}
7997
7998Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {
7999 bool Changed = false;
8000 const SimplifyQuery Q = SQ.getWithInstruction(I: &I);
8001 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
8002 unsigned Op0Cplxity = getComplexity(V: Op0);
8003 unsigned Op1Cplxity = getComplexity(V: Op1);
8004
8005 /// Orders the operands of the compare so that they are listed from most
8006 /// complex to least complex. This puts constants before unary operators,
8007 /// before binary operators.
8008 if (Op0Cplxity < Op1Cplxity) {
8009 I.swapOperands();
8010 std::swap(a&: Op0, b&: Op1);
8011 Changed = true;
8012 }
8013
8014 if (Value *V = simplifyICmpInst(Pred: I.getCmpPredicate(), LHS: Op0, RHS: Op1, Q))
8015 return replaceInstUsesWith(I, V);
8016
8017 // Comparing -val or val with non-zero is the same as just comparing val
8018 // ie, abs(val) != 0 -> val != 0
8019 if (I.getPredicate() == ICmpInst::ICMP_NE && match(V: Op1, P: m_Zero())) {
8020 Value *Cond, *SelectTrue, *SelectFalse;
8021 if (match(V: Op0, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: SelectTrue),
8022 R: m_Value(V&: SelectFalse)))) {
8023 if (Value *V = dyn_castNegVal(V: SelectTrue)) {
8024 if (V == SelectFalse)
8025 return CmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(), S1: V, S2: Op1);
8026 } else if (Value *V = dyn_castNegVal(V: SelectFalse)) {
8027 if (V == SelectTrue)
8028 return CmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(), S1: V, S2: Op1);
8029 }
8030 }
8031 }
8032
8033 if (Instruction *Res = foldICmpTruncWithTruncOrExt(Cmp&: I, Q))
8034 return Res;
8035
8036 if (Op0->getType()->isIntOrIntVectorTy(BitWidth: 1))
8037 if (Instruction *Res = canonicalizeICmpBool(I, Builder))
8038 return Res;
8039
8040 if (Instruction *Res = canonicalizeCmpWithConstant(I))
8041 return Res;
8042
8043 if (Instruction *Res = canonicalizeICmpPredicate(I))
8044 return Res;
8045
8046 if (Instruction *Res = foldICmpWithConstant(Cmp&: I))
8047 return Res;
8048
8049 if (Instruction *Res = foldICmpWithDominatingICmp(Cmp&: I))
8050 return Res;
8051
8052 if (Instruction *Res = foldICmpUsingBoolRange(I))
8053 return Res;
8054
8055 if (Instruction *Res = foldICmpUsingKnownBits(I))
8056 return Res;
8057
8058 if (Instruction *Res = foldIsMultipleOfAPowerOfTwo(Cmp&: I))
8059 return Res;
8060
8061 // Test if the ICmpInst instruction is used exclusively by a select as
8062 // part of a minimum or maximum operation. If so, refrain from doing
8063 // any other folding. This helps out other analyses which understand
8064 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
8065 // and CodeGen. And in this case, at least one of the comparison
8066 // operands has at least one user besides the compare (the select),
8067 // which would often largely negate the benefit of folding anyway.
8068 //
8069 // Do the same for the other patterns recognized by matchSelectPattern.
8070 if (I.hasOneUse())
8071 if (SelectInst *SI = dyn_cast<SelectInst>(Val: I.user_back())) {
8072 Value *A, *B;
8073 SelectPatternResult SPR = matchSelectPattern(V: SI, LHS&: A, RHS&: B);
8074 if (SPR.Flavor != SPF_UNKNOWN)
8075 return nullptr;
8076 }
8077
8078 // Do this after checking for min/max to prevent infinite looping.
8079 if (Instruction *Res = foldICmpWithZero(Cmp&: I))
8080 return Res;
8081
8082 Value *X;
8083 const APInt *C;
8084 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
8085 match(V: Op0, P: m_UMax(Op0: m_Value(V&: X), Op1: m_APInt(Res&: C))) &&
8086 match(V: Op1, P: m_Not(V: m_Specific(V: X)))) {
8087 if (C->isNonNegative())
8088 return new ICmpInst(ICmpInst::ICMP_SLT, X,
8089 Constant::getNullValue(Ty: X->getType()));
8090 return new ICmpInst(ICmpInst::ICMP_UGT, X,
8091 ConstantInt::get(Ty: X->getType(), V: ~*C));
8092 }
8093
8094 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
8095 match(V: Op0, P: m_UMax(Op0: m_Value(V&: X), Op1: m_APInt(Res&: C))) &&
8096 match(V: Op1, P: m_Not(V: m_Specific(V: X)))) {
8097 if (C->isNonNegative())
8098 return new ICmpInst(ICmpInst::ICMP_SGT, X,
8099 Constant::getAllOnesValue(Ty: X->getType()));
8100 return new ICmpInst(ICmpInst::ICMP_ULT, X,
8101 ConstantInt::get(Ty: X->getType(), V: ~*C));
8102 }
8103
8104 // FIXME: We only do this after checking for min/max to prevent infinite
8105 // looping caused by a reverse canonicalization of these patterns for min/max.
8106 // FIXME: The organization of folds is a mess. These would naturally go into
8107 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
8108 // down here after the min/max restriction.
8109 ICmpInst::Predicate Pred = I.getPredicate();
8110 if (match(V: Op1, P: m_APInt(Res&: C))) {
8111 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
8112 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
8113 Constant *Zero = Constant::getNullValue(Ty: Op0->getType());
8114 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
8115 }
8116
8117 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
8118 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
8119 Constant *AllOnes = Constant::getAllOnesValue(Ty: Op0->getType());
8120 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
8121 }
8122 }
8123
8124 // The folds in here may rely on wrapping flags and special constants, so
8125 // they can break up min/max idioms in some cases but not seemingly similar
8126 // patterns.
8127 // FIXME: It may be possible to enhance select folding to make this
8128 // unnecessary. It may also be moot if we canonicalize to min/max
8129 // intrinsics.
8130 if (Instruction *Res = foldICmpBinOp(I, SQ: Q))
8131 return Res;
8132
8133 if (Instruction *Res = foldICmpInstWithConstant(Cmp&: I))
8134 return Res;
8135
8136 // Try to match comparison as a sign bit test. Intentionally do this after
8137 // foldICmpInstWithConstant() to potentially let other folds to happen first.
8138 if (Instruction *New = foldSignBitTest(I))
8139 return New;
8140
8141 if (auto *PN = dyn_cast<PHINode>(Val: Op0))
8142 if (Instruction *NV = foldOpIntoPhi(I, PN))
8143 return NV;
8144 if (auto *PN = dyn_cast<PHINode>(Val: Op1))
8145 if (Instruction *NV = foldOpIntoPhi(I, PN))
8146 return NV;
8147
8148 if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
8149 return Res;
8150
8151 if (Instruction *Res = foldICmpCommutative(Pred: I.getCmpPredicate(), Op0, Op1, CtxI&: I))
8152 return Res;
8153 if (Instruction *Res =
8154 foldICmpCommutative(Pred: I.getSwappedCmpPredicate(), Op0: Op1, Op1: Op0, CtxI&: I))
8155 return Res;
8156
8157 if (I.isCommutative()) {
8158 if (auto Pair = matchSymmetricPair(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1))) {
8159 replaceOperand(I, OpNum: 0, V: Pair->first);
8160 replaceOperand(I, OpNum: 1, V: Pair->second);
8161 return &I;
8162 }
8163 }
8164
8165 // Fold icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8166 // when all select arms are constants, via truth table.
8167 if (Instruction *R = foldCmpSelectOfConstants(I))
8168 return R;
8169
8170 // In case of a comparison with two select instructions having the same
8171 // condition, check whether one of the resulting branches can be simplified.
8172 // If so, just compare the other branch and select the appropriate result.
8173 // For example:
8174 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
8175 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
8176 // %cmp2 = icmp slt i32 %tmp2, %tmp1
8177 // The icmp will result false for the false value of selects and the result
8178 // will depend upon the comparison of true values of selects if %cmp is
8179 // true. Thus, transform this into:
8180 // %cmp = icmp slt i32 %y, %z
8181 // %sel = select i1 %cond, i1 %cmp, i1 false
8182 // This handles similar cases to transform.
8183 {
8184 Value *Cond, *A, *B, *C, *D;
8185 if (match(V: Op0, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: A), R: m_Value(V&: B))) &&
8186 match(V: Op1, P: m_Select(C: m_Specific(V: Cond), L: m_Value(V&: C), R: m_Value(V&: D))) &&
8187 (Op0->hasOneUse() || Op1->hasOneUse())) {
8188 // Check whether comparison of TrueValues can be simplified
8189 if (Value *Res = simplifyICmpInst(Pred, LHS: A, RHS: C, Q: SQ)) {
8190 Value *NewICMP = Builder.CreateICmp(P: Pred, LHS: B, RHS: D);
8191 return SelectInst::Create(C: Cond, S1: Res, S2: NewICMP, /*NameStr=*/"",
8192 /*InsertBefore=*/nullptr,
8193 MDFrom: cast<Instruction>(Val: Op0));
8194 }
8195 // Check whether comparison of FalseValues can be simplified
8196 if (Value *Res = simplifyICmpInst(Pred, LHS: B, RHS: D, Q: SQ)) {
8197 Value *NewICMP = Builder.CreateICmp(P: Pred, LHS: A, RHS: C);
8198 return SelectInst::Create(C: Cond, S1: NewICMP, S2: Res, /*NameStr=*/"",
8199 /*InsertBefore=*/nullptr,
8200 MDFrom: cast<Instruction>(Val: Op0));
8201 }
8202 }
8203 }
8204
8205 // icmp slt (sub nsw x, y), (add nsw x, y) --> icmp sgt y, 0
8206 // icmp ult (sub nuw x, y), (add nuw x, y) --> icmp ugt y, 0
8207 // icmp eq (sub nsw/nuw x, y), (add nsw/nuw x, y) --> icmp eq y, 0
8208 {
8209 Value *A, *B;
8210 CmpPredicate CmpPred;
8211 if (match(V: &I, P: m_c_ICmp(Pred&: CmpPred, L: m_Sub(L: m_Value(V&: A), R: m_Value(V&: B)),
8212 R: m_c_Add(L: m_Deferred(V: A), R: m_Deferred(V: B))))) {
8213 auto *I0 = cast<OverflowingBinaryOperator>(Val: Op0);
8214 auto *I1 = cast<OverflowingBinaryOperator>(Val: Op1);
8215 bool I0NUW = I0->hasNoUnsignedWrap();
8216 bool I1NUW = I1->hasNoUnsignedWrap();
8217 bool I0NSW = I0->hasNoSignedWrap();
8218 bool I1NSW = I1->hasNoSignedWrap();
8219 if ((ICmpInst::isUnsigned(Pred) && I0NUW && I1NUW) ||
8220 (ICmpInst::isSigned(Pred) && I0NSW && I1NSW) ||
8221 (ICmpInst::isEquality(P: Pred) &&
8222 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
8223 return new ICmpInst(CmpPredicate::getSwapped(P: CmpPred), B,
8224 ConstantInt::get(Ty: Op0->getType(), V: 0));
8225 }
8226 }
8227 }
8228
8229 // Try to optimize equality comparisons against alloca-based pointers.
8230 if (Op0->getType()->isPointerTy() && I.isEquality()) {
8231 assert(Op1->getType()->isPointerTy() &&
8232 "Comparing pointer with non-pointer?");
8233 if (auto *Alloca = dyn_cast<AllocaInst>(Val: getUnderlyingObject(V: Op0)))
8234 if (foldAllocaCmp(Alloca))
8235 return nullptr;
8236 if (auto *Alloca = dyn_cast<AllocaInst>(Val: getUnderlyingObject(V: Op1)))
8237 if (foldAllocaCmp(Alloca))
8238 return nullptr;
8239 }
8240
8241 if (Instruction *Res = foldICmpBitCast(Cmp&: I))
8242 return Res;
8243
8244 // TODO: Hoist this above the min/max bailout.
8245 if (Instruction *R = foldICmpWithCastOp(ICmp&: I))
8246 return R;
8247
8248 // icmp (zext X), (and (trunc Y), Mask) -> icmp X, trunc Y IFF Mask exactly
8249 // covers the bits of X
8250 {
8251 Value *Y;
8252 const APInt *Mask;
8253 if (match(V: I.getOperand(i_nocapture: 1), P: m_ZExt(Op: m_Value(V&: X))) &&
8254 match(V: I.getOperand(i_nocapture: 0),
8255 P: m_OneUse(SubPattern: m_And(L: m_Trunc(Op: m_Value(V&: Y)), R: m_APInt(Res&: Mask))))) {
8256 Type *SmallType = X->getType();
8257 unsigned SmallWidth = SmallType->getScalarSizeInBits();
8258 if (Mask->isMask(numBits: SmallWidth) &&
8259 shouldChangeType(From: I.getOperand(i_nocapture: 0)->getType(), To: SmallType)) {
8260 Value *NewTrunc = Builder.CreateTrunc(V: Y, DestTy: SmallType);
8261 return new ICmpInst(I.getUnsignedPredicate(), NewTrunc, X);
8262 }
8263 }
8264 }
8265
8266 {
8267 Value *X, *Y;
8268 // Transform (X & ~Y) == 0 --> (X & Y) != 0
8269 // and (X & ~Y) != 0 --> (X & Y) == 0
8270 // if A is a power of 2.
8271 if (match(V: Op0, P: m_And(L: m_Value(V&: X), R: m_Not(V: m_Value(V&: Y)))) &&
8272 match(V: Op1, P: m_Zero()) && isKnownToBeAPowerOfTwo(V: X, OrZero: false, CtxI: &I) &&
8273 I.isEquality())
8274 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(LHS: X, RHS: Y),
8275 Op1);
8276
8277 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
8278 if (Op0->getType()->isIntOrIntVectorTy()) {
8279 bool ConsumesOp0, ConsumesOp1;
8280 if (isFreeToInvert(V: Op0, WillInvertAllUses: Op0->hasOneUse(), DoesConsume&: ConsumesOp0) &&
8281 isFreeToInvert(V: Op1, WillInvertAllUses: Op1->hasOneUse(), DoesConsume&: ConsumesOp1) &&
8282 (ConsumesOp0 || ConsumesOp1)) {
8283 Value *InvOp0 = getFreelyInverted(V: Op0, WillInvertAllUses: Op0->hasOneUse(), Builder: &Builder);
8284 Value *InvOp1 = getFreelyInverted(V: Op1, WillInvertAllUses: Op1->hasOneUse(), Builder: &Builder);
8285 assert(InvOp0 && InvOp1 &&
8286 "Mismatch between isFreeToInvert and getFreelyInverted");
8287 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
8288 }
8289 }
8290
8291 Instruction *AddI = nullptr;
8292 if (match(V: &I, P: m_UAddWithOverflow(L: m_Value(V&: X), R: m_Value(V&: Y),
8293 S: m_Instruction(I&: AddI))) &&
8294 isa<IntegerType>(Val: X->getType())) {
8295 Value *Result;
8296 Constant *Overflow;
8297 // m_UAddWithOverflow can match patterns that do not include an explicit
8298 // "add" instruction, so check the opcode of the matched op.
8299 if (AddI->getOpcode() == Instruction::Add &&
8300 OptimizeOverflowCheck(BinaryOp: Instruction::Add, /*Signed*/ IsSigned: false, LHS: X, RHS: Y, OrigI&: *AddI,
8301 Result, Overflow)) {
8302 replaceInstUsesWith(I&: *AddI, V: Result);
8303 eraseInstFromFunction(I&: *AddI);
8304 return replaceInstUsesWith(I, V: Overflow);
8305 }
8306 }
8307
8308 // (zext X) + (zext Y) --> add + overflow check.
8309 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
8310 if ((match(V: Op0, P: m_NUWAdd(L: m_ZExt(Op: m_Value(V&: X)), R: m_ZExt(Op: m_Value(V&: Y)))) ||
8311 match(V: Op0, P: m_NUWMul(L: m_ZExt(Op: m_Value(V&: X)), R: m_ZExt(Op: m_Value(V&: Y))))) &&
8312 match(V: Op1, P: m_APInt(Res&: C))) {
8313 if (Instruction *R = processUZExtIdiom(I, Val: Op0, OtherVal: C, IC&: *this))
8314 return R;
8315 }
8316
8317 // Signbit test folds
8318 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
8319 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
8320 Instruction *ExtI;
8321 if ((I.isUnsigned() || I.isEquality()) &&
8322 match(V: Op1,
8323 P: m_CombineAnd(Ps: m_Instruction(I&: ExtI), Ps: m_ZExtOrSExt(Op: m_Value(V&: Y)))) &&
8324 Y->getType()->getScalarSizeInBits() == 1 &&
8325 (Op0->hasOneUse() || Op1->hasOneUse())) {
8326 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
8327 Instruction *ShiftI;
8328 if (match(V: Op0, P: m_CombineAnd(Ps: m_Instruction(I&: ShiftI),
8329 Ps: m_Shr(L: m_Value(V&: X), R: m_SpecificIntAllowPoison(
8330 V: OpWidth - 1))))) {
8331 unsigned ExtOpc = ExtI->getOpcode();
8332 unsigned ShiftOpc = ShiftI->getOpcode();
8333 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
8334 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
8335 Value *SLTZero =
8336 Builder.CreateICmpSLT(LHS: X, RHS: Constant::getNullValue(Ty: X->getType()));
8337 Value *Cmp = Builder.CreateICmp(P: Pred, LHS: SLTZero, RHS: Y, Name: I.getName());
8338 return replaceInstUsesWith(I, V: Cmp);
8339 }
8340 }
8341 }
8342 }
8343
8344 if (Instruction *Res = foldICmpEquality(I))
8345 return Res;
8346
8347 if (Instruction *Res = foldICmpPow2Test(I, Builder))
8348 return Res;
8349
8350 if (Instruction *Res = foldICmpOfUAddOv(I))
8351 return Res;
8352
8353 if (Instruction *Res = foldICmpOfVectorReduce(I, DL, Builder))
8354 return Res;
8355
8356 // The 'cmpxchg' instruction returns an aggregate containing the old value and
8357 // an i1 which indicates whether or not we successfully did the swap.
8358 //
8359 // Replace comparisons between the old value and the expected value with the
8360 // indicator that 'cmpxchg' returns.
8361 //
8362 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
8363 // spuriously fail. In those cases, the old value may equal the expected
8364 // value but it is possible for the swap to not occur.
8365 if (I.getPredicate() == ICmpInst::ICMP_EQ)
8366 if (auto *EVI = dyn_cast<ExtractValueInst>(Val: Op0))
8367 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(Val: EVI->getAggregateOperand()))
8368 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
8369 !ACXI->isWeak())
8370 return ExtractValueInst::Create(Agg: ACXI, Idxs: 1);
8371
8372 if (Instruction *Res = foldICmpWithHighBitMask(Cmp&: I, Builder))
8373 return Res;
8374
8375 if (I.getType()->isVectorTy())
8376 if (Instruction *Res = foldVectorCmp(Cmp&: I, Builder))
8377 return Res;
8378
8379 if (Instruction *Res = foldICmpInvariantGroup(I))
8380 return Res;
8381
8382 if (Instruction *Res = foldReductionIdiom(I, Builder, DL))
8383 return Res;
8384
8385 {
8386 Value *A;
8387 const APInt *C1, *C2;
8388 ICmpInst::Predicate Pred = I.getPredicate();
8389 if (ICmpInst::isEquality(P: Pred)) {
8390 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
8391 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
8392 if (match(V: Op0, P: m_And(L: m_SExt(Op: m_Value(V&: A)), R: m_APInt(Res&: C1))) &&
8393 match(V: Op1, P: m_APInt(Res&: C2))) {
8394 Type *InputTy = A->getType();
8395 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
8396 // c2 must be non-negative at the bitwidth of a.
8397 if (C2->getActiveBits() < InputBitWidth) {
8398 APInt TruncC1 = C1->trunc(width: InputBitWidth);
8399 // Check if there are 1s in C1 high bits of size InputBitWidth.
8400 if (C1->uge(RHS: APInt::getOneBitSet(numBits: C1->getBitWidth(), BitNo: InputBitWidth)))
8401 TruncC1.setBit(InputBitWidth - 1);
8402 Value *AndInst = Builder.CreateAnd(LHS: A, RHS: TruncC1);
8403 return new ICmpInst(
8404 Pred, AndInst,
8405 ConstantInt::get(Ty: InputTy, V: C2->trunc(width: InputBitWidth)));
8406 }
8407 }
8408 }
8409 }
8410
8411 return Changed ? &I : nullptr;
8412}
8413
8414/// Fold fcmp ([us]itofp x, cst) if possible.
8415Instruction *InstCombinerImpl::foldFCmpIntToFPConst(FCmpInst &I,
8416 Instruction *LHSI,
8417 Constant *RHSC) {
8418 const APFloat *RHS;
8419 if (!match(V: RHSC, P: m_APFloat(Res&: RHS)))
8420 return nullptr;
8421
8422 // Get the width of the mantissa. We don't want to hack on conversions that
8423 // might lose information from the integer, e.g. "i64 -> float"
8424 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8425 if (MantissaWidth == -1)
8426 return nullptr; // Unknown.
8427
8428 Type *IntTy = LHSI->getOperand(i: 0)->getType();
8429 unsigned IntWidth = IntTy->getScalarSizeInBits();
8430 bool LHSUnsigned = isa<UIToFPInst>(Val: LHSI);
8431
8432 if (I.isEquality()) {
8433 FCmpInst::Predicate P = I.getPredicate();
8434 bool IsExact = false;
8435 APSInt RHSCvt(IntWidth, LHSUnsigned);
8436 RHS->convertToInteger(Result&: RHSCvt, RM: APFloat::rmNearestTiesToEven, IsExact: &IsExact);
8437
8438 // If the floating point constant isn't an integer value, we know if we will
8439 // ever compare equal / not equal to it.
8440 if (!IsExact) {
8441 // TODO: Can never be -0.0 and other non-representable values
8442 APFloat RHSRoundInt(*RHS);
8443 RHSRoundInt.roundToIntegral(RM: APFloat::rmNearestTiesToEven);
8444 if (*RHS != RHSRoundInt) {
8445 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
8446 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8447
8448 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
8449 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8450 }
8451 }
8452
8453 // TODO: If the constant is exactly representable, is it always OK to do
8454 // equality compares as integer?
8455 }
8456
8457 // Check to see that the input is converted from an integer type that is small
8458 // enough that preserves all bits. TODO: check here for "known" sign bits.
8459 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
8460
8461 // Following test does NOT adjust IntWidth downwards for signed inputs,
8462 // because the most negative value still requires all the mantissa bits
8463 // to distinguish it from one less than that value.
8464 if ((int)IntWidth > MantissaWidth) {
8465 // Conversion would lose accuracy. Check if loss can impact comparison.
8466 int Exp = ilogb(Arg: *RHS);
8467 if (Exp == APFloat::IEK_Inf) {
8468 int MaxExponent = ilogb(Arg: APFloat::getLargest(Sem: RHS->getSemantics()));
8469 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
8470 // Conversion could create infinity.
8471 return nullptr;
8472 } else {
8473 // Note that if RHS is zero or NaN, then Exp is negative
8474 // and first condition is trivially false.
8475 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
8476 // Conversion could affect comparison.
8477 return nullptr;
8478 }
8479 }
8480
8481 // Otherwise, we can potentially simplify the comparison. We know that it
8482 // will always come through as an integer value and we know the constant is
8483 // not a NAN (it would have been previously simplified).
8484 assert(!RHS->isNaN() && "NaN comparison not already folded!");
8485
8486 ICmpInst::Predicate Pred;
8487 switch (I.getPredicate()) {
8488 default:
8489 llvm_unreachable("Unexpected predicate!");
8490 case FCmpInst::FCMP_UEQ:
8491 case FCmpInst::FCMP_OEQ:
8492 Pred = ICmpInst::ICMP_EQ;
8493 break;
8494 case FCmpInst::FCMP_UGT:
8495 case FCmpInst::FCMP_OGT:
8496 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
8497 break;
8498 case FCmpInst::FCMP_UGE:
8499 case FCmpInst::FCMP_OGE:
8500 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
8501 break;
8502 case FCmpInst::FCMP_ULT:
8503 case FCmpInst::FCMP_OLT:
8504 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
8505 break;
8506 case FCmpInst::FCMP_ULE:
8507 case FCmpInst::FCMP_OLE:
8508 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
8509 break;
8510 case FCmpInst::FCMP_UNE:
8511 case FCmpInst::FCMP_ONE:
8512 Pred = ICmpInst::ICMP_NE;
8513 break;
8514 case FCmpInst::FCMP_ORD:
8515 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8516 case FCmpInst::FCMP_UNO:
8517 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8518 }
8519
8520 // Now we know that the APFloat is a normal number, zero or inf.
8521
8522 // See if the FP constant is too large for the integer. For example,
8523 // comparing an i8 to 300.0.
8524 if (!LHSUnsigned) {
8525 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
8526 // and large values.
8527 APFloat SMax(RHS->getSemantics());
8528 SMax.convertFromAPInt(Input: APInt::getSignedMaxValue(numBits: IntWidth), IsSigned: true,
8529 RM: APFloat::rmNearestTiesToEven);
8530 if (SMax < *RHS) { // smax < 13123.0
8531 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
8532 Pred == ICmpInst::ICMP_SLE)
8533 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8534 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8535 }
8536 } else {
8537 // If the RHS value is > UnsignedMax, fold the comparison. This handles
8538 // +INF and large values.
8539 APFloat UMax(RHS->getSemantics());
8540 UMax.convertFromAPInt(Input: APInt::getMaxValue(numBits: IntWidth), IsSigned: false,
8541 RM: APFloat::rmNearestTiesToEven);
8542 if (UMax < *RHS) { // umax < 13123.0
8543 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
8544 Pred == ICmpInst::ICMP_ULE)
8545 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8546 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8547 }
8548 }
8549
8550 if (!LHSUnsigned) {
8551 // See if the RHS value is < SignedMin.
8552 APFloat SMin(RHS->getSemantics());
8553 SMin.convertFromAPInt(Input: APInt::getSignedMinValue(numBits: IntWidth), IsSigned: true,
8554 RM: APFloat::rmNearestTiesToEven);
8555 if (SMin > *RHS) { // smin > 12312.0
8556 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
8557 Pred == ICmpInst::ICMP_SGE)
8558 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8559 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8560 }
8561 } else {
8562 // See if the RHS value is < UnsignedMin.
8563 APFloat UMin(RHS->getSemantics());
8564 UMin.convertFromAPInt(Input: APInt::getMinValue(numBits: IntWidth), IsSigned: false,
8565 RM: APFloat::rmNearestTiesToEven);
8566 if (UMin > *RHS) { // umin > 12312.0
8567 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
8568 Pred == ICmpInst::ICMP_UGE)
8569 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8570 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8571 }
8572 }
8573
8574 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
8575 // [0, UMAX], but it may still be fractional. Check whether this is the case
8576 // using the IsExact flag.
8577 // Don't do this for zero, because -0.0 is not fractional.
8578 APSInt RHSInt(IntWidth, LHSUnsigned);
8579 bool IsExact;
8580 RHS->convertToInteger(Result&: RHSInt, RM: APFloat::rmTowardZero, IsExact: &IsExact);
8581 if (!RHS->isZero()) {
8582 if (!IsExact) {
8583 // If we had a comparison against a fractional value, we have to adjust
8584 // the compare predicate and sometimes the value. RHSC is rounded towards
8585 // zero at this point.
8586 switch (Pred) {
8587 default:
8588 llvm_unreachable("Unexpected integer comparison!");
8589 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
8590 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8591 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
8592 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8593 case ICmpInst::ICMP_ULE:
8594 // (float)int <= 4.4 --> int <= 4
8595 // (float)int <= -4.4 --> false
8596 if (RHS->isNegative())
8597 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8598 break;
8599 case ICmpInst::ICMP_SLE:
8600 // (float)int <= 4.4 --> int <= 4
8601 // (float)int <= -4.4 --> int < -4
8602 if (RHS->isNegative())
8603 Pred = ICmpInst::ICMP_SLT;
8604 break;
8605 case ICmpInst::ICMP_ULT:
8606 // (float)int < -4.4 --> false
8607 // (float)int < 4.4 --> int <= 4
8608 if (RHS->isNegative())
8609 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8610 Pred = ICmpInst::ICMP_ULE;
8611 break;
8612 case ICmpInst::ICMP_SLT:
8613 // (float)int < -4.4 --> int < -4
8614 // (float)int < 4.4 --> int <= 4
8615 if (!RHS->isNegative())
8616 Pred = ICmpInst::ICMP_SLE;
8617 break;
8618 case ICmpInst::ICMP_UGT:
8619 // (float)int > 4.4 --> int > 4
8620 // (float)int > -4.4 --> true
8621 if (RHS->isNegative())
8622 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8623 break;
8624 case ICmpInst::ICMP_SGT:
8625 // (float)int > 4.4 --> int > 4
8626 // (float)int > -4.4 --> int >= -4
8627 if (RHS->isNegative())
8628 Pred = ICmpInst::ICMP_SGE;
8629 break;
8630 case ICmpInst::ICMP_UGE:
8631 // (float)int >= -4.4 --> true
8632 // (float)int >= 4.4 --> int > 4
8633 if (RHS->isNegative())
8634 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8635 Pred = ICmpInst::ICMP_UGT;
8636 break;
8637 case ICmpInst::ICMP_SGE:
8638 // (float)int >= -4.4 --> int >= -4
8639 // (float)int >= 4.4 --> int > 4
8640 if (!RHS->isNegative())
8641 Pred = ICmpInst::ICMP_SGT;
8642 break;
8643 }
8644 }
8645 }
8646
8647 // Lower this FP comparison into an appropriate integer version of the
8648 // comparison.
8649 return new ICmpInst(Pred, LHSI->getOperand(i: 0),
8650 ConstantInt::get(Ty: LHSI->getOperand(i: 0)->getType(), V: RHSInt));
8651}
8652
8653/// Fold fcmp/icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8654/// where all true/false values are constants that allow the compare to be
8655/// constant-folded for every combination of C1 and C2.
8656/// We compute a 4-entry truth table and use createLogicFromTable to
8657/// synthesize a boolean expression of C1 and C2.
8658Instruction *InstCombinerImpl::foldCmpSelectOfConstants(CmpInst &I) {
8659 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
8660 Value *C1, *C2;
8661 Constant *TV1, *FV1, *TV2, *FV2;
8662
8663 if (!match(V: Op0, P: m_Select(C: m_Value(V&: C1), L: m_Constant(C&: TV1), R: m_Constant(C&: FV1))) ||
8664 !match(V: Op1, P: m_Select(C: m_Value(V&: C2), L: m_Constant(C&: TV2), R: m_Constant(C&: FV2))))
8665 return nullptr;
8666
8667 if (I.getType() != C1->getType() || I.getType() != C2->getType())
8668 return nullptr;
8669
8670 unsigned Pred = I.getPredicate();
8671 const DataLayout &DL = I.getDataLayout();
8672
8673 Constant *Res00 = ConstantFoldCompareInstOperands(Predicate: Pred, LHS: FV1, RHS: FV2, DL);
8674 Constant *Res01 = ConstantFoldCompareInstOperands(Predicate: Pred, LHS: FV1, RHS: TV2, DL);
8675 Constant *Res10 = ConstantFoldCompareInstOperands(Predicate: Pred, LHS: TV1, RHS: FV2, DL);
8676 Constant *Res11 = ConstantFoldCompareInstOperands(Predicate: Pred, LHS: TV1, RHS: TV2, DL);
8677
8678 if (!Res00 || !Res01 || !Res10 || !Res11)
8679 return nullptr;
8680
8681 if ((!Res00->isNullValue() && !Res00->isAllOnesValue()) ||
8682 (!Res01->isNullValue() && !Res01->isAllOnesValue()) ||
8683 (!Res10->isNullValue() && !Res10->isAllOnesValue()) ||
8684 (!Res11->isNullValue() && !Res11->isAllOnesValue()))
8685 return nullptr;
8686
8687 std::bitset<4> Table;
8688 if (!Res00->isNullValue())
8689 Table.set(position: 0);
8690 if (!Res01->isNullValue())
8691 Table.set(position: 1);
8692 if (!Res10->isNullValue())
8693 Table.set(position: 2);
8694 if (!Res11->isNullValue())
8695 Table.set(position: 3);
8696
8697 Value *Res = createLogicFromTable(Table, Op0: C1, Op1: C2, Builder,
8698 HasOneUse: Op0->hasOneUse() && Op1->hasOneUse());
8699 if (!Res)
8700 return nullptr;
8701 return replaceInstUsesWith(I, V: Res);
8702}
8703
8704/// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
8705static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI,
8706 Constant *RHSC) {
8707 // When C is not 0.0 and infinities are not allowed:
8708 // (C / X) < 0.0 is a sign-bit test of X
8709 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
8710 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
8711 //
8712 // Proof:
8713 // Multiply (C / X) < 0.0 by X * X / C.
8714 // - X is non zero, if it is the flag 'ninf' is violated.
8715 // - C defines the sign of X * X * C. Thus it also defines whether to swap
8716 // the predicate. C is also non zero by definition.
8717 //
8718 // Thus X * X / C is non zero and the transformation is valid. [qed]
8719
8720 FCmpInst::Predicate Pred = I.getPredicate();
8721
8722 // Check that predicates are valid.
8723 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
8724 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
8725 return nullptr;
8726
8727 // Check that RHS operand is zero.
8728 if (!match(V: RHSC, P: m_AnyZeroFP()))
8729 return nullptr;
8730
8731 // Check fastmath flags ('ninf').
8732 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
8733 return nullptr;
8734
8735 // Check the properties of the dividend. It must not be zero to avoid a
8736 // division by zero (see Proof).
8737 const APFloat *C;
8738 if (!match(V: LHSI->getOperand(i: 0), P: m_APFloat(Res&: C)))
8739 return nullptr;
8740
8741 if (C->isZero())
8742 return nullptr;
8743
8744 // Get swapped predicate if necessary.
8745 if (C->isNegative())
8746 Pred = I.getSwappedPredicate();
8747
8748 return new FCmpInst(Pred, LHSI->getOperand(i: 1), RHSC, "", &I);
8749}
8750
8751// Transform 'fptrunc(x) cmp C' to 'x cmp ext(C)' if possible.
8752// Patterns include:
8753// fptrunc(x) < C --> x < ext(C)
8754// fptrunc(x) <= C --> x <= ext(C)
8755// fptrunc(x) > C --> x > ext(C)
8756// fptrunc(x) >= C --> x >= ext(C)
8757// fptrunc(x) ord/uno C --> x ord/uno 0
8758// where 'ext(C)' is the extension of 'C' to the type of 'x' with a small bias
8759// due to precision loss.
8760static Instruction *foldFCmpFpTrunc(FCmpInst &I, const Instruction &FPTrunc,
8761 const Constant &C) {
8762 FCmpInst::Predicate Pred = I.getPredicate();
8763 Type *DestType = FPTrunc.getOperand(i: 0)->getType();
8764
8765 const APFloat *CValue;
8766 // TODO: support vec
8767 if (!match(V: &C, P: m_APFloat(Res&: CValue)))
8768 return nullptr;
8769
8770 // Handle ord/uno
8771 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) {
8772 assert(!CValue->isNaN() &&
8773 "X ord/uno NaN should be folded away by simplifyFCmpInst()");
8774 return new FCmpInst(Pred, FPTrunc.getOperand(i: 0),
8775 ConstantFP::getZero(Ty: DestType), "", &I);
8776 }
8777
8778 // Handle <, >, <=, >=
8779 bool RoundDown = false;
8780
8781 if (Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE ||
8782 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT)
8783 RoundDown = true;
8784 else if (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT ||
8785 Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)
8786 RoundDown = false;
8787 else
8788 return nullptr;
8789
8790 if (CValue->isNaN() || CValue->isInfinity())
8791 return nullptr;
8792
8793 auto ConvertFltSema = [](const APFloat &Src, const fltSemantics &Sema) {
8794 bool LosesInfo;
8795 APFloat Dest = Src;
8796 Dest.convert(ToSemantics: Sema, RM: APFloat::rmNearestTiesToEven, losesInfo: &LosesInfo);
8797 return Dest;
8798 };
8799
8800 auto NextValue = [](const APFloat &Value, bool RoundDown) {
8801 APFloat NextValue = Value;
8802 NextValue.next(nextDown: RoundDown);
8803 return NextValue;
8804 };
8805
8806 APFloat NextCValue = NextValue(*CValue, RoundDown);
8807
8808 const fltSemantics &DestFltSema =
8809 DestType->getScalarType()->getFltSemantics();
8810
8811 APFloat ExtCValue = ConvertFltSema(*CValue, DestFltSema);
8812 APFloat ExtNextCValue = ConvertFltSema(NextCValue, DestFltSema);
8813
8814 // When 'NextCValue' is infinity, use an imaged 'NextCValue' that equals
8815 // 'CValue + bias' to avoid the infinity after conversion. The bias is
8816 // estimated as 'CValue - PrevCValue', where 'PrevCValue' is the previous
8817 // value of 'CValue'.
8818 if (NextCValue.isInfinity()) {
8819 APFloat PrevCValue = NextValue(*CValue, !RoundDown);
8820 APFloat Bias = ConvertFltSema(*CValue - PrevCValue, DestFltSema);
8821
8822 ExtNextCValue = ExtCValue + Bias;
8823 }
8824
8825 APFloat ExtMidValue =
8826 scalbn(X: ExtCValue + ExtNextCValue, Exp: -1, RM: APFloat::rmNearestTiesToEven);
8827
8828 const fltSemantics &SrcFltSema =
8829 C.getType()->getScalarType()->getFltSemantics();
8830
8831 // 'MidValue' might be rounded to 'NextCValue'. Correct it here.
8832 APFloat MidValue = ConvertFltSema(ExtMidValue, SrcFltSema);
8833 if (MidValue != *CValue)
8834 ExtMidValue.next(nextDown: !RoundDown);
8835
8836 // Check whether 'ExtMidValue' is a valid result since the assumption on
8837 // imaged 'NextCValue' might not hold for new float types.
8838 // ppc_fp128 can't pass here when converting from max float because of
8839 // APFloat implementation.
8840 if (NextCValue.isInfinity()) {
8841 // ExtMidValue --- narrowed ---> Finite
8842 if (ConvertFltSema(ExtMidValue, SrcFltSema).isInfinity())
8843 return nullptr;
8844
8845 // NextExtMidValue --- narrowed ---> Infinity
8846 APFloat NextExtMidValue = NextValue(ExtMidValue, RoundDown);
8847 if (ConvertFltSema(NextExtMidValue, SrcFltSema).isFinite())
8848 return nullptr;
8849 }
8850
8851 return new FCmpInst(Pred, FPTrunc.getOperand(i: 0),
8852 ConstantFP::get(Ty: DestType, V: ExtMidValue), "", &I);
8853}
8854
8855/// Optimize fabs(X) compared with zero.
8856static Instruction *foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
8857 Value *X;
8858 if (!match(V: I.getOperand(i_nocapture: 0), P: m_FAbs(Op0: m_Value(V&: X))))
8859 return nullptr;
8860
8861 const APFloat *C;
8862 if (!match(V: I.getOperand(i_nocapture: 1), P: m_APFloat(Res&: C)))
8863 return nullptr;
8864
8865 if (!C->isPosZero()) {
8866 if (!C->isSmallestNormalized())
8867 return nullptr;
8868
8869 const Function *F = I.getFunction();
8870 DenormalMode Mode = F->getDenormalMode(FPType: C->getSemantics());
8871 if (Mode.Input == DenormalMode::PreserveSign ||
8872 Mode.Input == DenormalMode::PositiveZero) {
8873
8874 auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8875 Constant *Zero = ConstantFP::getZero(Ty: X->getType());
8876 return new FCmpInst(P, X, Zero, "", I);
8877 };
8878
8879 switch (I.getPredicate()) {
8880 case FCmpInst::FCMP_OLT:
8881 // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
8882 return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
8883 case FCmpInst::FCMP_UGE:
8884 // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
8885 return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
8886 case FCmpInst::FCMP_OGE:
8887 // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
8888 return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
8889 case FCmpInst::FCMP_ULT:
8890 // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
8891 return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
8892 default:
8893 break;
8894 }
8895 }
8896
8897 return nullptr;
8898 }
8899
8900 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8901 I->setPredicate(P);
8902 return IC.replaceOperand(I&: *I, OpNum: 0, V: X);
8903 };
8904
8905 switch (I.getPredicate()) {
8906 case FCmpInst::FCMP_UGE:
8907 case FCmpInst::FCMP_OLT:
8908 // fabs(X) >= 0.0 --> true
8909 // fabs(X) < 0.0 --> false
8910 llvm_unreachable("fcmp should have simplified");
8911
8912 case FCmpInst::FCMP_OGT:
8913 // fabs(X) > 0.0 --> X != 0.0
8914 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
8915
8916 case FCmpInst::FCMP_UGT:
8917 // fabs(X) u> 0.0 --> X u!= 0.0
8918 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
8919
8920 case FCmpInst::FCMP_OLE:
8921 // fabs(X) <= 0.0 --> X == 0.0
8922 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
8923
8924 case FCmpInst::FCMP_ULE:
8925 // fabs(X) u<= 0.0 --> X u== 0.0
8926 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
8927
8928 case FCmpInst::FCMP_OGE:
8929 // fabs(X) >= 0.0 --> !isnan(X)
8930 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8931 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
8932
8933 case FCmpInst::FCMP_ULT:
8934 // fabs(X) u< 0.0 --> isnan(X)
8935 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8936 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
8937
8938 case FCmpInst::FCMP_OEQ:
8939 case FCmpInst::FCMP_UEQ:
8940 case FCmpInst::FCMP_ONE:
8941 case FCmpInst::FCMP_UNE:
8942 case FCmpInst::FCMP_ORD:
8943 case FCmpInst::FCMP_UNO:
8944 // Look through the fabs() because it doesn't change anything but the sign.
8945 // fabs(X) == 0.0 --> X == 0.0,
8946 // fabs(X) != 0.0 --> X != 0.0
8947 // isnan(fabs(X)) --> isnan(X)
8948 // !isnan(fabs(X) --> !isnan(X)
8949 return replacePredAndOp0(&I, I.getPredicate(), X);
8950
8951 default:
8952 return nullptr;
8953 }
8954}
8955
8956/// Optimize sqrt(X) compared with zero.
8957static Instruction *foldSqrtWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
8958 Value *X;
8959 if (!match(V: I.getOperand(i_nocapture: 0), P: m_Sqrt(Op0: m_Value(V&: X))))
8960 return nullptr;
8961
8962 if (!match(V: I.getOperand(i_nocapture: 1), P: m_PosZeroFP()))
8963 return nullptr;
8964
8965 auto ReplacePredAndOp0 = [&](FCmpInst::Predicate P) {
8966 I.setPredicate(P);
8967 return IC.replaceOperand(I, OpNum: 0, V: X);
8968 };
8969
8970 // Clear ninf flag if sqrt doesn't have it.
8971 if (!cast<Instruction>(Val: I.getOperand(i_nocapture: 0))->hasNoInfs())
8972 I.setHasNoInfs(false);
8973
8974 switch (I.getPredicate()) {
8975 case FCmpInst::FCMP_OLT:
8976 case FCmpInst::FCMP_UGE:
8977 // sqrt(X) < 0.0 --> false
8978 // sqrt(X) u>= 0.0 --> true
8979 llvm_unreachable("fcmp should have simplified");
8980 case FCmpInst::FCMP_ULT:
8981 case FCmpInst::FCMP_ULE:
8982 case FCmpInst::FCMP_OGT:
8983 case FCmpInst::FCMP_OGE:
8984 case FCmpInst::FCMP_OEQ:
8985 case FCmpInst::FCMP_UNE:
8986 // sqrt(X) u< 0.0 --> X u< 0.0
8987 // sqrt(X) u<= 0.0 --> X u<= 0.0
8988 // sqrt(X) > 0.0 --> X > 0.0
8989 // sqrt(X) >= 0.0 --> X >= 0.0
8990 // sqrt(X) == 0.0 --> X == 0.0
8991 // sqrt(X) u!= 0.0 --> X u!= 0.0
8992 return IC.replaceOperand(I, OpNum: 0, V: X);
8993
8994 case FCmpInst::FCMP_OLE:
8995 // sqrt(X) <= 0.0 --> X == 0.0
8996 return ReplacePredAndOp0(FCmpInst::FCMP_OEQ);
8997 case FCmpInst::FCMP_UGT:
8998 // sqrt(X) u> 0.0 --> X u!= 0.0
8999 return ReplacePredAndOp0(FCmpInst::FCMP_UNE);
9000 case FCmpInst::FCMP_UEQ:
9001 // sqrt(X) u== 0.0 --> X u<= 0.0
9002 return ReplacePredAndOp0(FCmpInst::FCMP_ULE);
9003 case FCmpInst::FCMP_ONE:
9004 // sqrt(X) != 0.0 --> X > 0.0
9005 return ReplacePredAndOp0(FCmpInst::FCMP_OGT);
9006 case FCmpInst::FCMP_ORD:
9007 // !isnan(sqrt(X)) --> X >= 0.0
9008 return ReplacePredAndOp0(FCmpInst::FCMP_OGE);
9009 case FCmpInst::FCMP_UNO:
9010 // isnan(sqrt(X)) --> X u< 0.0
9011 return ReplacePredAndOp0(FCmpInst::FCMP_ULT);
9012 default:
9013 llvm_unreachable("Unexpected predicate!");
9014 }
9015}
9016
9017static Instruction *foldFCmpFNegCommonOp(FCmpInst &I) {
9018 CmpInst::Predicate Pred = I.getPredicate();
9019 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
9020
9021 // Canonicalize fneg as Op1.
9022 if (match(V: Op0, P: m_FNeg(X: m_Value())) && !match(V: Op1, P: m_FNeg(X: m_Value()))) {
9023 std::swap(a&: Op0, b&: Op1);
9024 Pred = I.getSwappedPredicate();
9025 }
9026
9027 if (!match(V: Op1, P: m_FNeg(X: m_Specific(V: Op0))))
9028 return nullptr;
9029
9030 // Replace the negated operand with 0.0:
9031 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
9032 Constant *Zero = ConstantFP::getZero(Ty: Op0->getType());
9033 return new FCmpInst(Pred, Op0, Zero, "", &I);
9034}
9035
9036static Instruction *foldFCmpFSubIntoFCmp(FCmpInst &I, Instruction *LHSI,
9037 Constant *RHSC, InstCombinerImpl &CI) {
9038 const CmpInst::Predicate Pred = I.getPredicate();
9039 Value *X = LHSI->getOperand(i: 0);
9040 Value *Y = LHSI->getOperand(i: 1);
9041 switch (Pred) {
9042 default:
9043 break;
9044 case FCmpInst::FCMP_UGT:
9045 case FCmpInst::FCMP_ULT:
9046 case FCmpInst::FCMP_UNE:
9047 case FCmpInst::FCMP_OEQ:
9048 case FCmpInst::FCMP_OGE:
9049 case FCmpInst::FCMP_OLE:
9050 // The optimization is not valid if X and Y are infinities of the same
9051 // sign, i.e. the inf - inf = nan case. If the fsub has the ninf or nnan
9052 // flag then we can assume we do not have that case. Otherwise we might be
9053 // able to prove that either X or Y is not infinity.
9054 if (!LHSI->hasNoNaNs() && !LHSI->hasNoInfs() &&
9055 !isKnownNeverInfinity(V: Y,
9056 SQ: CI.getSimplifyQuery().getWithInstruction(I: &I)) &&
9057 !isKnownNeverInfinity(V: X, SQ: CI.getSimplifyQuery().getWithInstruction(I: &I)))
9058 break;
9059
9060 [[fallthrough]];
9061 case FCmpInst::FCMP_OGT:
9062 case FCmpInst::FCMP_OLT:
9063 case FCmpInst::FCMP_ONE:
9064 case FCmpInst::FCMP_UEQ:
9065 case FCmpInst::FCMP_UGE:
9066 case FCmpInst::FCMP_ULE:
9067 // fcmp pred (x - y), 0 --> fcmp pred x, y
9068 if (match(V: RHSC, P: m_AnyZeroFP()) &&
9069 I.getFunction()->getDenormalMode(
9070 FPType: LHSI->getType()->getScalarType()->getFltSemantics()) ==
9071 DenormalMode::getIEEE()) {
9072 CI.replaceOperand(I, OpNum: 0, V: X);
9073 CI.replaceOperand(I, OpNum: 1, V: Y);
9074 I.setHasNoInfs(LHSI->hasNoInfs());
9075 if (LHSI->hasNoNaNs())
9076 I.setHasNoNaNs(true);
9077 return &I;
9078 }
9079 // fcmp `pred (C - Y), C` -> `fcmp swap(pred), Y, 0`
9080 // where C and Y can't be arbitrary floating-point values.
9081 // For example, with `C = 1.0f` and `Y = 0x1p-149`, `1.0f - Y` rounds back
9082 // to `1.0f`, so the source compare is false while the rewritten compare is
9083 // true.
9084 // We need to make sure (C - Y) never rounds back to C
9085 const APFloat *C;
9086 Value *IntSrc;
9087 if (match(V: RHSC, P: m_APFloat(Res&: C)) &&
9088 match(V: LHSI, P: m_FSub(L: m_Specific(V: RHSC), R: m_IToFP(Op: m_Value(V&: IntSrc)))) &&
9089 C->isNormal()) {
9090 // Requirements on C and Y:
9091 // 1. C is finite, nonzero, normal.
9092 // 2. C shouldn't be too large, that is, ULP(C) <= 1.
9093 // 3. Y must be the form of `[su]itofp`, so the finite nonzero result of Y
9094 // must be integer-valued with an absolute value of at least 1;
9095 // as long as the step size near C does not exceed 1,
9096 // C - Y cannot be rounded back to C when Y != 0.
9097 // 4. If Y = 0, `fcmp pred (C - 0), C` are equivalent to `fcmp swap(pred)
9098 // 0, 0` for ordered and unordered predicates as long as C is finite and
9099 // nonzero.
9100 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
9101 if (MantissaWidth != -1 && ilogb(Arg: *C) < MantissaWidth) {
9102 Constant *ZeroC = ConstantFP::getZero(Ty: LHSI->getType());
9103 I.setPredicate(I.getSwappedPredicate());
9104 CI.replaceOperand(I, OpNum: 0, V: Y);
9105 CI.replaceOperand(I, OpNum: 1, V: ZeroC);
9106 return &I;
9107 }
9108 }
9109 break;
9110 }
9111
9112 return nullptr;
9113}
9114
9115/// Fold: fabs(uitofp(a) - uitofp(b)) pred C --> a == b
9116/// where 'pred' is olt, ult, ogt, ugt, oge or uge and C is a positive, Non-NaN
9117/// float when the uitofp casts are exact and C is in the valid range.
9118///
9119/// Since exact uitofp means distinct integers map to distinct floats, the only
9120/// values fabs(uitofp(a) - uitofp(b)) can take are {0.0, 1.0, 2.0, ...}.
9121/// There are no values in the open interval (0, 1), so:
9122/// fabs(...) < C where 0 < C <= 1.0 --> a == b (strict lt: C=1.0 ok)
9123// fabs(..) >= C where C >= 1.0 -> a != b
9124///
9125/// The same logic applies to sitofp.
9126static Instruction *foldFCmpFAbsFSubIntToFP(FCmpInst &I, InstCombinerImpl &IC) {
9127 Value *FAbsArg;
9128 if (!match(V: I.getOperand(i_nocapture: 0), P: m_FAbs(Op0: m_Value(V&: FAbsArg))))
9129 return nullptr;
9130
9131 const APFloat *C;
9132 if (!match(V: I.getOperand(i_nocapture: 1), P: PatternMatch::m_FiniteNonZero(V&: C)))
9133 return nullptr;
9134
9135 FCmpInst::Predicate Pred = I.getPredicate();
9136 bool IsStrictLt = Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT;
9137 bool IsLe = Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE;
9138 bool IsStrictGt = Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT;
9139 bool IsGe = Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
9140 if (!IsStrictLt && !IsStrictGt && !IsGe)
9141 return nullptr;
9142
9143 APFloat One = APFloat::getOne(Sem: C->getSemantics());
9144 APFloat::cmpResult Cmp = C->compare(RHS: One);
9145
9146 // For strict-lt (olt/ult): C must be in (0, 1.0] -- C == 1.0 is fine since
9147 // the next possible value after 0.0 is 1.0, and < 1.0 excludes it.
9148 if (IsStrictLt && Cmp == APFloat::cmpGreaterThan)
9149 return nullptr;
9150 if (IsGe && Cmp == APFloat::cmpGreaterThan)
9151 return nullptr;
9152 if (IsLe && Cmp != APFloat::cmpGreaterThan)
9153 return nullptr;
9154 if (IsStrictGt && Cmp != APFloat::cmpLessThan)
9155 return nullptr;
9156
9157 // Match: fsub(uitofp(A), uitofp(B)) where both casts are uitofp or sitofp
9158 Value *A, *B;
9159 bool IsSigned;
9160 if (match(V: FAbsArg, P: m_FSub(L: m_UIToFP(Op: m_Value(V&: A)), R: m_UIToFP(Op: m_Value(V&: B))))) {
9161 IsSigned = false;
9162 } else if (match(V: FAbsArg,
9163 P: m_FSub(L: m_SIToFP(Op: m_Value(V&: A)), R: m_SIToFP(Op: m_Value(V&: B))))) {
9164 IsSigned = true;
9165 } else {
9166 return nullptr;
9167 }
9168
9169 // A and B must have the same integer type
9170 if (A->getType() != B->getType())
9171 return nullptr;
9172
9173 Type *FPTy = FAbsArg->getType();
9174 if (!IC.canBeCastedExactlyIntToFP(V: A, FPTy, IsSigned, CtxI: &I) ||
9175 !IC.canBeCastedExactlyIntToFP(V: B, FPTy, IsSigned, CtxI: &I))
9176 return nullptr;
9177 ICmpInst::Predicate ResultPred =
9178 IsStrictLt || IsLe ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9179 return new ICmpInst(ResultPred, A, B);
9180}
9181
9182static Instruction *foldFCmpWithFloorAndCeil(FCmpInst &I,
9183 InstCombinerImpl &IC) {
9184 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
9185 Type *OpType = LHS->getType();
9186 CmpInst::Predicate Pred = I.getPredicate();
9187
9188 bool FloorX = match(V: LHS, P: m_Intrinsic<Intrinsic::floor>(Ops: m_Specific(V: RHS)));
9189 bool CeilX = match(V: LHS, P: m_Intrinsic<Intrinsic::ceil>(Ops: m_Specific(V: RHS)));
9190
9191 if (!FloorX && !CeilX) {
9192 if ((FloorX = match(V: RHS, P: m_Intrinsic<Intrinsic::floor>(Ops: m_Specific(V: LHS)))) ||
9193 (CeilX = match(V: RHS, P: m_Intrinsic<Intrinsic::ceil>(Ops: m_Specific(V: LHS))))) {
9194 std::swap(a&: LHS, b&: RHS);
9195 Pred = I.getSwappedPredicate();
9196 }
9197 }
9198
9199 if ((FloorX || CeilX) && FCmpInst::isCommutative(Pred) && LHS->hasOneUse()) {
9200 // fcmp pred floor(x), x => fcmp pred trunc(x), x
9201 // fcmp pred ceil(x), x => fcmp pred trunc(x), x
9202 // where pred is oeq, one, ord, ueq, une, uno.
9203 Value *TruncX = IC.Builder.CreateUnaryIntrinsic(ID: Intrinsic::trunc, Op: RHS);
9204 return new FCmpInst(Pred, TruncX, RHS, "", &I);
9205 }
9206
9207 switch (Pred) {
9208 case FCmpInst::FCMP_OLE:
9209 // fcmp ole floor(x), x => fcmp ord x, 0
9210 if (FloorX)
9211 return new FCmpInst(FCmpInst::FCMP_ORD, RHS, ConstantFP::getZero(Ty: OpType),
9212 "", &I);
9213 break;
9214 case FCmpInst::FCMP_OGT:
9215 // fcmp ogt floor(x), x => false
9216 if (FloorX)
9217 return IC.replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
9218 break;
9219 case FCmpInst::FCMP_OGE:
9220 // fcmp oge ceil(x), x => fcmp ord x, 0
9221 if (CeilX)
9222 return new FCmpInst(FCmpInst::FCMP_ORD, RHS, ConstantFP::getZero(Ty: OpType),
9223 "", &I);
9224 break;
9225 case FCmpInst::FCMP_OLT:
9226 // fcmp olt ceil(x), x => false
9227 if (CeilX)
9228 return IC.replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
9229 break;
9230 case FCmpInst::FCMP_ULE:
9231 // fcmp ule floor(x), x => true
9232 if (FloorX)
9233 return IC.replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
9234 break;
9235 case FCmpInst::FCMP_UGT:
9236 // fcmp ugt floor(x), x => fcmp uno x, 0
9237 if (FloorX)
9238 return new FCmpInst(FCmpInst::FCMP_UNO, RHS, ConstantFP::getZero(Ty: OpType),
9239 "", &I);
9240 break;
9241 case FCmpInst::FCMP_UGE:
9242 // fcmp uge ceil(x), x => true
9243 if (CeilX)
9244 return IC.replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
9245 break;
9246 case FCmpInst::FCMP_ULT:
9247 // fcmp ult ceil(x), x => fcmp uno x, 0
9248 if (CeilX)
9249 return new FCmpInst(FCmpInst::FCMP_UNO, RHS, ConstantFP::getZero(Ty: OpType),
9250 "", &I);
9251 break;
9252 default:
9253 break;
9254 }
9255
9256 return nullptr;
9257}
9258
9259/// Returns true if a select that implements a min/max is redundant and
9260/// select result can be replaced with its non-constant operand, e.g.,
9261/// select ( (si/ui-to-fp A) <= C ), C, (si/ui-to-fp A)
9262/// where C is the FP constant equal to the minimum integer value
9263/// representable by A.
9264static bool isMinMaxCmpSelectEliminable(SelectPatternFlavor Flavor, Value *A,
9265 Value *B) {
9266 const APFloat *APF;
9267 if (!match(V: B, P: m_APFloat(Res&: APF)))
9268 return false;
9269
9270 auto *I = dyn_cast<Instruction>(Val: A);
9271 if (!I || !(I->getOpcode() == Instruction::SIToFP ||
9272 I->getOpcode() == Instruction::UIToFP))
9273 return false;
9274
9275 bool IsUnsigned = I->getOpcode() == Instruction::UIToFP;
9276 unsigned BitWidth = I->getOperand(i: 0)->getType()->getScalarSizeInBits();
9277 APSInt IntBoundary = (Flavor == SPF_FMAXNUM)
9278 ? APSInt::getMinValue(numBits: BitWidth, Unsigned: IsUnsigned)
9279 : APSInt::getMaxValue(numBits: BitWidth, Unsigned: IsUnsigned);
9280 APSInt ConvertedInt(BitWidth, IsUnsigned);
9281 bool IsExact;
9282 APFloat::opStatus Status =
9283 APF->convertToInteger(Result&: ConvertedInt, RM: APFloat::rmTowardZero, IsExact: &IsExact);
9284 return Status == APFloat::opOK && IsExact && ConvertedInt == IntBoundary;
9285}
9286
9287Instruction *InstCombinerImpl::visitFCmpInst(FCmpInst &I) {
9288 bool Changed = false;
9289
9290 /// Orders the operands of the compare so that they are listed from most
9291 /// complex to least complex. This puts constants before unary operators,
9292 /// before binary operators.
9293 if (getComplexity(V: I.getOperand(i_nocapture: 0)) < getComplexity(V: I.getOperand(i_nocapture: 1))) {
9294 I.swapOperands();
9295 Changed = true;
9296 }
9297
9298 const CmpInst::Predicate Pred = I.getPredicate();
9299 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
9300 if (Value *V = simplifyFCmpInst(Predicate: Pred, LHS: Op0, RHS: Op1, FMF: I.getFastMathFlags(),
9301 Q: SQ.getWithInstruction(I: &I)))
9302 return replaceInstUsesWith(I, V);
9303
9304 // Simplify 'fcmp pred X, X'
9305 Type *OpType = Op0->getType();
9306 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
9307 if (Op0 == Op1) {
9308 switch (Pred) {
9309 default:
9310 break;
9311 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
9312 case FCmpInst::FCMP_ULT: // True if unordered or less than
9313 case FCmpInst::FCMP_UGT: // True if unordered or greater than
9314 case FCmpInst::FCMP_UNE: // True if unordered or not equal
9315 // Canonicalize these to be 'fcmp uno %X, 0.0'.
9316 I.setPredicate(FCmpInst::FCMP_UNO);
9317 I.setOperand(i_nocapture: 1, Val_nocapture: Constant::getNullValue(Ty: OpType));
9318 return &I;
9319
9320 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
9321 case FCmpInst::FCMP_OEQ: // True if ordered and equal
9322 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
9323 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
9324 // Canonicalize these to be 'fcmp ord %X, 0.0'.
9325 I.setPredicate(FCmpInst::FCMP_ORD);
9326 I.setOperand(i_nocapture: 1, Val_nocapture: Constant::getNullValue(Ty: OpType));
9327 return &I;
9328 }
9329 }
9330
9331 if (I.isCommutative()) {
9332 if (auto Pair = matchSymmetricPair(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1))) {
9333 replaceOperand(I, OpNum: 0, V: Pair->first);
9334 replaceOperand(I, OpNum: 1, V: Pair->second);
9335 return &I;
9336 }
9337 }
9338
9339 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
9340 // then canonicalize the operand to 0.0.
9341 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
9342 if (!match(V: Op0, P: m_PosZeroFP()) &&
9343 isKnownNeverNaN(V: Op0, SQ: getSimplifyQuery().getWithInstruction(I: &I)))
9344 return replaceOperand(I, OpNum: 0, V: ConstantFP::getZero(Ty: OpType));
9345
9346 if (!match(V: Op1, P: m_PosZeroFP()) &&
9347 isKnownNeverNaN(V: Op1, SQ: getSimplifyQuery().getWithInstruction(I: &I)))
9348 return replaceOperand(I, OpNum: 1, V: ConstantFP::getZero(Ty: OpType));
9349 }
9350
9351 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
9352 Value *X, *Y;
9353 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: X))) && match(V: Op1, P: m_FNeg(X: m_Value(V&: Y))))
9354 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
9355
9356 if (Instruction *R = foldFCmpFNegCommonOp(I))
9357 return R;
9358
9359 // Test if the FCmpInst instruction is used exclusively by a select as
9360 // part of a minimum or maximum operation. If so, refrain from doing
9361 // any other folding. This helps out other analyses which understand
9362 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
9363 // and CodeGen. And in this case, at least one of the comparison
9364 // operands has at least one user besides the compare (the select),
9365 // which would often largely negate the benefit of folding anyway.
9366 if (I.hasOneUse())
9367 if (SelectInst *SI = dyn_cast<SelectInst>(Val: I.user_back())) {
9368 Value *A, *B;
9369 SelectPatternResult SPR = matchSelectPattern(V: SI, LHS&: A, RHS&: B);
9370 bool IsRedundantMinMaxClamp =
9371 (SPR.Flavor == SPF_FMAXNUM || SPR.Flavor == SPF_FMINNUM) &&
9372 isMinMaxCmpSelectEliminable(Flavor: SPR.Flavor, A, B);
9373 if (SPR.Flavor != SPF_UNKNOWN && !IsRedundantMinMaxClamp)
9374 return nullptr;
9375 }
9376
9377 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
9378 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
9379 if (match(V: Op1, P: m_AnyZeroFP()) && !match(V: Op1, P: m_PosZeroFP()))
9380 return replaceOperand(I, OpNum: 1, V: ConstantFP::getZero(Ty: OpType));
9381
9382 // Canonicalize:
9383 // fcmp olt X, +inf -> fcmp one X, +inf
9384 // fcmp ole X, +inf -> fcmp ord X, 0
9385 // fcmp ogt X, +inf -> false
9386 // fcmp oge X, +inf -> fcmp oeq X, +inf
9387 // fcmp ult X, +inf -> fcmp une X, +inf
9388 // fcmp ule X, +inf -> true
9389 // fcmp ugt X, +inf -> fcmp uno X, 0
9390 // fcmp uge X, +inf -> fcmp ueq X, +inf
9391 // fcmp olt X, -inf -> false
9392 // fcmp ole X, -inf -> fcmp oeq X, -inf
9393 // fcmp ogt X, -inf -> fcmp one X, -inf
9394 // fcmp oge X, -inf -> fcmp ord X, 0
9395 // fcmp ult X, -inf -> fcmp uno X, 0
9396 // fcmp ule X, -inf -> fcmp ueq X, -inf
9397 // fcmp ugt X, -inf -> fcmp une X, -inf
9398 // fcmp uge X, -inf -> true
9399 const APFloat *C;
9400 if (match(V: Op1, P: m_APFloat(Res&: C)) && C->isInfinity()) {
9401 switch (C->isNegative() ? FCmpInst::getSwappedPredicate(pred: Pred) : Pred) {
9402 default:
9403 break;
9404 case FCmpInst::FCMP_ORD:
9405 case FCmpInst::FCMP_UNO:
9406 case FCmpInst::FCMP_TRUE:
9407 case FCmpInst::FCMP_FALSE:
9408 case FCmpInst::FCMP_OGT:
9409 case FCmpInst::FCMP_ULE:
9410 llvm_unreachable("Should be simplified by InstSimplify");
9411 case FCmpInst::FCMP_OLT:
9412 return new FCmpInst(FCmpInst::FCMP_ONE, Op0, Op1, "", &I);
9413 case FCmpInst::FCMP_OLE:
9414 return new FCmpInst(FCmpInst::FCMP_ORD, Op0, ConstantFP::getZero(Ty: OpType),
9415 "", &I);
9416 case FCmpInst::FCMP_OGE:
9417 return new FCmpInst(FCmpInst::FCMP_OEQ, Op0, Op1, "", &I);
9418 case FCmpInst::FCMP_ULT:
9419 return new FCmpInst(FCmpInst::FCMP_UNE, Op0, Op1, "", &I);
9420 case FCmpInst::FCMP_UGT:
9421 return new FCmpInst(FCmpInst::FCMP_UNO, Op0, ConstantFP::getZero(Ty: OpType),
9422 "", &I);
9423 case FCmpInst::FCMP_UGE:
9424 return new FCmpInst(FCmpInst::FCMP_UEQ, Op0, Op1, "", &I);
9425 }
9426 }
9427
9428 // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
9429 // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
9430 if (match(V: Op1, P: m_PosZeroFP()) &&
9431 match(V: Op0, P: m_OneUse(SubPattern: m_ElementWiseBitCast(Op: m_Value(V&: X)))) &&
9432 X->getType()->isIntOrIntVectorTy() &&
9433 !F.getDenormalMode(FPType: Op1->getType()->getScalarType()->getFltSemantics())
9434 .inputsMayBeZero()) {
9435 ICmpInst::Predicate IntPred = ICmpInst::BAD_ICMP_PREDICATE;
9436 if (Pred == FCmpInst::FCMP_OEQ)
9437 IntPred = ICmpInst::ICMP_EQ;
9438 else if (Pred == FCmpInst::FCMP_UNE)
9439 IntPred = ICmpInst::ICMP_NE;
9440
9441 if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
9442 Type *IntTy = X->getType();
9443 const APInt &SignMask = ~APInt::getSignMask(BitWidth: IntTy->getScalarSizeInBits());
9444 Value *MaskX = Builder.CreateAnd(LHS: X, RHS: ConstantInt::get(Ty: IntTy, V: SignMask));
9445 return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(Ty: IntTy));
9446 }
9447 }
9448
9449 // Handle fcmp with instruction LHS and constant RHS.
9450 Instruction *LHSI;
9451 Constant *RHSC;
9452 if (match(V: Op0, P: m_Instruction(I&: LHSI)) && match(V: Op1, P: m_Constant(C&: RHSC))) {
9453 switch (LHSI->getOpcode()) {
9454 case Instruction::Select:
9455 // fcmp eq (cond ? x : -x), 0 --> fcmp eq x, 0
9456 if (FCmpInst::isEquality(Pred) && match(V: RHSC, P: m_AnyZeroFP()) &&
9457 match(V: LHSI, P: m_c_Select(L: m_FNeg(X: m_Value(V&: X)), R: m_Deferred(V: X))))
9458 return replaceOperand(I, OpNum: 0, V: X);
9459 if (Instruction *NV = FoldOpIntoSelect(Op&: I, SI: cast<SelectInst>(Val: LHSI)))
9460 return NV;
9461 break;
9462 case Instruction::FSub:
9463 if (LHSI->hasOneUse())
9464 if (Instruction *NV = foldFCmpFSubIntoFCmp(I, LHSI, RHSC, CI&: *this))
9465 return NV;
9466 break;
9467 case Instruction::PHI:
9468 if (Instruction *NV = foldOpIntoPhi(I, PN: cast<PHINode>(Val: LHSI)))
9469 return NV;
9470 break;
9471 case Instruction::SIToFP:
9472 case Instruction::UIToFP:
9473 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
9474 return NV;
9475 break;
9476 case Instruction::FDiv:
9477 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
9478 return NV;
9479 break;
9480 case Instruction::Load:
9481 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: LHSI->getOperand(i: 0)))
9482 if (Instruction *Res =
9483 foldCmpLoadFromIndexedGlobal(LI: cast<LoadInst>(Val: LHSI), GEP, ICI&: I))
9484 return Res;
9485 break;
9486 case Instruction::FPTrunc:
9487 if (Instruction *NV = foldFCmpFpTrunc(I, FPTrunc: *LHSI, C: *RHSC))
9488 return NV;
9489 break;
9490 }
9491 }
9492
9493 if (Instruction *R = foldFabsWithFcmpZero(I, IC&: *this))
9494 return R;
9495
9496 if (Instruction *R = foldFCmpFAbsFSubIntToFP(I, IC&: *this))
9497 return R;
9498
9499 if (Instruction *R = foldSqrtWithFcmpZero(I, IC&: *this))
9500 return R;
9501
9502 if (Instruction *R = foldFCmpWithFloorAndCeil(I, IC&: *this))
9503 return R;
9504
9505 if (Instruction *R = foldCmpSelectOfConstants(I))
9506 return R;
9507
9508 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: X)))) {
9509 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
9510 Constant *C;
9511 if (match(V: Op1, P: m_Constant(C)))
9512 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL))
9513 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
9514 }
9515
9516 // fcmp (fadd X, 0.0), Y --> fcmp X, Y
9517 if (match(V: Op0, P: m_FAdd(L: m_Value(V&: X), R: m_AnyZeroFP())))
9518 return new FCmpInst(Pred, X, Op1, "", &I);
9519
9520 // fcmp X, (fadd Y, 0.0) --> fcmp X, Y
9521 if (match(V: Op1, P: m_FAdd(L: m_Value(V&: Y), R: m_AnyZeroFP())))
9522 return new FCmpInst(Pred, Op0, Y, "", &I);
9523
9524 // fcmp ord/uno (fptrunc X), (fptrunc Y) -> fcmp ord/uno X, Y
9525 if ((Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) &&
9526 match(V: Op0, P: m_FPTrunc(Op: m_Value(V&: X))) && match(V: Op1, P: m_FPTrunc(Op: m_Value(V&: Y))) &&
9527 X->getType() == Y->getType())
9528 return new FCmpInst(Pred, X, Y, "", &I);
9529
9530 if (match(V: Op0, P: m_FPExt(Op: m_Value(V&: X)))) {
9531 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
9532 if (match(V: Op1, P: m_FPExt(Op: m_Value(V&: Y))) && X->getType() == Y->getType())
9533 return new FCmpInst(Pred, X, Y, "", &I);
9534
9535 const APFloat *C;
9536 if (match(V: Op1, P: m_APFloat(Res&: C))) {
9537 const fltSemantics &FPSem =
9538 X->getType()->getScalarType()->getFltSemantics();
9539 bool Lossy;
9540 APFloat TruncC = *C;
9541 TruncC.convert(ToSemantics: FPSem, RM: APFloat::rmNearestTiesToEven, losesInfo: &Lossy);
9542
9543 if (Lossy) {
9544 // X can't possibly equal the higher-precision constant, so reduce any
9545 // equality comparison.
9546 // TODO: Other predicates can be handled via getFCmpCode().
9547 switch (Pred) {
9548 case FCmpInst::FCMP_OEQ:
9549 // X is ordered and equal to an impossible constant --> false
9550 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
9551 case FCmpInst::FCMP_ONE:
9552 // X is ordered and not equal to an impossible constant --> ordered
9553 return new FCmpInst(FCmpInst::FCMP_ORD, X,
9554 ConstantFP::getZero(Ty: X->getType()));
9555 case FCmpInst::FCMP_UEQ:
9556 // X is unordered or equal to an impossible constant --> unordered
9557 return new FCmpInst(FCmpInst::FCMP_UNO, X,
9558 ConstantFP::getZero(Ty: X->getType()));
9559 case FCmpInst::FCMP_UNE:
9560 // X is unordered or not equal to an impossible constant --> true
9561 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
9562 default:
9563 break;
9564 }
9565 }
9566
9567 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
9568 // Avoid lossy conversions and denormals.
9569 // Zero is a special case that's OK to convert.
9570 APFloat Fabs = TruncC;
9571 Fabs.clearSign();
9572 if (!Lossy &&
9573 (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(Sem: FPSem)))) {
9574 Constant *NewC = ConstantFP::get(Ty: X->getType(), V: TruncC);
9575 return new FCmpInst(Pred, X, NewC, "", &I);
9576 }
9577 }
9578 }
9579
9580 // Convert a sign-bit test of an FP value into a cast and integer compare.
9581 // TODO: Simplify if the copysign constant is 0.0 or NaN.
9582 // TODO: Handle non-zero compare constants.
9583 // TODO: Handle other predicates.
9584 if (match(V: Op0, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::copysign>(Ops: m_APFloat(Res&: C),
9585 Ops: m_Value(V&: X)))) &&
9586 match(V: Op1, P: m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
9587 Type *IntType = Builder.getIntNTy(N: X->getType()->getScalarSizeInBits());
9588 if (auto *VecTy = dyn_cast<VectorType>(Val: OpType))
9589 IntType = VectorType::get(ElementType: IntType, EC: VecTy->getElementCount());
9590
9591 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
9592 if (Pred == FCmpInst::FCMP_OLT) {
9593 Value *IntX = Builder.CreateBitCast(V: X, DestTy: IntType);
9594 return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
9595 ConstantInt::getNullValue(Ty: IntType));
9596 }
9597 }
9598
9599 {
9600 Value *CanonLHS = nullptr;
9601 match(V: Op0, P: m_Intrinsic<Intrinsic::canonicalize>(Ops: m_Value(V&: CanonLHS)));
9602 // (canonicalize(x) == x) => (x == x)
9603 if (CanonLHS == Op1)
9604 return new FCmpInst(Pred, Op1, Op1, "", &I);
9605
9606 Value *CanonRHS = nullptr;
9607 match(V: Op1, P: m_Intrinsic<Intrinsic::canonicalize>(Ops: m_Value(V&: CanonRHS)));
9608 // (x == canonicalize(x)) => (x == x)
9609 if (CanonRHS == Op0)
9610 return new FCmpInst(Pred, Op0, Op0, "", &I);
9611
9612 // (canonicalize(x) == canonicalize(y)) => (x == y)
9613 if (CanonLHS && CanonRHS)
9614 return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
9615 }
9616
9617 if (I.getType()->isVectorTy())
9618 if (Instruction *Res = foldVectorCmp(Cmp&: I, Builder))
9619 return Res;
9620
9621 return Changed ? &I : nullptr;
9622}
9623