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/APSInt.h"
15#include "llvm/ADT/SetVector.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/Analysis/CaptureTracking.h"
18#include "llvm/Analysis/CmpInstAnalysis.h"
19#include "llvm/Analysis/ConstantFolding.h"
20#include "llvm/Analysis/InstructionSimplify.h"
21#include "llvm/Analysis/Utils/Local.h"
22#include "llvm/Analysis/VectorUtils.h"
23#include "llvm/IR/ConstantRange.h"
24#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/InstrTypes.h"
26#include "llvm/IR/IntrinsicInst.h"
27#include "llvm/IR/PatternMatch.h"
28#include "llvm/Support/KnownBits.h"
29#include "llvm/Transforms/InstCombine/InstCombiner.h"
30#include <bitset>
31
32using namespace llvm;
33using namespace PatternMatch;
34
35#define DEBUG_TYPE "instcombine"
36
37// How many times is a select replaced by one of its operands?
38STATISTIC(NumSel, "Number of select opts");
39
40/// Compute Result = In1+In2, returning true if the result overflowed for this
41/// type.
42static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
43 bool IsSigned = false) {
44 bool Overflow;
45 if (IsSigned)
46 Result = In1.sadd_ov(RHS: In2, Overflow);
47 else
48 Result = In1.uadd_ov(RHS: In2, Overflow);
49
50 return Overflow;
51}
52
53/// Compute Result = In1-In2, returning true if the result overflowed for this
54/// type.
55static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
56 bool IsSigned = false) {
57 bool Overflow;
58 if (IsSigned)
59 Result = In1.ssub_ov(RHS: In2, Overflow);
60 else
61 Result = In1.usub_ov(RHS: In2, Overflow);
62
63 return Overflow;
64}
65
66/// Given an icmp instruction, return true if any use of this comparison is a
67/// branch on sign bit comparison.
68static bool hasBranchUse(ICmpInst &I) {
69 for (auto *U : I.users())
70 if (isa<BranchInst>(Val: U))
71 return true;
72 return false;
73}
74
75/// Returns true if the exploded icmp can be expressed as a signed comparison
76/// to zero and updates the predicate accordingly.
77/// The signedness of the comparison is preserved.
78/// TODO: Refactor with decomposeBitTestICmp()?
79static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
80 if (!ICmpInst::isSigned(predicate: Pred))
81 return false;
82
83 if (C.isZero())
84 return ICmpInst::isRelational(P: Pred);
85
86 if (C.isOne()) {
87 if (Pred == ICmpInst::ICMP_SLT) {
88 Pred = ICmpInst::ICMP_SLE;
89 return true;
90 }
91 } else if (C.isAllOnes()) {
92 if (Pred == ICmpInst::ICMP_SGT) {
93 Pred = ICmpInst::ICMP_SGE;
94 return true;
95 }
96 }
97
98 return false;
99}
100
101/// This is called when we see this pattern:
102/// cmp pred (load (gep GV, ...)), cmpcst
103/// where GV is a global variable with a constant initializer. Try to simplify
104/// this into some simple computation that does not need the load. For example
105/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
106///
107/// If AndCst is non-null, then the loaded value is masked with that constant
108/// before doing the comparison. This handles cases like "A[i]&4 == 0".
109Instruction *InstCombinerImpl::foldCmpLoadFromIndexedGlobal(
110 LoadInst *LI, GetElementPtrInst *GEP, GlobalVariable *GV, CmpInst &ICI,
111 ConstantInt *AndCst) {
112 if (LI->isVolatile() || LI->getType() != GEP->getResultElementType() ||
113 GV->getValueType() != GEP->getSourceElementType() || !GV->isConstant() ||
114 !GV->hasDefinitiveInitializer())
115 return nullptr;
116
117 Constant *Init = GV->getInitializer();
118 if (!isa<ConstantArray>(Val: Init) && !isa<ConstantDataArray>(Val: Init))
119 return nullptr;
120
121 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
122 // Don't blow up on huge arrays.
123 if (ArrayElementCount > MaxArraySizeForCombine)
124 return nullptr;
125
126 // There are many forms of this optimization we can handle, for now, just do
127 // the simple index into a single-dimensional array.
128 //
129 // Require: GEP GV, 0, i {{, constant indices}}
130 if (GEP->getNumOperands() < 3 || !isa<ConstantInt>(Val: GEP->getOperand(i_nocapture: 1)) ||
131 !cast<ConstantInt>(Val: GEP->getOperand(i_nocapture: 1))->isZero() ||
132 isa<Constant>(Val: GEP->getOperand(i_nocapture: 2)))
133 return nullptr;
134
135 // Check that indices after the variable are constants and in-range for the
136 // type they index. Collect the indices. This is typically for arrays of
137 // structs.
138 SmallVector<unsigned, 4> LaterIndices;
139
140 Type *EltTy = Init->getType()->getArrayElementType();
141 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
142 ConstantInt *Idx = dyn_cast<ConstantInt>(Val: GEP->getOperand(i_nocapture: i));
143 if (!Idx)
144 return nullptr; // Variable index.
145
146 uint64_t IdxVal = Idx->getZExtValue();
147 if ((unsigned)IdxVal != IdxVal)
148 return nullptr; // Too large array index.
149
150 if (StructType *STy = dyn_cast<StructType>(Val: EltTy))
151 EltTy = STy->getElementType(N: IdxVal);
152 else if (ArrayType *ATy = dyn_cast<ArrayType>(Val: EltTy)) {
153 if (IdxVal >= ATy->getNumElements())
154 return nullptr;
155 EltTy = ATy->getElementType();
156 } else {
157 return nullptr; // Unknown type.
158 }
159
160 LaterIndices.push_back(Elt: IdxVal);
161 }
162
163 enum { Overdefined = -3, Undefined = -2 };
164
165 // Variables for our state machines.
166
167 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
168 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
169 // and 87 is the second (and last) index. FirstTrueElement is -2 when
170 // undefined, otherwise set to the first true element. SecondTrueElement is
171 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
172 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
173
174 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
175 // form "i != 47 & i != 87". Same state transitions as for true elements.
176 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
177
178 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
179 /// define a state machine that triggers for ranges of values that the index
180 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
181 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
182 /// index in the range (inclusive). We use -2 for undefined here because we
183 /// use relative comparisons and don't want 0-1 to match -1.
184 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
185
186 // MagicBitvector - This is a magic bitvector where we set a bit if the
187 // comparison is true for element 'i'. If there are 64 elements or less in
188 // the array, this will fully represent all the comparison results.
189 uint64_t MagicBitvector = 0;
190
191 // Scan the array and see if one of our patterns matches.
192 Constant *CompareRHS = cast<Constant>(Val: ICI.getOperand(i_nocapture: 1));
193 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
194 Constant *Elt = Init->getAggregateElement(Elt: i);
195 if (!Elt)
196 return nullptr;
197
198 // If this is indexing an array of structures, get the structure element.
199 if (!LaterIndices.empty()) {
200 Elt = ConstantFoldExtractValueInstruction(Agg: Elt, Idxs: LaterIndices);
201 if (!Elt)
202 return nullptr;
203 }
204
205 // If the element is masked, handle it.
206 if (AndCst) {
207 Elt = ConstantFoldBinaryOpOperands(Opcode: Instruction::And, LHS: Elt, RHS: AndCst, DL);
208 if (!Elt)
209 return nullptr;
210 }
211
212 // Find out if the comparison would be true or false for the i'th element.
213 Constant *C = ConstantFoldCompareInstOperands(Predicate: ICI.getPredicate(), LHS: Elt,
214 RHS: CompareRHS, DL, TLI: &TLI);
215 if (!C)
216 return nullptr;
217
218 // If the result is undef for this element, ignore it.
219 if (isa<UndefValue>(Val: C)) {
220 // Extend range state machines to cover this element in case there is an
221 // undef in the middle of the range.
222 if (TrueRangeEnd == (int)i - 1)
223 TrueRangeEnd = i;
224 if (FalseRangeEnd == (int)i - 1)
225 FalseRangeEnd = i;
226 continue;
227 }
228
229 // If we can't compute the result for any of the elements, we have to give
230 // up evaluating the entire conditional.
231 if (!isa<ConstantInt>(Val: C))
232 return nullptr;
233
234 // Otherwise, we know if the comparison is true or false for this element,
235 // update our state machines.
236 bool IsTrueForElt = !cast<ConstantInt>(Val: C)->isZero();
237
238 // State machine for single/double/range index comparison.
239 if (IsTrueForElt) {
240 // Update the TrueElement state machine.
241 if (FirstTrueElement == Undefined)
242 FirstTrueElement = TrueRangeEnd = i; // First true element.
243 else {
244 // Update double-compare state machine.
245 if (SecondTrueElement == Undefined)
246 SecondTrueElement = i;
247 else
248 SecondTrueElement = Overdefined;
249
250 // Update range state machine.
251 if (TrueRangeEnd == (int)i - 1)
252 TrueRangeEnd = i;
253 else
254 TrueRangeEnd = Overdefined;
255 }
256 } else {
257 // Update the FalseElement state machine.
258 if (FirstFalseElement == Undefined)
259 FirstFalseElement = FalseRangeEnd = i; // First false element.
260 else {
261 // Update double-compare state machine.
262 if (SecondFalseElement == Undefined)
263 SecondFalseElement = i;
264 else
265 SecondFalseElement = Overdefined;
266
267 // Update range state machine.
268 if (FalseRangeEnd == (int)i - 1)
269 FalseRangeEnd = i;
270 else
271 FalseRangeEnd = Overdefined;
272 }
273 }
274
275 // If this element is in range, update our magic bitvector.
276 if (i < 64 && IsTrueForElt)
277 MagicBitvector |= 1ULL << i;
278
279 // If all of our states become overdefined, bail out early. Since the
280 // predicate is expensive, only check it every 8 elements. This is only
281 // really useful for really huge arrays.
282 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
283 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
284 FalseRangeEnd == Overdefined)
285 return nullptr;
286 }
287
288 // Now that we've scanned the entire array, emit our new comparison(s). We
289 // order the state machines in complexity of the generated code.
290 Value *Idx = GEP->getOperand(i_nocapture: 2);
291
292 // If the index is larger than the pointer offset size of the target, truncate
293 // the index down like the GEP would do implicitly. We don't have to do this
294 // for an inbounds GEP because the index can't be out of range.
295 if (!GEP->isInBounds()) {
296 Type *PtrIdxTy = DL.getIndexType(PtrTy: GEP->getType());
297 unsigned OffsetSize = PtrIdxTy->getIntegerBitWidth();
298 if (Idx->getType()->getPrimitiveSizeInBits().getFixedValue() > OffsetSize)
299 Idx = Builder.CreateTrunc(V: Idx, DestTy: PtrIdxTy);
300 }
301
302 // If inbounds keyword is not present, Idx * ElementSize can overflow.
303 // Let's assume that ElementSize is 2 and the wanted value is at offset 0.
304 // Then, there are two possible values for Idx to match offset 0:
305 // 0x00..00, 0x80..00.
306 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
307 // comparison is false if Idx was 0x80..00.
308 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
309 unsigned ElementSize =
310 DL.getTypeAllocSize(Ty: Init->getType()->getArrayElementType());
311 auto MaskIdx = [&](Value *Idx) {
312 if (!GEP->isInBounds() && llvm::countr_zero(Val: ElementSize) != 0) {
313 Value *Mask = Constant::getAllOnesValue(Ty: Idx->getType());
314 Mask = Builder.CreateLShr(LHS: Mask, RHS: llvm::countr_zero(Val: ElementSize));
315 Idx = Builder.CreateAnd(LHS: Idx, RHS: Mask);
316 }
317 return Idx;
318 };
319
320 // If the comparison is only true for one or two elements, emit direct
321 // comparisons.
322 if (SecondTrueElement != Overdefined) {
323 Idx = MaskIdx(Idx);
324 // None true -> false.
325 if (FirstTrueElement == Undefined)
326 return replaceInstUsesWith(I&: ICI, V: Builder.getFalse());
327
328 Value *FirstTrueIdx = ConstantInt::get(Ty: Idx->getType(), V: FirstTrueElement);
329
330 // True for one element -> 'i == 47'.
331 if (SecondTrueElement == Undefined)
332 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
333
334 // True for two elements -> 'i == 47 | i == 72'.
335 Value *C1 = Builder.CreateICmpEQ(LHS: Idx, RHS: FirstTrueIdx);
336 Value *SecondTrueIdx = ConstantInt::get(Ty: Idx->getType(), V: SecondTrueElement);
337 Value *C2 = Builder.CreateICmpEQ(LHS: Idx, RHS: SecondTrueIdx);
338 return BinaryOperator::CreateOr(V1: C1, V2: C2);
339 }
340
341 // If the comparison is only false for one or two elements, emit direct
342 // comparisons.
343 if (SecondFalseElement != Overdefined) {
344 Idx = MaskIdx(Idx);
345 // None false -> true.
346 if (FirstFalseElement == Undefined)
347 return replaceInstUsesWith(I&: ICI, V: Builder.getTrue());
348
349 Value *FirstFalseIdx = ConstantInt::get(Ty: Idx->getType(), V: FirstFalseElement);
350
351 // False for one element -> 'i != 47'.
352 if (SecondFalseElement == Undefined)
353 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
354
355 // False for two elements -> 'i != 47 & i != 72'.
356 Value *C1 = Builder.CreateICmpNE(LHS: Idx, RHS: FirstFalseIdx);
357 Value *SecondFalseIdx =
358 ConstantInt::get(Ty: Idx->getType(), V: SecondFalseElement);
359 Value *C2 = Builder.CreateICmpNE(LHS: Idx, RHS: SecondFalseIdx);
360 return BinaryOperator::CreateAnd(V1: C1, V2: C2);
361 }
362
363 // If the comparison can be replaced with a range comparison for the elements
364 // where it is true, emit the range check.
365 if (TrueRangeEnd != Overdefined) {
366 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
367 Idx = MaskIdx(Idx);
368
369 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
370 if (FirstTrueElement) {
371 Value *Offs = ConstantInt::get(Ty: Idx->getType(), V: -FirstTrueElement);
372 Idx = Builder.CreateAdd(LHS: Idx, RHS: Offs);
373 }
374
375 Value *End =
376 ConstantInt::get(Ty: Idx->getType(), V: TrueRangeEnd - FirstTrueElement + 1);
377 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
378 }
379
380 // False range check.
381 if (FalseRangeEnd != Overdefined) {
382 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
383 Idx = MaskIdx(Idx);
384 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
385 if (FirstFalseElement) {
386 Value *Offs = ConstantInt::get(Ty: Idx->getType(), V: -FirstFalseElement);
387 Idx = Builder.CreateAdd(LHS: Idx, RHS: Offs);
388 }
389
390 Value *End =
391 ConstantInt::get(Ty: Idx->getType(), V: FalseRangeEnd - FirstFalseElement);
392 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
393 }
394
395 // If a magic bitvector captures the entire comparison state
396 // of this load, replace it with computation that does:
397 // ((magic_cst >> i) & 1) != 0
398 {
399 Type *Ty = nullptr;
400
401 // Look for an appropriate type:
402 // - The type of Idx if the magic fits
403 // - The smallest fitting legal type
404 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
405 Ty = Idx->getType();
406 else
407 Ty = DL.getSmallestLegalIntType(C&: Init->getContext(), Width: ArrayElementCount);
408
409 if (Ty) {
410 Idx = MaskIdx(Idx);
411 Value *V = Builder.CreateIntCast(V: Idx, DestTy: Ty, isSigned: false);
412 V = Builder.CreateLShr(LHS: ConstantInt::get(Ty, V: MagicBitvector), RHS: V);
413 V = Builder.CreateAnd(LHS: ConstantInt::get(Ty, V: 1), RHS: V);
414 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, V: 0));
415 }
416 }
417
418 return nullptr;
419}
420
421/// Returns true if we can rewrite Start as a GEP with pointer Base
422/// and some integer offset. The nodes that need to be re-written
423/// for this transformation will be added to Explored.
424static bool canRewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags &NW,
425 const DataLayout &DL,
426 SetVector<Value *> &Explored) {
427 SmallVector<Value *, 16> WorkList(1, Start);
428 Explored.insert(X: Base);
429
430 // The following traversal gives us an order which can be used
431 // when doing the final transformation. Since in the final
432 // transformation we create the PHI replacement instructions first,
433 // we don't have to get them in any particular order.
434 //
435 // However, for other instructions we will have to traverse the
436 // operands of an instruction first, which means that we have to
437 // do a post-order traversal.
438 while (!WorkList.empty()) {
439 SetVector<PHINode *> PHIs;
440
441 while (!WorkList.empty()) {
442 if (Explored.size() >= 100)
443 return false;
444
445 Value *V = WorkList.back();
446
447 if (Explored.contains(key: V)) {
448 WorkList.pop_back();
449 continue;
450 }
451
452 if (!isa<GetElementPtrInst>(Val: V) && !isa<PHINode>(Val: V))
453 // We've found some value that we can't explore which is different from
454 // the base. Therefore we can't do this transformation.
455 return false;
456
457 if (auto *GEP = dyn_cast<GEPOperator>(Val: V)) {
458 // Only allow inbounds GEPs with at most one variable offset.
459 auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(Val: V); };
460 if (!GEP->isInBounds() || count_if(Range: GEP->indices(), P: IsNonConst) > 1)
461 return false;
462
463 NW = NW.intersectForOffsetAdd(Other: GEP->getNoWrapFlags());
464 if (!Explored.contains(key: GEP->getOperand(i_nocapture: 0)))
465 WorkList.push_back(Elt: GEP->getOperand(i_nocapture: 0));
466 }
467
468 if (WorkList.back() == V) {
469 WorkList.pop_back();
470 // We've finished visiting this node, mark it as such.
471 Explored.insert(X: V);
472 }
473
474 if (auto *PN = dyn_cast<PHINode>(Val: V)) {
475 // We cannot transform PHIs on unsplittable basic blocks.
476 if (isa<CatchSwitchInst>(Val: PN->getParent()->getTerminator()))
477 return false;
478 Explored.insert(X: PN);
479 PHIs.insert(X: PN);
480 }
481 }
482
483 // Explore the PHI nodes further.
484 for (auto *PN : PHIs)
485 for (Value *Op : PN->incoming_values())
486 if (!Explored.contains(key: Op))
487 WorkList.push_back(Elt: Op);
488 }
489
490 // Make sure that we can do this. Since we can't insert GEPs in a basic
491 // block before a PHI node, we can't easily do this transformation if
492 // we have PHI node users of transformed instructions.
493 for (Value *Val : Explored) {
494 for (Value *Use : Val->uses()) {
495
496 auto *PHI = dyn_cast<PHINode>(Val: Use);
497 auto *Inst = dyn_cast<Instruction>(Val);
498
499 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
500 !Explored.contains(key: PHI))
501 continue;
502
503 if (PHI->getParent() == Inst->getParent())
504 return false;
505 }
506 }
507 return true;
508}
509
510// Sets the appropriate insert point on Builder where we can add
511// a replacement Instruction for V (if that is possible).
512static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
513 bool Before = true) {
514 if (auto *PHI = dyn_cast<PHINode>(Val: V)) {
515 BasicBlock *Parent = PHI->getParent();
516 Builder.SetInsertPoint(TheBB: Parent, IP: Parent->getFirstInsertionPt());
517 return;
518 }
519 if (auto *I = dyn_cast<Instruction>(Val: V)) {
520 if (!Before)
521 I = &*std::next(x: I->getIterator());
522 Builder.SetInsertPoint(I);
523 return;
524 }
525 if (auto *A = dyn_cast<Argument>(Val: V)) {
526 // Set the insertion point in the entry block.
527 BasicBlock &Entry = A->getParent()->getEntryBlock();
528 Builder.SetInsertPoint(TheBB: &Entry, IP: Entry.getFirstInsertionPt());
529 return;
530 }
531 // Otherwise, this is a constant and we don't need to set a new
532 // insertion point.
533 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
534}
535
536/// Returns a re-written value of Start as an indexed GEP using Base as a
537/// pointer.
538static Value *rewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags NW,
539 const DataLayout &DL,
540 SetVector<Value *> &Explored,
541 InstCombiner &IC) {
542 // Perform all the substitutions. This is a bit tricky because we can
543 // have cycles in our use-def chains.
544 // 1. Create the PHI nodes without any incoming values.
545 // 2. Create all the other values.
546 // 3. Add the edges for the PHI nodes.
547 // 4. Emit GEPs to get the original pointers.
548 // 5. Remove the original instructions.
549 Type *IndexType = IntegerType::get(
550 C&: Base->getContext(), NumBits: DL.getIndexTypeSizeInBits(Ty: Start->getType()));
551
552 DenseMap<Value *, Value *> NewInsts;
553 NewInsts[Base] = ConstantInt::getNullValue(Ty: IndexType);
554
555 // Create the new PHI nodes, without adding any incoming values.
556 for (Value *Val : Explored) {
557 if (Val == Base)
558 continue;
559 // Create empty phi nodes. This avoids cyclic dependencies when creating
560 // the remaining instructions.
561 if (auto *PHI = dyn_cast<PHINode>(Val))
562 NewInsts[PHI] =
563 PHINode::Create(Ty: IndexType, NumReservedValues: PHI->getNumIncomingValues(),
564 NameStr: PHI->getName() + ".idx", InsertBefore: PHI->getIterator());
565 }
566 IRBuilder<> Builder(Base->getContext());
567
568 // Create all the other instructions.
569 for (Value *Val : Explored) {
570 if (NewInsts.contains(Val))
571 continue;
572
573 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
574 setInsertionPoint(Builder, V: GEP);
575 Value *Op = NewInsts[GEP->getOperand(i_nocapture: 0)];
576 Value *OffsetV = emitGEPOffset(Builder: &Builder, DL, GEP);
577 if (isa<ConstantInt>(Val: Op) && cast<ConstantInt>(Val: Op)->isZero())
578 NewInsts[GEP] = OffsetV;
579 else
580 NewInsts[GEP] = Builder.CreateAdd(
581 LHS: Op, RHS: OffsetV, Name: GEP->getOperand(i_nocapture: 0)->getName() + ".add",
582 /*NUW=*/HasNUW: NW.hasNoUnsignedWrap(),
583 /*NSW=*/HasNSW: NW.hasNoUnsignedSignedWrap());
584 continue;
585 }
586 if (isa<PHINode>(Val))
587 continue;
588
589 llvm_unreachable("Unexpected instruction type");
590 }
591
592 // Add the incoming values to the PHI nodes.
593 for (Value *Val : Explored) {
594 if (Val == Base)
595 continue;
596 // All the instructions have been created, we can now add edges to the
597 // phi nodes.
598 if (auto *PHI = dyn_cast<PHINode>(Val)) {
599 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
600 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
601 Value *NewIncoming = PHI->getIncomingValue(i: I);
602
603 auto It = NewInsts.find(Val: NewIncoming);
604 if (It != NewInsts.end())
605 NewIncoming = It->second;
606
607 NewPhi->addIncoming(V: NewIncoming, BB: PHI->getIncomingBlock(i: I));
608 }
609 }
610 }
611
612 for (Value *Val : Explored) {
613 if (Val == Base)
614 continue;
615
616 setInsertionPoint(Builder, V: Val, Before: false);
617 // Create GEP for external users.
618 Value *NewVal = Builder.CreateGEP(Ty: Builder.getInt8Ty(), Ptr: Base, IdxList: NewInsts[Val],
619 Name: Val->getName() + ".ptr", NW);
620 IC.replaceInstUsesWith(I&: *cast<Instruction>(Val), V: NewVal);
621 // Add old instruction to worklist for DCE. We don't directly remove it
622 // here because the original compare is one of the users.
623 IC.addToWorklist(I: cast<Instruction>(Val));
624 }
625
626 return NewInsts[Start];
627}
628
629/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
630/// We can look through PHIs, GEPs and casts in order to determine a common base
631/// between GEPLHS and RHS.
632static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
633 CmpPredicate Cond,
634 const DataLayout &DL,
635 InstCombiner &IC) {
636 // FIXME: Support vector of pointers.
637 if (GEPLHS->getType()->isVectorTy())
638 return nullptr;
639
640 if (!GEPLHS->hasAllConstantIndices())
641 return nullptr;
642
643 APInt Offset(DL.getIndexTypeSizeInBits(Ty: GEPLHS->getType()), 0);
644 Value *PtrBase =
645 GEPLHS->stripAndAccumulateConstantOffsets(DL, Offset,
646 /*AllowNonInbounds*/ false);
647
648 // Bail if we looked through addrspacecast.
649 if (PtrBase->getType() != GEPLHS->getType())
650 return nullptr;
651
652 // The set of nodes that will take part in this transformation.
653 SetVector<Value *> Nodes;
654 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags();
655 if (!canRewriteGEPAsOffset(Start: RHS, Base: PtrBase, NW, DL, Explored&: Nodes))
656 return nullptr;
657
658 // We know we can re-write this as
659 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
660 // Since we've only looked through inbouds GEPs we know that we
661 // can't have overflow on either side. We can therefore re-write
662 // this as:
663 // OFFSET1 cmp OFFSET2
664 Value *NewRHS = rewriteGEPAsOffset(Start: RHS, Base: PtrBase, NW, DL, Explored&: Nodes, IC);
665
666 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
667 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
668 // offset. Since Index is the offset of LHS to the base pointer, we will now
669 // compare the offsets instead of comparing the pointers.
670 return new ICmpInst(ICmpInst::getSignedPredicate(Pred: Cond),
671 IC.Builder.getInt(AI: Offset), NewRHS);
672}
673
674/// Fold comparisons between a GEP instruction and something else. At this point
675/// we know that the GEP is on the LHS of the comparison.
676Instruction *InstCombinerImpl::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
677 CmpPredicate Cond, Instruction &I) {
678 // Don't transform signed compares of GEPs into index compares. Even if the
679 // GEP is inbounds, the final add of the base pointer can have signed overflow
680 // and would change the result of the icmp.
681 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
682 // the maximum signed value for the pointer type.
683 if (ICmpInst::isSigned(predicate: Cond))
684 return nullptr;
685
686 // Look through bitcasts and addrspacecasts. We do not however want to remove
687 // 0 GEPs.
688 if (!isa<GetElementPtrInst>(Val: RHS))
689 RHS = RHS->stripPointerCasts();
690
691 auto CanFold = [Cond](GEPNoWrapFlags NW) {
692 if (ICmpInst::isEquality(P: Cond))
693 return true;
694
695 // Unsigned predicates can be folded if the GEPs have *any* nowrap flags.
696 assert(ICmpInst::isUnsigned(Cond));
697 return NW != GEPNoWrapFlags::none();
698 };
699
700 auto NewICmp = [Cond](GEPNoWrapFlags NW, Value *Op1, Value *Op2) {
701 if (!NW.hasNoUnsignedWrap()) {
702 // Convert signed to unsigned comparison.
703 return new ICmpInst(ICmpInst::getSignedPredicate(Pred: Cond), Op1, Op2);
704 }
705
706 auto *I = new ICmpInst(Cond, Op1, Op2);
707 I->setSameSign(NW.hasNoUnsignedSignedWrap());
708 return I;
709 };
710
711 CommonPointerBase Base = CommonPointerBase::compute(LHS: GEPLHS, RHS);
712 if (Base.Ptr == RHS && CanFold(Base.LHSNW)) {
713 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
714 Type *IdxTy = DL.getIndexType(PtrTy: GEPLHS->getType());
715 Value *Offset =
716 EmitGEPOffsets(GEPs: Base.LHSGEPs, NW: Base.LHSNW, IdxTy, /*RewriteGEPs=*/true);
717 return NewICmp(Base.LHSNW, Offset,
718 Constant::getNullValue(Ty: Offset->getType()));
719 }
720
721 if (GEPLHS->isInBounds() && ICmpInst::isEquality(P: Cond) &&
722 isa<Constant>(Val: RHS) && cast<Constant>(Val: RHS)->isNullValue() &&
723 !NullPointerIsDefined(F: I.getFunction(),
724 AS: RHS->getType()->getPointerAddressSpace())) {
725 // For most address spaces, an allocation can't be placed at null, but null
726 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
727 // the only valid inbounds address derived from null, is null itself.
728 // Thus, we have four cases to consider:
729 // 1) Base == nullptr, Offset == 0 -> inbounds, null
730 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
731 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
732 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
733 //
734 // (Note if we're indexing a type of size 0, that simply collapses into one
735 // of the buckets above.)
736 //
737 // In general, we're allowed to make values less poison (i.e. remove
738 // sources of full UB), so in this case, we just select between the two
739 // non-poison cases (1 and 4 above).
740 //
741 // For vectors, we apply the same reasoning on a per-lane basis.
742 auto *Base = GEPLHS->getPointerOperand();
743 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
744 auto EC = cast<VectorType>(Val: GEPLHS->getType())->getElementCount();
745 Base = Builder.CreateVectorSplat(EC, V: Base);
746 }
747 return new ICmpInst(Cond, Base,
748 ConstantExpr::getPointerBitCastOrAddrSpaceCast(
749 C: cast<Constant>(Val: RHS), Ty: Base->getType()));
750 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(Val: RHS)) {
751 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags() & GEPRHS->getNoWrapFlags();
752
753 // If the base pointers are different, but the indices are the same, just
754 // compare the base pointer.
755 Value *PtrBase = GEPLHS->getOperand(i_nocapture: 0);
756 if (PtrBase != GEPRHS->getOperand(i_nocapture: 0)) {
757 bool IndicesTheSame =
758 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
759 GEPLHS->getPointerOperand()->getType() ==
760 GEPRHS->getPointerOperand()->getType() &&
761 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
762 if (IndicesTheSame)
763 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
764 if (GEPLHS->getOperand(i_nocapture: i) != GEPRHS->getOperand(i_nocapture: i)) {
765 IndicesTheSame = false;
766 break;
767 }
768
769 // If all indices are the same, just compare the base pointers.
770 Type *BaseType = GEPLHS->getOperand(i_nocapture: 0)->getType();
771 if (IndicesTheSame &&
772 CmpInst::makeCmpResultType(opnd_type: BaseType) == I.getType() && CanFold(NW))
773 return new ICmpInst(Cond, GEPLHS->getOperand(i_nocapture: 0), GEPRHS->getOperand(i_nocapture: 0));
774
775 // If we're comparing GEPs with two base pointers that only differ in type
776 // and both GEPs have only constant indices or just one use, then fold
777 // the compare with the adjusted indices.
778 // FIXME: Support vector of pointers.
779 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
780 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
781 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
782 PtrBase->stripPointerCasts() ==
783 GEPRHS->getOperand(i_nocapture: 0)->stripPointerCasts() &&
784 !GEPLHS->getType()->isVectorTy()) {
785 Value *LOffset = EmitGEPOffset(GEP: GEPLHS);
786 Value *ROffset = EmitGEPOffset(GEP: GEPRHS);
787
788 // If we looked through an addrspacecast between different sized address
789 // spaces, the LHS and RHS pointers are different sized
790 // integers. Truncate to the smaller one.
791 Type *LHSIndexTy = LOffset->getType();
792 Type *RHSIndexTy = ROffset->getType();
793 if (LHSIndexTy != RHSIndexTy) {
794 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
795 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
796 ROffset = Builder.CreateTrunc(V: ROffset, DestTy: LHSIndexTy);
797 } else
798 LOffset = Builder.CreateTrunc(V: LOffset, DestTy: RHSIndexTy);
799 }
800
801 Value *Cmp = Builder.CreateICmp(P: ICmpInst::getSignedPredicate(Pred: Cond),
802 LHS: LOffset, RHS: ROffset);
803 return replaceInstUsesWith(I, V: Cmp);
804 }
805
806 // Otherwise, the base pointers are different and the indices are
807 // different. Try convert this to an indexed compare by looking through
808 // PHIs/casts.
809 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, IC&: *this);
810 }
811
812 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
813 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
814 // If the GEPs only differ by one index, compare it.
815 unsigned NumDifferences = 0; // Keep track of # differences.
816 unsigned DiffOperand = 0; // The operand that differs.
817 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
818 if (GEPLHS->getOperand(i_nocapture: i) != GEPRHS->getOperand(i_nocapture: i)) {
819 Type *LHSType = GEPLHS->getOperand(i_nocapture: i)->getType();
820 Type *RHSType = GEPRHS->getOperand(i_nocapture: i)->getType();
821 // FIXME: Better support for vector of pointers.
822 if (LHSType->getPrimitiveSizeInBits() !=
823 RHSType->getPrimitiveSizeInBits() ||
824 (GEPLHS->getType()->isVectorTy() &&
825 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
826 // Irreconcilable differences.
827 NumDifferences = 2;
828 break;
829 }
830
831 if (NumDifferences++)
832 break;
833 DiffOperand = i;
834 }
835
836 if (NumDifferences == 0) // SAME GEP?
837 return replaceInstUsesWith(
838 I, // No comparison is needed here.
839 V: ConstantInt::get(Ty: I.getType(), V: ICmpInst::isTrueWhenEqual(predicate: Cond)));
840 // If two GEPs only differ by an index, compare them.
841 // Note that nowrap flags are always needed when comparing two indices.
842 else if (NumDifferences == 1 && NW != GEPNoWrapFlags::none()) {
843 Value *LHSV = GEPLHS->getOperand(i_nocapture: DiffOperand);
844 Value *RHSV = GEPRHS->getOperand(i_nocapture: DiffOperand);
845 return NewICmp(NW, LHSV, RHSV);
846 }
847 }
848
849 if (CanFold(NW)) {
850 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
851 Value *L = EmitGEPOffset(GEP: GEPLHS, /*RewriteGEP=*/true);
852 Value *R = EmitGEPOffset(GEP: GEPRHS, /*RewriteGEP=*/true);
853 return NewICmp(NW, L, R);
854 }
855 }
856
857 // Try convert this to an indexed compare by looking through PHIs/casts as a
858 // last resort.
859 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, IC&: *this);
860}
861
862bool InstCombinerImpl::foldAllocaCmp(AllocaInst *Alloca) {
863 // It would be tempting to fold away comparisons between allocas and any
864 // pointer not based on that alloca (e.g. an argument). However, even
865 // though such pointers cannot alias, they can still compare equal.
866 //
867 // But LLVM doesn't specify where allocas get their memory, so if the alloca
868 // doesn't escape we can argue that it's impossible to guess its value, and we
869 // can therefore act as if any such guesses are wrong.
870 //
871 // However, we need to ensure that this folding is consistent: We can't fold
872 // one comparison to false, and then leave a different comparison against the
873 // same value alone (as it might evaluate to true at runtime, leading to a
874 // contradiction). As such, this code ensures that all comparisons are folded
875 // at the same time, and there are no other escapes.
876
877 struct CmpCaptureTracker : public CaptureTracker {
878 AllocaInst *Alloca;
879 bool Captured = false;
880 /// The value of the map is a bit mask of which icmp operands the alloca is
881 /// used in.
882 SmallMapVector<ICmpInst *, unsigned, 4> ICmps;
883
884 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
885
886 void tooManyUses() override { Captured = true; }
887
888 Action captured(const Use *U, UseCaptureInfo CI) override {
889 // TODO(captures): Use UseCaptureInfo.
890 auto *ICmp = dyn_cast<ICmpInst>(Val: U->getUser());
891 // We need to check that U is based *only* on the alloca, and doesn't
892 // have other contributions from a select/phi operand.
893 // TODO: We could check whether getUnderlyingObjects() reduces to one
894 // object, which would allow looking through phi nodes.
895 if (ICmp && ICmp->isEquality() && getUnderlyingObject(V: *U) == Alloca) {
896 // Collect equality icmps of the alloca, and don't treat them as
897 // captures.
898 ICmps[ICmp] |= 1u << U->getOperandNo();
899 return Continue;
900 }
901
902 Captured = true;
903 return Stop;
904 }
905 };
906
907 CmpCaptureTracker Tracker(Alloca);
908 PointerMayBeCaptured(V: Alloca, Tracker: &Tracker);
909 if (Tracker.Captured)
910 return false;
911
912 bool Changed = false;
913 for (auto [ICmp, Operands] : Tracker.ICmps) {
914 switch (Operands) {
915 case 1:
916 case 2: {
917 // The alloca is only used in one icmp operand. Assume that the
918 // equality is false.
919 auto *Res = ConstantInt::get(Ty: ICmp->getType(),
920 V: ICmp->getPredicate() == ICmpInst::ICMP_NE);
921 replaceInstUsesWith(I&: *ICmp, V: Res);
922 eraseInstFromFunction(I&: *ICmp);
923 Changed = true;
924 break;
925 }
926 case 3:
927 // Both icmp operands are based on the alloca, so this is comparing
928 // pointer offsets, without leaking any information about the address
929 // of the alloca. Ignore such comparisons.
930 break;
931 default:
932 llvm_unreachable("Cannot happen");
933 }
934 }
935
936 return Changed;
937}
938
939/// Fold "icmp pred (X+C), X".
940Instruction *InstCombinerImpl::foldICmpAddOpConst(Value *X, const APInt &C,
941 CmpPredicate Pred) {
942 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
943 // so the values can never be equal. Similarly for all other "or equals"
944 // operators.
945 assert(!!C && "C should not be zero!");
946
947 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
948 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
949 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
950 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
951 Constant *R =
952 ConstantInt::get(Ty: X->getType(), V: APInt::getMaxValue(numBits: C.getBitWidth()) - C);
953 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
954 }
955
956 // (X+1) >u X --> X <u (0-1) --> X != 255
957 // (X+2) >u X --> X <u (0-2) --> X <u 254
958 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
959 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
960 return new ICmpInst(ICmpInst::ICMP_ULT, X,
961 ConstantInt::get(Ty: X->getType(), V: -C));
962
963 APInt SMax = APInt::getSignedMaxValue(numBits: C.getBitWidth());
964
965 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
966 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
967 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
968 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
969 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
970 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
971 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
972 return new ICmpInst(ICmpInst::ICMP_SGT, X,
973 ConstantInt::get(Ty: X->getType(), V: SMax - C));
974
975 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
976 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
977 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
978 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
979 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
980 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
981
982 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
983 return new ICmpInst(ICmpInst::ICMP_SLT, X,
984 ConstantInt::get(Ty: X->getType(), V: SMax - (C - 1)));
985}
986
987/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
988/// (icmp eq/ne A, Log2(AP2/AP1)) ->
989/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
990Instruction *InstCombinerImpl::foldICmpShrConstConst(ICmpInst &I, Value *A,
991 const APInt &AP1,
992 const APInt &AP2) {
993 assert(I.isEquality() && "Cannot fold icmp gt/lt");
994
995 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
996 if (I.getPredicate() == I.ICMP_NE)
997 Pred = CmpInst::getInversePredicate(pred: Pred);
998 return new ICmpInst(Pred, LHS, RHS);
999 };
1000
1001 // Don't bother doing any work for cases which InstSimplify handles.
1002 if (AP2.isZero())
1003 return nullptr;
1004
1005 bool IsAShr = isa<AShrOperator>(Val: I.getOperand(i_nocapture: 0));
1006 if (IsAShr) {
1007 if (AP2.isAllOnes())
1008 return nullptr;
1009 if (AP2.isNegative() != AP1.isNegative())
1010 return nullptr;
1011 if (AP2.sgt(RHS: AP1))
1012 return nullptr;
1013 }
1014
1015 if (!AP1)
1016 // 'A' must be large enough to shift out the highest set bit.
1017 return getICmp(I.ICMP_UGT, A,
1018 ConstantInt::get(Ty: A->getType(), V: AP2.logBase2()));
1019
1020 if (AP1 == AP2)
1021 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(Ty: A->getType()));
1022
1023 int Shift;
1024 if (IsAShr && AP1.isNegative())
1025 Shift = AP1.countl_one() - AP2.countl_one();
1026 else
1027 Shift = AP1.countl_zero() - AP2.countl_zero();
1028
1029 if (Shift > 0) {
1030 if (IsAShr && AP1 == AP2.ashr(ShiftAmt: Shift)) {
1031 // There are multiple solutions if we are comparing against -1 and the LHS
1032 // of the ashr is not a power of two.
1033 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1034 return getICmp(I.ICMP_UGE, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1035 return getICmp(I.ICMP_EQ, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1036 } else if (AP1 == AP2.lshr(shiftAmt: Shift)) {
1037 return getICmp(I.ICMP_EQ, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1038 }
1039 }
1040
1041 // Shifting const2 will never be equal to const1.
1042 // FIXME: This should always be handled by InstSimplify?
1043 auto *TorF = ConstantInt::get(Ty: I.getType(), V: I.getPredicate() == I.ICMP_NE);
1044 return replaceInstUsesWith(I, V: TorF);
1045}
1046
1047/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1048/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1049Instruction *InstCombinerImpl::foldICmpShlConstConst(ICmpInst &I, Value *A,
1050 const APInt &AP1,
1051 const APInt &AP2) {
1052 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1053
1054 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1055 if (I.getPredicate() == I.ICMP_NE)
1056 Pred = CmpInst::getInversePredicate(pred: Pred);
1057 return new ICmpInst(Pred, LHS, RHS);
1058 };
1059
1060 // Don't bother doing any work for cases which InstSimplify handles.
1061 if (AP2.isZero())
1062 return nullptr;
1063
1064 unsigned AP2TrailingZeros = AP2.countr_zero();
1065
1066 if (!AP1 && AP2TrailingZeros != 0)
1067 return getICmp(
1068 I.ICMP_UGE, A,
1069 ConstantInt::get(Ty: A->getType(), V: AP2.getBitWidth() - AP2TrailingZeros));
1070
1071 if (AP1 == AP2)
1072 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(Ty: A->getType()));
1073
1074 // Get the distance between the lowest bits that are set.
1075 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1076
1077 if (Shift > 0 && AP2.shl(shiftAmt: Shift) == AP1)
1078 return getICmp(I.ICMP_EQ, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1079
1080 // Shifting const2 will never be equal to const1.
1081 // FIXME: This should always be handled by InstSimplify?
1082 auto *TorF = ConstantInt::get(Ty: I.getType(), V: I.getPredicate() == I.ICMP_NE);
1083 return replaceInstUsesWith(I, V: TorF);
1084}
1085
1086/// The caller has matched a pattern of the form:
1087/// I = icmp ugt (add (add A, B), CI2), CI1
1088/// If this is of the form:
1089/// sum = a + b
1090/// if (sum+128 >u 255)
1091/// Then replace it with llvm.sadd.with.overflow.i8.
1092///
1093static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1094 ConstantInt *CI2, ConstantInt *CI1,
1095 InstCombinerImpl &IC) {
1096 // The transformation we're trying to do here is to transform this into an
1097 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1098 // with a narrower add, and discard the add-with-constant that is part of the
1099 // range check (if we can't eliminate it, this isn't profitable).
1100
1101 // In order to eliminate the add-with-constant, the compare can be its only
1102 // use.
1103 Instruction *AddWithCst = cast<Instruction>(Val: I.getOperand(i_nocapture: 0));
1104 if (!AddWithCst->hasOneUse())
1105 return nullptr;
1106
1107 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1108 if (!CI2->getValue().isPowerOf2())
1109 return nullptr;
1110 unsigned NewWidth = CI2->getValue().countr_zero();
1111 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1112 return nullptr;
1113
1114 // The width of the new add formed is 1 more than the bias.
1115 ++NewWidth;
1116
1117 // Check to see that CI1 is an all-ones value with NewWidth bits.
1118 if (CI1->getBitWidth() == NewWidth ||
1119 CI1->getValue() != APInt::getLowBitsSet(numBits: CI1->getBitWidth(), loBitsSet: NewWidth))
1120 return nullptr;
1121
1122 // This is only really a signed overflow check if the inputs have been
1123 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1124 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1125 if (IC.ComputeMaxSignificantBits(Op: A, CxtI: &I) > NewWidth ||
1126 IC.ComputeMaxSignificantBits(Op: B, CxtI: &I) > NewWidth)
1127 return nullptr;
1128
1129 // In order to replace the original add with a narrower
1130 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1131 // and truncates that discard the high bits of the add. Verify that this is
1132 // the case.
1133 Instruction *OrigAdd = cast<Instruction>(Val: AddWithCst->getOperand(i: 0));
1134 for (User *U : OrigAdd->users()) {
1135 if (U == AddWithCst)
1136 continue;
1137
1138 // Only accept truncates for now. We would really like a nice recursive
1139 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1140 // chain to see which bits of a value are actually demanded. If the
1141 // original add had another add which was then immediately truncated, we
1142 // could still do the transformation.
1143 TruncInst *TI = dyn_cast<TruncInst>(Val: U);
1144 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1145 return nullptr;
1146 }
1147
1148 // If the pattern matches, truncate the inputs to the narrower type and
1149 // use the sadd_with_overflow intrinsic to efficiently compute both the
1150 // result and the overflow bit.
1151 Type *NewType = IntegerType::get(C&: OrigAdd->getContext(), NumBits: NewWidth);
1152 Function *F = Intrinsic::getOrInsertDeclaration(
1153 M: I.getModule(), id: Intrinsic::sadd_with_overflow, Tys: NewType);
1154
1155 InstCombiner::BuilderTy &Builder = IC.Builder;
1156
1157 // Put the new code above the original add, in case there are any uses of the
1158 // add between the add and the compare.
1159 Builder.SetInsertPoint(OrigAdd);
1160
1161 Value *TruncA = Builder.CreateTrunc(V: A, DestTy: NewType, Name: A->getName() + ".trunc");
1162 Value *TruncB = Builder.CreateTrunc(V: B, DestTy: NewType, Name: B->getName() + ".trunc");
1163 CallInst *Call = Builder.CreateCall(Callee: F, Args: {TruncA, TruncB}, Name: "sadd");
1164 Value *Add = Builder.CreateExtractValue(Agg: Call, Idxs: 0, Name: "sadd.result");
1165 Value *ZExt = Builder.CreateZExt(V: Add, DestTy: OrigAdd->getType());
1166
1167 // The inner add was the result of the narrow add, zero extended to the
1168 // wider type. Replace it with the result computed by the intrinsic.
1169 IC.replaceInstUsesWith(I&: *OrigAdd, V: ZExt);
1170 IC.eraseInstFromFunction(I&: *OrigAdd);
1171
1172 // The original icmp gets replaced with the overflow value.
1173 return ExtractValueInst::Create(Agg: Call, Idxs: 1, NameStr: "sadd.overflow");
1174}
1175
1176/// If we have:
1177/// icmp eq/ne (urem/srem %x, %y), 0
1178/// iff %y is a power-of-two, we can replace this with a bit test:
1179/// icmp eq/ne (and %x, (add %y, -1)), 0
1180Instruction *InstCombinerImpl::foldIRemByPowerOfTwoToBitTest(ICmpInst &I) {
1181 // This fold is only valid for equality predicates.
1182 if (!I.isEquality())
1183 return nullptr;
1184 CmpPredicate Pred;
1185 Value *X, *Y, *Zero;
1186 if (!match(V: &I, P: m_ICmp(Pred, L: m_OneUse(SubPattern: m_IRem(L: m_Value(V&: X), R: m_Value(V&: Y))),
1187 R: m_CombineAnd(L: m_Zero(), R: m_Value(V&: Zero)))))
1188 return nullptr;
1189 if (!isKnownToBeAPowerOfTwo(V: Y, /*OrZero*/ true, CxtI: &I))
1190 return nullptr;
1191 // This may increase instruction count, we don't enforce that Y is a constant.
1192 Value *Mask = Builder.CreateAdd(LHS: Y, RHS: Constant::getAllOnesValue(Ty: Y->getType()));
1193 Value *Masked = Builder.CreateAnd(LHS: X, RHS: Mask);
1194 return ICmpInst::Create(Op: Instruction::ICmp, Pred, S1: Masked, S2: Zero);
1195}
1196
1197/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1198/// by one-less-than-bitwidth into a sign test on the original value.
1199Instruction *InstCombinerImpl::foldSignBitTest(ICmpInst &I) {
1200 Instruction *Val;
1201 CmpPredicate Pred;
1202 if (!I.isEquality() || !match(V: &I, P: m_ICmp(Pred, L: m_Instruction(I&: Val), R: m_Zero())))
1203 return nullptr;
1204
1205 Value *X;
1206 Type *XTy;
1207
1208 Constant *C;
1209 if (match(V: Val, P: m_TruncOrSelf(Op: m_Shr(L: m_Value(V&: X), R: m_Constant(C))))) {
1210 XTy = X->getType();
1211 unsigned XBitWidth = XTy->getScalarSizeInBits();
1212 if (!match(V: C, P: m_SpecificInt_ICMP(Predicate: ICmpInst::Predicate::ICMP_EQ,
1213 Threshold: APInt(XBitWidth, XBitWidth - 1))))
1214 return nullptr;
1215 } else if (isa<BinaryOperator>(Val) &&
1216 (X = reassociateShiftAmtsOfTwoSameDirectionShifts(
1217 Sh0: cast<BinaryOperator>(Val), SQ: SQ.getWithInstruction(I: Val),
1218 /*AnalyzeForSignBitExtraction=*/true))) {
1219 XTy = X->getType();
1220 } else
1221 return nullptr;
1222
1223 return ICmpInst::Create(Op: Instruction::ICmp,
1224 Pred: Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SGE
1225 : ICmpInst::ICMP_SLT,
1226 S1: X, S2: ConstantInt::getNullValue(Ty: XTy));
1227}
1228
1229// Handle icmp pred X, 0
1230Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) {
1231 CmpInst::Predicate Pred = Cmp.getPredicate();
1232 if (!match(V: Cmp.getOperand(i_nocapture: 1), P: m_Zero()))
1233 return nullptr;
1234
1235 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1236 if (Pred == ICmpInst::ICMP_SGT) {
1237 Value *A, *B;
1238 if (match(V: Cmp.getOperand(i_nocapture: 0), P: m_SMin(L: m_Value(V&: A), R: m_Value(V&: B)))) {
1239 if (isKnownPositive(V: A, SQ: SQ.getWithInstruction(I: &Cmp)))
1240 return new ICmpInst(Pred, B, Cmp.getOperand(i_nocapture: 1));
1241 if (isKnownPositive(V: B, SQ: SQ.getWithInstruction(I: &Cmp)))
1242 return new ICmpInst(Pred, A, Cmp.getOperand(i_nocapture: 1));
1243 }
1244 }
1245
1246 if (Instruction *New = foldIRemByPowerOfTwoToBitTest(I&: Cmp))
1247 return New;
1248
1249 // Given:
1250 // icmp eq/ne (urem %x, %y), 0
1251 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1252 // icmp eq/ne %x, 0
1253 Value *X, *Y;
1254 if (match(V: Cmp.getOperand(i_nocapture: 0), P: m_URem(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
1255 ICmpInst::isEquality(P: Pred)) {
1256 KnownBits XKnown = computeKnownBits(V: X, CxtI: &Cmp);
1257 KnownBits YKnown = computeKnownBits(V: Y, CxtI: &Cmp);
1258 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1259 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
1260 }
1261
1262 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1263 // odd/non-zero/there is no overflow.
1264 if (match(V: Cmp.getOperand(i_nocapture: 0), P: m_Mul(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
1265 ICmpInst::isEquality(P: Pred)) {
1266
1267 KnownBits XKnown = computeKnownBits(V: X, CxtI: &Cmp);
1268 // if X % 2 != 0
1269 // (icmp eq/ne Y)
1270 if (XKnown.countMaxTrailingZeros() == 0)
1271 return new ICmpInst(Pred, Y, Cmp.getOperand(i_nocapture: 1));
1272
1273 KnownBits YKnown = computeKnownBits(V: Y, CxtI: &Cmp);
1274 // if Y % 2 != 0
1275 // (icmp eq/ne X)
1276 if (YKnown.countMaxTrailingZeros() == 0)
1277 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
1278
1279 auto *BO0 = cast<OverflowingBinaryOperator>(Val: Cmp.getOperand(i_nocapture: 0));
1280 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1281 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
1282 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1283 // but to avoid unnecessary work, first just if this is an obvious case.
1284
1285 // if X non-zero and NoOverflow(X * Y)
1286 // (icmp eq/ne Y)
1287 if (!XKnown.One.isZero() || isKnownNonZero(V: X, Q))
1288 return new ICmpInst(Pred, Y, Cmp.getOperand(i_nocapture: 1));
1289
1290 // if Y non-zero and NoOverflow(X * Y)
1291 // (icmp eq/ne X)
1292 if (!YKnown.One.isZero() || isKnownNonZero(V: Y, Q))
1293 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
1294 }
1295 // Note, we are skipping cases:
1296 // if Y % 2 != 0 AND X % 2 != 0
1297 // (false/true)
1298 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1299 // (false/true)
1300 // Those can be simplified later as we would have already replaced the (icmp
1301 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1302 // will fold to a constant elsewhere.
1303 }
1304
1305 // (icmp eq/ne f(X), 0) -> (icmp eq/ne X, 0)
1306 // where f(X) == 0 if and only if X == 0
1307 if (ICmpInst::isEquality(P: Pred))
1308 if (Value *Stripped = stripNullTest(V: Cmp.getOperand(i_nocapture: 0)))
1309 return new ICmpInst(Pred, Stripped,
1310 Constant::getNullValue(Ty: Stripped->getType()));
1311
1312 return nullptr;
1313}
1314
1315/// Fold icmp Pred X, C.
1316/// TODO: This code structure does not make sense. The saturating add fold
1317/// should be moved to some other helper and extended as noted below (it is also
1318/// possible that code has been made unnecessary - do we canonicalize IR to
1319/// overflow/saturating intrinsics or not?).
1320Instruction *InstCombinerImpl::foldICmpWithConstant(ICmpInst &Cmp) {
1321 // Match the following pattern, which is a common idiom when writing
1322 // overflow-safe integer arithmetic functions. The source performs an addition
1323 // in wider type and explicitly checks for overflow using comparisons against
1324 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1325 //
1326 // TODO: This could probably be generalized to handle other overflow-safe
1327 // operations if we worked out the formulas to compute the appropriate magic
1328 // constants.
1329 //
1330 // sum = a + b
1331 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1332 CmpInst::Predicate Pred = Cmp.getPredicate();
1333 Value *Op0 = Cmp.getOperand(i_nocapture: 0), *Op1 = Cmp.getOperand(i_nocapture: 1);
1334 Value *A, *B;
1335 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1336 if (Pred == ICmpInst::ICMP_UGT && match(V: Op1, P: m_ConstantInt(CI)) &&
1337 match(V: Op0, P: m_Add(L: m_Add(L: m_Value(V&: A), R: m_Value(V&: B)), R: m_ConstantInt(CI&: CI2))))
1338 if (Instruction *Res = processUGT_ADDCST_ADD(I&: Cmp, A, B, CI2, CI1: CI, IC&: *this))
1339 return Res;
1340
1341 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1342 Constant *C = dyn_cast<Constant>(Val: Op1);
1343 if (!C)
1344 return nullptr;
1345
1346 if (auto *Phi = dyn_cast<PHINode>(Val: Op0))
1347 if (all_of(Range: Phi->operands(), P: [](Value *V) { return isa<Constant>(Val: V); })) {
1348 SmallVector<Constant *> Ops;
1349 for (Value *V : Phi->incoming_values()) {
1350 Constant *Res =
1351 ConstantFoldCompareInstOperands(Predicate: Pred, LHS: cast<Constant>(Val: V), RHS: C, DL);
1352 if (!Res)
1353 return nullptr;
1354 Ops.push_back(Elt: Res);
1355 }
1356 Builder.SetInsertPoint(Phi);
1357 PHINode *NewPhi = Builder.CreatePHI(Ty: Cmp.getType(), NumReservedValues: Phi->getNumOperands());
1358 for (auto [V, Pred] : zip(t&: Ops, u: Phi->blocks()))
1359 NewPhi->addIncoming(V, BB: Pred);
1360 return replaceInstUsesWith(I&: Cmp, V: NewPhi);
1361 }
1362
1363 if (Instruction *R = tryFoldInstWithCtpopWithNot(I: &Cmp))
1364 return R;
1365
1366 return nullptr;
1367}
1368
1369/// Canonicalize icmp instructions based on dominating conditions.
1370Instruction *InstCombinerImpl::foldICmpWithDominatingICmp(ICmpInst &Cmp) {
1371 // We already checked simple implication in InstSimplify, only handle complex
1372 // cases here.
1373 Value *X = Cmp.getOperand(i_nocapture: 0), *Y = Cmp.getOperand(i_nocapture: 1);
1374 const APInt *C;
1375 if (!match(V: Y, P: m_APInt(Res&: C)))
1376 return nullptr;
1377
1378 CmpInst::Predicate Pred = Cmp.getPredicate();
1379 ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, Other: *C);
1380
1381 auto handleDomCond = [&](ICmpInst::Predicate DomPred,
1382 const APInt *DomC) -> Instruction * {
1383 // We have 2 compares of a variable with constants. Calculate the constant
1384 // ranges of those compares to see if we can transform the 2nd compare:
1385 // DomBB:
1386 // DomCond = icmp DomPred X, DomC
1387 // br DomCond, CmpBB, FalseBB
1388 // CmpBB:
1389 // Cmp = icmp Pred X, C
1390 ConstantRange DominatingCR =
1391 ConstantRange::makeExactICmpRegion(Pred: DomPred, Other: *DomC);
1392 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1393 ConstantRange Difference = DominatingCR.difference(CR);
1394 if (Intersection.isEmptySet())
1395 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
1396 if (Difference.isEmptySet())
1397 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
1398
1399 // Canonicalizing a sign bit comparison that gets used in a branch,
1400 // pessimizes codegen by generating branch on zero instruction instead
1401 // of a test and branch. So we avoid canonicalizing in such situations
1402 // because test and branch instruction has better branch displacement
1403 // than compare and branch instruction.
1404 bool UnusedBit;
1405 bool IsSignBit = isSignBitCheck(Pred, RHS: *C, TrueIfSigned&: UnusedBit);
1406 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(I&: Cmp)))
1407 return nullptr;
1408
1409 // Avoid an infinite loop with min/max canonicalization.
1410 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1411 if (Cmp.hasOneUse() &&
1412 match(V: Cmp.user_back(), P: m_MaxOrMin(L: m_Value(), R: m_Value())))
1413 return nullptr;
1414
1415 if (const APInt *EqC = Intersection.getSingleElement())
1416 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(AI: *EqC));
1417 if (const APInt *NeC = Difference.getSingleElement())
1418 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(AI: *NeC));
1419 return nullptr;
1420 };
1421
1422 for (BranchInst *BI : DC.conditionsFor(V: X)) {
1423 CmpPredicate DomPred;
1424 const APInt *DomC;
1425 if (!match(V: BI->getCondition(),
1426 P: m_ICmp(Pred&: DomPred, L: m_Specific(V: X), R: m_APInt(Res&: DomC))))
1427 continue;
1428
1429 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(i: 0));
1430 if (DT.dominates(BBE: Edge0, BB: Cmp.getParent())) {
1431 if (auto *V = handleDomCond(DomPred, DomC))
1432 return V;
1433 } else {
1434 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(i: 1));
1435 if (DT.dominates(BBE: Edge1, BB: Cmp.getParent()))
1436 if (auto *V =
1437 handleDomCond(CmpInst::getInversePredicate(pred: DomPred), DomC))
1438 return V;
1439 }
1440 }
1441
1442 return nullptr;
1443}
1444
1445/// Fold icmp (trunc X), C.
1446Instruction *InstCombinerImpl::foldICmpTruncConstant(ICmpInst &Cmp,
1447 TruncInst *Trunc,
1448 const APInt &C) {
1449 ICmpInst::Predicate Pred = Cmp.getPredicate();
1450 Value *X = Trunc->getOperand(i_nocapture: 0);
1451 Type *SrcTy = X->getType();
1452 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1453 SrcBits = SrcTy->getScalarSizeInBits();
1454
1455 // Match (icmp pred (trunc nuw/nsw X), C)
1456 // Which we can convert to (icmp pred X, (sext/zext C))
1457 if (shouldChangeType(From: Trunc->getType(), To: SrcTy)) {
1458 if (Trunc->hasNoSignedWrap())
1459 return new ICmpInst(Pred, X, ConstantInt::get(Ty: SrcTy, V: C.sext(width: SrcBits)));
1460 if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())
1461 return new ICmpInst(Pred, X, ConstantInt::get(Ty: SrcTy, V: C.zext(width: SrcBits)));
1462 }
1463
1464 if (C.isOne() && C.getBitWidth() > 1) {
1465 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1466 Value *V = nullptr;
1467 if (Pred == ICmpInst::ICMP_SLT && match(V: X, P: m_Signum(V: m_Value(V))))
1468 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1469 ConstantInt::get(Ty: V->getType(), V: 1));
1470 }
1471
1472 // TODO: Handle any shifted constant by subtracting trailing zeros.
1473 // TODO: Handle non-equality predicates.
1474 Value *Y;
1475 if (Cmp.isEquality() && match(V: X, P: m_Shl(L: m_One(), R: m_Value(V&: Y)))) {
1476 // (trunc (1 << Y) to iN) == 0 --> Y u>= N
1477 // (trunc (1 << Y) to iN) != 0 --> Y u< N
1478 if (C.isZero()) {
1479 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1480 return new ICmpInst(NewPred, Y, ConstantInt::get(Ty: SrcTy, V: DstBits));
1481 }
1482 // (trunc (1 << Y) to iN) == 2**C --> Y == C
1483 // (trunc (1 << Y) to iN) != 2**C --> Y != C
1484 if (C.isPowerOf2())
1485 return new ICmpInst(Pred, Y, ConstantInt::get(Ty: SrcTy, V: C.logBase2()));
1486 }
1487
1488 if (Cmp.isEquality() && Trunc->hasOneUse()) {
1489 // Canonicalize to a mask and wider compare if the wide type is suitable:
1490 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1491 if (!SrcTy->isVectorTy() && shouldChangeType(FromBitWidth: DstBits, ToBitWidth: SrcBits)) {
1492 Constant *Mask =
1493 ConstantInt::get(Ty: SrcTy, V: APInt::getLowBitsSet(numBits: SrcBits, loBitsSet: DstBits));
1494 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask);
1495 Constant *WideC = ConstantInt::get(Ty: SrcTy, V: C.zext(width: SrcBits));
1496 return new ICmpInst(Pred, And, WideC);
1497 }
1498
1499 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1500 // of the high bits truncated out of x are known.
1501 KnownBits Known = computeKnownBits(V: X, CxtI: &Cmp);
1502
1503 // If all the high bits are known, we can do this xform.
1504 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1505 // Pull in the high bits from known-ones set.
1506 APInt NewRHS = C.zext(width: SrcBits);
1507 NewRHS |= Known.One & APInt::getHighBitsSet(numBits: SrcBits, hiBitsSet: SrcBits - DstBits);
1508 return new ICmpInst(Pred, X, ConstantInt::get(Ty: SrcTy, V: NewRHS));
1509 }
1510 }
1511
1512 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1513 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1514 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1515 Value *ShOp;
1516 const APInt *ShAmtC;
1517 bool TrueIfSigned;
1518 if (isSignBitCheck(Pred, RHS: C, TrueIfSigned) &&
1519 match(V: X, P: m_Shr(L: m_Value(V&: ShOp), R: m_APInt(Res&: ShAmtC))) &&
1520 DstBits == SrcBits - ShAmtC->getZExtValue()) {
1521 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1522 ConstantInt::getNullValue(Ty: SrcTy))
1523 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1524 ConstantInt::getAllOnesValue(Ty: SrcTy));
1525 }
1526
1527 return nullptr;
1528}
1529
1530/// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
1531/// Fold icmp (trunc nuw/nsw X), (zext/sext Y).
1532Instruction *
1533InstCombinerImpl::foldICmpTruncWithTruncOrExt(ICmpInst &Cmp,
1534 const SimplifyQuery &Q) {
1535 Value *X, *Y;
1536 CmpPredicate Pred;
1537 bool YIsSExt = false;
1538 // Try to match icmp (trunc X), (trunc Y)
1539 if (match(V: &Cmp, P: m_ICmp(Pred, L: m_Trunc(Op: m_Value(V&: X)), R: m_Trunc(Op: m_Value(V&: Y))))) {
1540 unsigned NoWrapFlags = cast<TruncInst>(Val: Cmp.getOperand(i_nocapture: 0))->getNoWrapKind() &
1541 cast<TruncInst>(Val: Cmp.getOperand(i_nocapture: 1))->getNoWrapKind();
1542 if (Cmp.isSigned()) {
1543 // For signed comparisons, both truncs must be nsw.
1544 if (!(NoWrapFlags & TruncInst::NoSignedWrap))
1545 return nullptr;
1546 } else {
1547 // For unsigned and equality comparisons, either both must be nuw or
1548 // both must be nsw, we don't care which.
1549 if (!NoWrapFlags)
1550 return nullptr;
1551 }
1552
1553 if (X->getType() != Y->getType() &&
1554 (!Cmp.getOperand(i_nocapture: 0)->hasOneUse() || !Cmp.getOperand(i_nocapture: 1)->hasOneUse()))
1555 return nullptr;
1556 if (!isDesirableIntType(BitWidth: X->getType()->getScalarSizeInBits()) &&
1557 isDesirableIntType(BitWidth: Y->getType()->getScalarSizeInBits())) {
1558 std::swap(a&: X, b&: Y);
1559 Pred = Cmp.getSwappedPredicate(pred: Pred);
1560 }
1561 YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);
1562 }
1563 // Try to match icmp (trunc nuw X), (zext Y)
1564 else if (!Cmp.isSigned() &&
1565 match(V: &Cmp, P: m_c_ICmp(Pred, L: m_NUWTrunc(Op: m_Value(V&: X)),
1566 R: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: Y)))))) {
1567 // Can fold trunc nuw + zext for unsigned and equality predicates.
1568 }
1569 // Try to match icmp (trunc nsw X), (sext Y)
1570 else if (match(V: &Cmp, P: m_c_ICmp(Pred, L: m_NSWTrunc(Op: m_Value(V&: X)),
1571 R: m_OneUse(SubPattern: m_ZExtOrSExt(Op: m_Value(V&: Y)))))) {
1572 // Can fold trunc nsw + zext/sext for all predicates.
1573 YIsSExt =
1574 isa<SExtInst>(Val: Cmp.getOperand(i_nocapture: 0)) || isa<SExtInst>(Val: Cmp.getOperand(i_nocapture: 1));
1575 } else
1576 return nullptr;
1577
1578 Type *TruncTy = Cmp.getOperand(i_nocapture: 0)->getType();
1579 unsigned TruncBits = TruncTy->getScalarSizeInBits();
1580
1581 // If this transform will end up changing from desirable types -> undesirable
1582 // types skip it.
1583 if (isDesirableIntType(BitWidth: TruncBits) &&
1584 !isDesirableIntType(BitWidth: X->getType()->getScalarSizeInBits()))
1585 return nullptr;
1586
1587 Value *NewY = Builder.CreateIntCast(V: Y, DestTy: X->getType(), isSigned: YIsSExt);
1588 return new ICmpInst(Pred, X, NewY);
1589}
1590
1591/// Fold icmp (xor X, Y), C.
1592Instruction *InstCombinerImpl::foldICmpXorConstant(ICmpInst &Cmp,
1593 BinaryOperator *Xor,
1594 const APInt &C) {
1595 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1596 return I;
1597
1598 Value *X = Xor->getOperand(i_nocapture: 0);
1599 Value *Y = Xor->getOperand(i_nocapture: 1);
1600 const APInt *XorC;
1601 if (!match(V: Y, P: m_APInt(Res&: XorC)))
1602 return nullptr;
1603
1604 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1605 // fold the xor.
1606 ICmpInst::Predicate Pred = Cmp.getPredicate();
1607 bool TrueIfSigned = false;
1608 if (isSignBitCheck(Pred: Cmp.getPredicate(), RHS: C, TrueIfSigned)) {
1609
1610 // If the sign bit of the XorCst is not set, there is no change to
1611 // the operation, just stop using the Xor.
1612 if (!XorC->isNegative())
1613 return replaceOperand(I&: Cmp, OpNum: 0, V: X);
1614
1615 // Emit the opposite comparison.
1616 if (TrueIfSigned)
1617 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1618 ConstantInt::getAllOnesValue(Ty: X->getType()));
1619 else
1620 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1621 ConstantInt::getNullValue(Ty: X->getType()));
1622 }
1623
1624 if (Xor->hasOneUse()) {
1625 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1626 if (!Cmp.isEquality() && XorC->isSignMask()) {
1627 Pred = Cmp.getFlippedSignednessPredicate();
1628 return new ICmpInst(Pred, X, ConstantInt::get(Ty: X->getType(), V: C ^ *XorC));
1629 }
1630
1631 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1632 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1633 Pred = Cmp.getFlippedSignednessPredicate();
1634 Pred = Cmp.getSwappedPredicate(pred: Pred);
1635 return new ICmpInst(Pred, X, ConstantInt::get(Ty: X->getType(), V: C ^ *XorC));
1636 }
1637 }
1638
1639 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1640 if (Pred == ICmpInst::ICMP_UGT) {
1641 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1642 if (*XorC == ~C && (C + 1).isPowerOf2())
1643 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1644 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1645 if (*XorC == C && (C + 1).isPowerOf2())
1646 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1647 }
1648 if (Pred == ICmpInst::ICMP_ULT) {
1649 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1650 if (*XorC == -C && C.isPowerOf2())
1651 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1652 ConstantInt::get(Ty: X->getType(), V: ~C));
1653 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1654 if (*XorC == C && (-C).isPowerOf2())
1655 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1656 ConstantInt::get(Ty: X->getType(), V: ~C));
1657 }
1658 return nullptr;
1659}
1660
1661/// For power-of-2 C:
1662/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1663/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1664Instruction *InstCombinerImpl::foldICmpXorShiftConst(ICmpInst &Cmp,
1665 BinaryOperator *Xor,
1666 const APInt &C) {
1667 CmpInst::Predicate Pred = Cmp.getPredicate();
1668 APInt PowerOf2;
1669 if (Pred == ICmpInst::ICMP_ULT)
1670 PowerOf2 = C;
1671 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1672 PowerOf2 = C + 1;
1673 else
1674 return nullptr;
1675 if (!PowerOf2.isPowerOf2())
1676 return nullptr;
1677 Value *X;
1678 const APInt *ShiftC;
1679 if (!match(V: Xor, P: m_OneUse(SubPattern: m_c_Xor(L: m_Value(V&: X),
1680 R: m_AShr(L: m_Deferred(V: X), R: m_APInt(Res&: ShiftC))))))
1681 return nullptr;
1682 uint64_t Shift = ShiftC->getLimitedValue();
1683 Type *XType = X->getType();
1684 if (Shift == 0 || PowerOf2.isMinSignedValue())
1685 return nullptr;
1686 Value *Add = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty: XType, V: PowerOf2));
1687 APInt Bound =
1688 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1689 return new ICmpInst(Pred, Add, ConstantInt::get(Ty: XType, V: Bound));
1690}
1691
1692/// Fold icmp (and (sh X, Y), C2), C1.
1693Instruction *InstCombinerImpl::foldICmpAndShift(ICmpInst &Cmp,
1694 BinaryOperator *And,
1695 const APInt &C1,
1696 const APInt &C2) {
1697 BinaryOperator *Shift = dyn_cast<BinaryOperator>(Val: And->getOperand(i_nocapture: 0));
1698 if (!Shift || !Shift->isShift())
1699 return nullptr;
1700
1701 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1702 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1703 // code produced by the clang front-end, for bitfield access.
1704 // This seemingly simple opportunity to fold away a shift turns out to be
1705 // rather complicated. See PR17827 for details.
1706 unsigned ShiftOpcode = Shift->getOpcode();
1707 bool IsShl = ShiftOpcode == Instruction::Shl;
1708 const APInt *C3;
1709 if (match(V: Shift->getOperand(i_nocapture: 1), P: m_APInt(Res&: C3))) {
1710 APInt NewAndCst, NewCmpCst;
1711 bool AnyCmpCstBitsShiftedOut;
1712 if (ShiftOpcode == Instruction::Shl) {
1713 // For a left shift, we can fold if the comparison is not signed. We can
1714 // also fold a signed comparison if the mask value and comparison value
1715 // are not negative. These constraints may not be obvious, but we can
1716 // prove that they are correct using an SMT solver.
1717 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1718 return nullptr;
1719
1720 NewCmpCst = C1.lshr(ShiftAmt: *C3);
1721 NewAndCst = C2.lshr(ShiftAmt: *C3);
1722 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(ShiftAmt: *C3) != C1;
1723 } else if (ShiftOpcode == Instruction::LShr) {
1724 // For a logical right shift, we can fold if the comparison is not signed.
1725 // We can also fold a signed comparison if the shifted mask value and the
1726 // shifted comparison value are not negative. These constraints may not be
1727 // obvious, but we can prove that they are correct using an SMT solver.
1728 NewCmpCst = C1.shl(ShiftAmt: *C3);
1729 NewAndCst = C2.shl(ShiftAmt: *C3);
1730 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(ShiftAmt: *C3) != C1;
1731 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1732 return nullptr;
1733 } else {
1734 // For an arithmetic shift, check that both constants don't use (in a
1735 // signed sense) the top bits being shifted out.
1736 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1737 NewCmpCst = C1.shl(ShiftAmt: *C3);
1738 NewAndCst = C2.shl(ShiftAmt: *C3);
1739 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(ShiftAmt: *C3) != C1;
1740 if (NewAndCst.ashr(ShiftAmt: *C3) != C2)
1741 return nullptr;
1742 }
1743
1744 if (AnyCmpCstBitsShiftedOut) {
1745 // If we shifted bits out, the fold is not going to work out. As a
1746 // special case, check to see if this means that the result is always
1747 // true or false now.
1748 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1749 return replaceInstUsesWith(I&: Cmp, V: ConstantInt::getFalse(Ty: Cmp.getType()));
1750 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1751 return replaceInstUsesWith(I&: Cmp, V: ConstantInt::getTrue(Ty: Cmp.getType()));
1752 } else {
1753 Value *NewAnd = Builder.CreateAnd(
1754 LHS: Shift->getOperand(i_nocapture: 0), RHS: ConstantInt::get(Ty: And->getType(), V: NewAndCst));
1755 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1756 ConstantInt::get(Ty: And->getType(), V: NewCmpCst));
1757 }
1758 }
1759
1760 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1761 // preferable because it allows the C2 << Y expression to be hoisted out of a
1762 // loop if Y is invariant and X is not.
1763 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1764 !Shift->isArithmeticShift() &&
1765 ((!IsShl && C2.isOne()) || !isa<Constant>(Val: Shift->getOperand(i_nocapture: 0)))) {
1766 // Compute C2 << Y.
1767 Value *NewShift =
1768 IsShl ? Builder.CreateLShr(LHS: And->getOperand(i_nocapture: 1), RHS: Shift->getOperand(i_nocapture: 1))
1769 : Builder.CreateShl(LHS: And->getOperand(i_nocapture: 1), RHS: Shift->getOperand(i_nocapture: 1));
1770
1771 // Compute X & (C2 << Y).
1772 Value *NewAnd = Builder.CreateAnd(LHS: Shift->getOperand(i_nocapture: 0), RHS: NewShift);
1773 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(i_nocapture: 1));
1774 }
1775
1776 return nullptr;
1777}
1778
1779/// Fold icmp (and X, C2), C1.
1780Instruction *InstCombinerImpl::foldICmpAndConstConst(ICmpInst &Cmp,
1781 BinaryOperator *And,
1782 const APInt &C1) {
1783 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1784
1785 // For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i1
1786 // TODO: We canonicalize to the longer form for scalars because we have
1787 // better analysis/folds for icmp, and codegen may be better with icmp.
1788 if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.isZero() &&
1789 match(V: And->getOperand(i_nocapture: 1), P: m_One()))
1790 return new TruncInst(And->getOperand(i_nocapture: 0), Cmp.getType());
1791
1792 const APInt *C2;
1793 Value *X;
1794 if (!match(V: And, P: m_And(L: m_Value(V&: X), R: m_APInt(Res&: C2))))
1795 return nullptr;
1796
1797 // (and X, highmask) s> [0, ~highmask] --> X s> ~highmask
1798 if (Cmp.getPredicate() == ICmpInst::ICMP_SGT && C1.ule(RHS: ~*C2) &&
1799 C2->isNegatedPowerOf2())
1800 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1801 ConstantInt::get(Ty: X->getType(), V: ~*C2));
1802 // (and X, highmask) s< [1, -highmask] --> X s< -highmask
1803 if (Cmp.getPredicate() == ICmpInst::ICMP_SLT && !C1.isSignMask() &&
1804 (C1 - 1).ule(RHS: ~*C2) && C2->isNegatedPowerOf2() && !C2->isSignMask())
1805 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1806 ConstantInt::get(Ty: X->getType(), V: -*C2));
1807
1808 // Don't perform the following transforms if the AND has multiple uses
1809 if (!And->hasOneUse())
1810 return nullptr;
1811
1812 if (Cmp.isEquality() && C1.isZero()) {
1813 // Restrict this fold to single-use 'and' (PR10267).
1814 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1815 if (C2->isSignMask()) {
1816 Constant *Zero = Constant::getNullValue(Ty: X->getType());
1817 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1818 return new ICmpInst(NewPred, X, Zero);
1819 }
1820
1821 APInt NewC2 = *C2;
1822 KnownBits Know = computeKnownBits(V: And->getOperand(i_nocapture: 0), CxtI: And);
1823 // Set high zeros of C2 to allow matching negated power-of-2.
1824 NewC2 = *C2 | APInt::getHighBitsSet(numBits: C2->getBitWidth(),
1825 hiBitsSet: Know.countMinLeadingZeros());
1826
1827 // Restrict this fold only for single-use 'and' (PR10267).
1828 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1829 if (NewC2.isNegatedPowerOf2()) {
1830 Constant *NegBOC = ConstantInt::get(Ty: And->getType(), V: -NewC2);
1831 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1832 return new ICmpInst(NewPred, X, NegBOC);
1833 }
1834 }
1835
1836 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1837 // the input width without changing the value produced, eliminate the cast:
1838 //
1839 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1840 //
1841 // We can do this transformation if the constants do not have their sign bits
1842 // set or if it is an equality comparison. Extending a relational comparison
1843 // when we're checking the sign bit would not work.
1844 Value *W;
1845 if (match(V: And->getOperand(i_nocapture: 0), P: m_OneUse(SubPattern: m_Trunc(Op: m_Value(V&: W)))) &&
1846 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1847 // TODO: Is this a good transform for vectors? Wider types may reduce
1848 // throughput. Should this transform be limited (even for scalars) by using
1849 // shouldChangeType()?
1850 if (!Cmp.getType()->isVectorTy()) {
1851 Type *WideType = W->getType();
1852 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1853 Constant *ZextC1 = ConstantInt::get(Ty: WideType, V: C1.zext(width: WideScalarBits));
1854 Constant *ZextC2 = ConstantInt::get(Ty: WideType, V: C2->zext(width: WideScalarBits));
1855 Value *NewAnd = Builder.CreateAnd(LHS: W, RHS: ZextC2, Name: And->getName());
1856 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1857 }
1858 }
1859
1860 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, C2: *C2))
1861 return I;
1862
1863 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1864 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1865 //
1866 // iff pred isn't signed
1867 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(i_nocapture: 0)->hasOneUse() &&
1868 match(V: And->getOperand(i_nocapture: 1), P: m_One())) {
1869 Constant *One = cast<Constant>(Val: And->getOperand(i_nocapture: 1));
1870 Value *Or = And->getOperand(i_nocapture: 0);
1871 Value *A, *B, *LShr;
1872 if (match(V: Or, P: m_Or(L: m_Value(V&: LShr), R: m_Value(V&: A))) &&
1873 match(V: LShr, P: m_LShr(L: m_Specific(V: A), R: m_Value(V&: B)))) {
1874 unsigned UsesRemoved = 0;
1875 if (And->hasOneUse())
1876 ++UsesRemoved;
1877 if (Or->hasOneUse())
1878 ++UsesRemoved;
1879 if (LShr->hasOneUse())
1880 ++UsesRemoved;
1881
1882 // Compute A & ((1 << B) | 1)
1883 unsigned RequireUsesRemoved = match(V: B, P: m_ImmConstant()) ? 1 : 3;
1884 if (UsesRemoved >= RequireUsesRemoved) {
1885 Value *NewOr =
1886 Builder.CreateOr(LHS: Builder.CreateShl(LHS: One, RHS: B, Name: LShr->getName(),
1887 /*HasNUW=*/true),
1888 RHS: One, Name: Or->getName());
1889 Value *NewAnd = Builder.CreateAnd(LHS: A, RHS: NewOr, Name: And->getName());
1890 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(i_nocapture: 1));
1891 }
1892 }
1893 }
1894
1895 // (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->
1896 // llvm.is.fpclass(X, fcInf|fcNan)
1897 // (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->
1898 // llvm.is.fpclass(X, ~(fcInf|fcNan))
1899 // (icmp eq (and (bitcast X to int), ExponentMask), 0) -->
1900 // llvm.is.fpclass(X, fcSubnormal|fcZero)
1901 // (icmp ne (and (bitcast X to int), ExponentMask), 0) -->
1902 // llvm.is.fpclass(X, ~(fcSubnormal|fcZero))
1903 Value *V;
1904 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1905 Kind: Attribute::NoImplicitFloat) &&
1906 Cmp.isEquality() &&
1907 match(V: X, P: m_OneUse(SubPattern: m_ElementWiseBitCast(Op: m_Value(V))))) {
1908 Type *FPType = V->getType()->getScalarType();
1909 if (FPType->isIEEELikeFPTy() && (C1.isZero() || C1 == *C2)) {
1910 APInt ExponentMask =
1911 APFloat::getInf(Sem: FPType->getFltSemantics()).bitcastToAPInt();
1912 if (*C2 == ExponentMask) {
1913 unsigned Mask = C1.isZero()
1914 ? FPClassTest::fcZero | FPClassTest::fcSubnormal
1915 : FPClassTest::fcNan | FPClassTest::fcInf;
1916 if (isICMP_NE)
1917 Mask = ~Mask & fcAllFlags;
1918 return replaceInstUsesWith(I&: Cmp, V: Builder.createIsFPClass(FPNum: V, Test: Mask));
1919 }
1920 }
1921 }
1922
1923 return nullptr;
1924}
1925
1926/// Fold icmp (and X, Y), C.
1927Instruction *InstCombinerImpl::foldICmpAndConstant(ICmpInst &Cmp,
1928 BinaryOperator *And,
1929 const APInt &C) {
1930 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C1: C))
1931 return I;
1932
1933 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1934 bool TrueIfNeg;
1935 if (isSignBitCheck(Pred, RHS: C, TrueIfSigned&: TrueIfNeg)) {
1936 // ((X - 1) & ~X) < 0 --> X == 0
1937 // ((X - 1) & ~X) >= 0 --> X != 0
1938 Value *X;
1939 if (match(V: And->getOperand(i_nocapture: 0), P: m_Add(L: m_Value(V&: X), R: m_AllOnes())) &&
1940 match(V: And->getOperand(i_nocapture: 1), P: m_Not(V: m_Specific(V: X)))) {
1941 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1942 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(Ty: X->getType()));
1943 }
1944 // (X & -X) < 0 --> X == MinSignedC
1945 // (X & -X) > -1 --> X != MinSignedC
1946 if (match(V: And, P: m_c_And(L: m_Neg(V: m_Value(V&: X)), R: m_Deferred(V: X)))) {
1947 Constant *MinSignedC = ConstantInt::get(
1948 Ty: X->getType(),
1949 V: APInt::getSignedMinValue(numBits: X->getType()->getScalarSizeInBits()));
1950 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1951 return new ICmpInst(NewPred, X, MinSignedC);
1952 }
1953 }
1954
1955 // TODO: These all require that Y is constant too, so refactor with the above.
1956
1957 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1958 Value *X = And->getOperand(i_nocapture: 0);
1959 Value *Y = And->getOperand(i_nocapture: 1);
1960 if (auto *C2 = dyn_cast<ConstantInt>(Val: Y))
1961 if (auto *LI = dyn_cast<LoadInst>(Val: X))
1962 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: LI->getOperand(i_nocapture: 0)))
1963 if (auto *GV = dyn_cast<GlobalVariable>(Val: GEP->getOperand(i_nocapture: 0)))
1964 if (Instruction *Res =
1965 foldCmpLoadFromIndexedGlobal(LI, GEP, GV, ICI&: Cmp, AndCst: C2))
1966 return Res;
1967
1968 if (!Cmp.isEquality())
1969 return nullptr;
1970
1971 // X & -C == -C -> X > u ~C
1972 // X & -C != -C -> X <= u ~C
1973 // iff C is a power of 2
1974 if (Cmp.getOperand(i_nocapture: 1) == Y && C.isNegatedPowerOf2()) {
1975 auto NewPred =
1976 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT : CmpInst::ICMP_ULE;
1977 return new ICmpInst(NewPred, X, SubOne(C: cast<Constant>(Val: Cmp.getOperand(i_nocapture: 1))));
1978 }
1979
1980 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
1981 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
1982 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
1983 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
1984 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)))) &&
1985 X->getType()->isIntOrIntVectorTy(BitWidth: 1) && (C.isZero() || C.isOne())) {
1986 Value *TruncY = Builder.CreateTrunc(V: Y, DestTy: X->getType());
1987 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
1988 Value *And = Builder.CreateAnd(LHS: TruncY, RHS: X);
1989 return BinaryOperator::CreateNot(Op: And);
1990 }
1991 return BinaryOperator::CreateAnd(V1: TruncY, V2: X);
1992 }
1993
1994 // (icmp eq/ne (and (shl -1, X), Y), 0)
1995 // -> (icmp eq/ne (lshr Y, X), 0)
1996 // We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems
1997 // highly unlikely the non-zero case will ever show up in code.
1998 if (C.isZero() &&
1999 match(V: And, P: m_OneUse(SubPattern: m_c_And(L: m_OneUse(SubPattern: m_Shl(L: m_AllOnes(), R: m_Value(V&: X))),
2000 R: m_Value(V&: Y))))) {
2001 Value *LShr = Builder.CreateLShr(LHS: Y, RHS: X);
2002 return new ICmpInst(Pred, LShr, Constant::getNullValue(Ty: LShr->getType()));
2003 }
2004
2005 // (icmp eq/ne (and (add A, Addend), Msk), C)
2006 // -> (icmp eq/ne (and A, Msk), (and (sub C, Addend), Msk))
2007 {
2008 Value *A;
2009 const APInt *Addend, *Msk;
2010 if (match(V: And, P: m_And(L: m_OneUse(SubPattern: m_Add(L: m_Value(V&: A), R: m_APInt(Res&: Addend))),
2011 R: m_LowBitMask(V&: Msk))) &&
2012 C.ule(RHS: *Msk)) {
2013 APInt NewComperand = (C - *Addend) & *Msk;
2014 Value *MaskA = Builder.CreateAnd(LHS: A, RHS: ConstantInt::get(Ty: A->getType(), V: *Msk));
2015 return new ICmpInst(Pred, MaskA,
2016 ConstantInt::get(Ty: MaskA->getType(), V: NewComperand));
2017 }
2018 }
2019
2020 return nullptr;
2021}
2022
2023/// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
2024static Value *foldICmpOrXorSubChain(ICmpInst &Cmp, BinaryOperator *Or,
2025 InstCombiner::BuilderTy &Builder) {
2026 // Are we using xors or subs to bitwise check for a pair or pairs of
2027 // (in)equalities? Convert to a shorter form that has more potential to be
2028 // folded even further.
2029 // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
2030 // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
2031 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
2032 // (X1 == X2) && (X3 == X4) && (X5 == X6)
2033 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
2034 // (X1 != X2) || (X3 != X4) || (X5 != X6)
2035 SmallVector<std::pair<Value *, Value *>, 2> CmpValues;
2036 SmallVector<Value *, 16> WorkList(1, Or);
2037
2038 while (!WorkList.empty()) {
2039 auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
2040 Value *Lhs, *Rhs;
2041
2042 if (match(V: OrOperatorArgument,
2043 P: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: Lhs), R: m_Value(V&: Rhs))))) {
2044 CmpValues.emplace_back(Args&: Lhs, Args&: Rhs);
2045 return;
2046 }
2047
2048 if (match(V: OrOperatorArgument,
2049 P: m_OneUse(SubPattern: m_Sub(L: m_Value(V&: Lhs), R: m_Value(V&: Rhs))))) {
2050 CmpValues.emplace_back(Args&: Lhs, Args&: Rhs);
2051 return;
2052 }
2053
2054 WorkList.push_back(Elt: OrOperatorArgument);
2055 };
2056
2057 Value *CurrentValue = WorkList.pop_back_val();
2058 Value *OrOperatorLhs, *OrOperatorRhs;
2059
2060 if (!match(V: CurrentValue,
2061 P: m_Or(L: m_Value(V&: OrOperatorLhs), R: m_Value(V&: OrOperatorRhs)))) {
2062 return nullptr;
2063 }
2064
2065 MatchOrOperatorArgument(OrOperatorRhs);
2066 MatchOrOperatorArgument(OrOperatorLhs);
2067 }
2068
2069 ICmpInst::Predicate Pred = Cmp.getPredicate();
2070 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2071 Value *LhsCmp = Builder.CreateICmp(P: Pred, LHS: CmpValues.rbegin()->first,
2072 RHS: CmpValues.rbegin()->second);
2073
2074 for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
2075 Value *RhsCmp = Builder.CreateICmp(P: Pred, LHS: It->first, RHS: It->second);
2076 LhsCmp = Builder.CreateBinOp(Opc: BOpc, LHS: LhsCmp, RHS: RhsCmp);
2077 }
2078
2079 return LhsCmp;
2080}
2081
2082/// Fold icmp (or X, Y), C.
2083Instruction *InstCombinerImpl::foldICmpOrConstant(ICmpInst &Cmp,
2084 BinaryOperator *Or,
2085 const APInt &C) {
2086 ICmpInst::Predicate Pred = Cmp.getPredicate();
2087 if (C.isOne()) {
2088 // icmp slt signum(V) 1 --> icmp slt V, 1
2089 Value *V = nullptr;
2090 if (Pred == ICmpInst::ICMP_SLT && match(V: Or, P: m_Signum(V: m_Value(V))))
2091 return new ICmpInst(ICmpInst::ICMP_SLT, V,
2092 ConstantInt::get(Ty: V->getType(), V: 1));
2093 }
2094
2095 Value *OrOp0 = Or->getOperand(i_nocapture: 0), *OrOp1 = Or->getOperand(i_nocapture: 1);
2096
2097 // (icmp eq/ne (or disjoint x, C0), C1)
2098 // -> (icmp eq/ne x, C0^C1)
2099 if (Cmp.isEquality() && match(V: OrOp1, P: m_ImmConstant()) &&
2100 cast<PossiblyDisjointInst>(Val: Or)->isDisjoint()) {
2101 Value *NewC =
2102 Builder.CreateXor(LHS: OrOp1, RHS: ConstantInt::get(Ty: OrOp1->getType(), V: C));
2103 return new ICmpInst(Pred, OrOp0, NewC);
2104 }
2105
2106 const APInt *MaskC;
2107 if (match(V: OrOp1, P: m_APInt(Res&: MaskC)) && Cmp.isEquality()) {
2108 if (*MaskC == C && (C + 1).isPowerOf2()) {
2109 // X | C == C --> X <=u C
2110 // X | C != C --> X >u C
2111 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
2112 Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT;
2113 return new ICmpInst(Pred, OrOp0, OrOp1);
2114 }
2115
2116 // More general: canonicalize 'equality with set bits mask' to
2117 // 'equality with clear bits mask'.
2118 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2119 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2120 if (Or->hasOneUse()) {
2121 Value *And = Builder.CreateAnd(LHS: OrOp0, RHS: ~(*MaskC));
2122 Constant *NewC = ConstantInt::get(Ty: Or->getType(), V: C ^ (*MaskC));
2123 return new ICmpInst(Pred, And, NewC);
2124 }
2125 }
2126
2127 // (X | (X-1)) s< 0 --> X s< 1
2128 // (X | (X-1)) s> -1 --> X s> 0
2129 Value *X;
2130 bool TrueIfSigned;
2131 if (isSignBitCheck(Pred, RHS: C, TrueIfSigned) &&
2132 match(V: Or, P: m_c_Or(L: m_Add(L: m_Value(V&: X), R: m_AllOnes()), R: m_Deferred(V: X)))) {
2133 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2134 Constant *NewC = ConstantInt::get(Ty: X->getType(), V: TrueIfSigned ? 1 : 0);
2135 return new ICmpInst(NewPred, X, NewC);
2136 }
2137
2138 const APInt *OrC;
2139 // icmp(X | OrC, C) --> icmp(X, 0)
2140 if (C.isNonNegative() && match(V: Or, P: m_Or(L: m_Value(V&: X), R: m_APInt(Res&: OrC)))) {
2141 switch (Pred) {
2142 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2143 case ICmpInst::ICMP_SLT:
2144 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2145 case ICmpInst::ICMP_SGE:
2146 if (OrC->sge(RHS: C))
2147 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: X->getType()));
2148 break;
2149 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2150 case ICmpInst::ICMP_SLE:
2151 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2152 case ICmpInst::ICMP_SGT:
2153 if (OrC->sgt(RHS: C))
2154 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), X,
2155 ConstantInt::getNullValue(Ty: X->getType()));
2156 break;
2157 default:
2158 break;
2159 }
2160 }
2161
2162 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2163 return nullptr;
2164
2165 Value *P, *Q;
2166 if (match(V: Or, P: m_Or(L: m_PtrToInt(Op: m_Value(V&: P)), R: m_PtrToInt(Op: m_Value(V&: Q))))) {
2167 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2168 // -> and (icmp eq P, null), (icmp eq Q, null).
2169 Value *CmpP =
2170 Builder.CreateICmp(P: Pred, LHS: P, RHS: ConstantInt::getNullValue(Ty: P->getType()));
2171 Value *CmpQ =
2172 Builder.CreateICmp(P: Pred, LHS: Q, RHS: ConstantInt::getNullValue(Ty: Q->getType()));
2173 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2174 return BinaryOperator::Create(Op: BOpc, S1: CmpP, S2: CmpQ);
2175 }
2176
2177 if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2178 return replaceInstUsesWith(I&: Cmp, V);
2179
2180 return nullptr;
2181}
2182
2183/// Fold icmp (mul X, Y), C.
2184Instruction *InstCombinerImpl::foldICmpMulConstant(ICmpInst &Cmp,
2185 BinaryOperator *Mul,
2186 const APInt &C) {
2187 ICmpInst::Predicate Pred = Cmp.getPredicate();
2188 Type *MulTy = Mul->getType();
2189 Value *X = Mul->getOperand(i_nocapture: 0);
2190
2191 // If there's no overflow:
2192 // X * X == 0 --> X == 0
2193 // X * X != 0 --> X != 0
2194 if (Cmp.isEquality() && C.isZero() && X == Mul->getOperand(i_nocapture: 1) &&
2195 (Mul->hasNoUnsignedWrap() || Mul->hasNoSignedWrap()))
2196 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: MulTy));
2197
2198 const APInt *MulC;
2199 if (!match(V: Mul->getOperand(i_nocapture: 1), P: m_APInt(Res&: MulC)))
2200 return nullptr;
2201
2202 // If this is a test of the sign bit and the multiply is sign-preserving with
2203 // a constant operand, use the multiply LHS operand instead:
2204 // (X * +MulC) < 0 --> X < 0
2205 // (X * -MulC) < 0 --> X > 0
2206 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2207 if (MulC->isNegative())
2208 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
2209 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: MulTy));
2210 }
2211
2212 if (MulC->isZero())
2213 return nullptr;
2214
2215 // If the multiply does not wrap or the constant is odd, try to divide the
2216 // compare constant by the multiplication factor.
2217 if (Cmp.isEquality()) {
2218 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2219 if (Mul->hasNoSignedWrap() && C.srem(RHS: *MulC).isZero()) {
2220 Constant *NewC = ConstantInt::get(Ty: MulTy, V: C.sdiv(RHS: *MulC));
2221 return new ICmpInst(Pred, X, NewC);
2222 }
2223
2224 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2225 // correct to transform if MulC * N == C including overflow. I.e with i8
2226 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2227 // miss that case.
2228 if (C.urem(RHS: *MulC).isZero()) {
2229 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2230 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2231 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2232 Constant *NewC = ConstantInt::get(Ty: MulTy, V: C.udiv(RHS: *MulC));
2233 return new ICmpInst(Pred, X, NewC);
2234 }
2235 }
2236 }
2237
2238 // With a matching no-overflow guarantee, fold the constants:
2239 // (X * MulC) < C --> X < (C / MulC)
2240 // (X * MulC) > C --> X > (C / MulC)
2241 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2242 Constant *NewC = nullptr;
2243 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(predicate: Pred)) {
2244 // MININT / -1 --> overflow.
2245 if (C.isMinSignedValue() && MulC->isAllOnes())
2246 return nullptr;
2247 if (MulC->isNegative())
2248 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
2249
2250 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2251 NewC = ConstantInt::get(
2252 Ty: MulTy, V: APIntOps::RoundingSDiv(A: C, B: *MulC, RM: APInt::Rounding::UP));
2253 } else {
2254 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2255 "Unexpected predicate");
2256 NewC = ConstantInt::get(
2257 Ty: MulTy, V: APIntOps::RoundingSDiv(A: C, B: *MulC, RM: APInt::Rounding::DOWN));
2258 }
2259 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(predicate: Pred)) {
2260 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2261 NewC = ConstantInt::get(
2262 Ty: MulTy, V: APIntOps::RoundingUDiv(A: C, B: *MulC, RM: APInt::Rounding::UP));
2263 } else {
2264 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2265 "Unexpected predicate");
2266 NewC = ConstantInt::get(
2267 Ty: MulTy, V: APIntOps::RoundingUDiv(A: C, B: *MulC, RM: APInt::Rounding::DOWN));
2268 }
2269 }
2270
2271 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2272}
2273
2274/// Fold icmp (shl nuw C2, Y), C.
2275static Instruction *foldICmpShlLHSC(ICmpInst &Cmp, Instruction *Shl,
2276 const APInt &C) {
2277 Value *Y;
2278 const APInt *C2;
2279 if (!match(V: Shl, P: m_NUWShl(L: m_APInt(Res&: C2), R: m_Value(V&: Y))))
2280 return nullptr;
2281
2282 Type *ShiftType = Shl->getType();
2283 unsigned TypeBits = C.getBitWidth();
2284 ICmpInst::Predicate Pred = Cmp.getPredicate();
2285 if (Cmp.isUnsigned()) {
2286 if (C2->isZero() || C2->ugt(RHS: C))
2287 return nullptr;
2288 APInt Div, Rem;
2289 APInt::udivrem(LHS: C, RHS: *C2, Quotient&: Div, Remainder&: Rem);
2290 bool CIsPowerOf2 = Rem.isZero() && Div.isPowerOf2();
2291
2292 // (1 << Y) pred C -> Y pred Log2(C)
2293 if (!CIsPowerOf2) {
2294 // (1 << Y) < 30 -> Y <= 4
2295 // (1 << Y) <= 30 -> Y <= 4
2296 // (1 << Y) >= 30 -> Y > 4
2297 // (1 << Y) > 30 -> Y > 4
2298 if (Pred == ICmpInst::ICMP_ULT)
2299 Pred = ICmpInst::ICMP_ULE;
2300 else if (Pred == ICmpInst::ICMP_UGE)
2301 Pred = ICmpInst::ICMP_UGT;
2302 }
2303
2304 unsigned CLog2 = Div.logBase2();
2305 return new ICmpInst(Pred, Y, ConstantInt::get(Ty: ShiftType, V: CLog2));
2306 } else if (Cmp.isSigned() && C2->isOne()) {
2307 Constant *BitWidthMinusOne = ConstantInt::get(Ty: ShiftType, V: TypeBits - 1);
2308 // (1 << Y) > 0 -> Y != 31
2309 // (1 << Y) > C -> Y != 31 if C is negative.
2310 if (Pred == ICmpInst::ICMP_SGT && C.sle(RHS: 0))
2311 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2312
2313 // (1 << Y) < 0 -> Y == 31
2314 // (1 << Y) < 1 -> Y == 31
2315 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2316 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2317 if (Pred == ICmpInst::ICMP_SLT && (C - 1).sle(RHS: 0))
2318 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2319 }
2320
2321 return nullptr;
2322}
2323
2324/// Fold icmp (shl X, Y), C.
2325Instruction *InstCombinerImpl::foldICmpShlConstant(ICmpInst &Cmp,
2326 BinaryOperator *Shl,
2327 const APInt &C) {
2328 const APInt *ShiftVal;
2329 if (Cmp.isEquality() && match(V: Shl->getOperand(i_nocapture: 0), P: m_APInt(Res&: ShiftVal)))
2330 return foldICmpShlConstConst(I&: Cmp, A: Shl->getOperand(i_nocapture: 1), AP1: C, AP2: *ShiftVal);
2331
2332 ICmpInst::Predicate Pred = Cmp.getPredicate();
2333 // (icmp pred (shl nuw&nsw X, Y), Csle0)
2334 // -> (icmp pred X, Csle0)
2335 //
2336 // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2337 // so X's must be what is used.
2338 if (C.sle(RHS: 0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2339 return new ICmpInst(Pred, Shl->getOperand(i_nocapture: 0), Cmp.getOperand(i_nocapture: 1));
2340
2341 // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2342 // -> (icmp eq/ne X, 0)
2343 if (ICmpInst::isEquality(P: Pred) && C.isZero() &&
2344 (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2345 return new ICmpInst(Pred, Shl->getOperand(i_nocapture: 0), Cmp.getOperand(i_nocapture: 1));
2346
2347 // (icmp slt (shl nsw X, Y), 0/1)
2348 // -> (icmp slt X, 0/1)
2349 // (icmp sgt (shl nsw X, Y), 0/-1)
2350 // -> (icmp sgt X, 0/-1)
2351 //
2352 // NB: sge/sle with a constant will canonicalize to sgt/slt.
2353 if (Shl->hasNoSignedWrap() &&
2354 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2355 if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2356 return new ICmpInst(Pred, Shl->getOperand(i_nocapture: 0), Cmp.getOperand(i_nocapture: 1));
2357
2358 const APInt *ShiftAmt;
2359 if (!match(V: Shl->getOperand(i_nocapture: 1), P: m_APInt(Res&: ShiftAmt)))
2360 return foldICmpShlLHSC(Cmp, Shl, C);
2361
2362 // Check that the shift amount is in range. If not, don't perform undefined
2363 // shifts. When the shift is visited, it will be simplified.
2364 unsigned TypeBits = C.getBitWidth();
2365 if (ShiftAmt->uge(RHS: TypeBits))
2366 return nullptr;
2367
2368 Value *X = Shl->getOperand(i_nocapture: 0);
2369 Type *ShType = Shl->getType();
2370
2371 // NSW guarantees that we are only shifting out sign bits from the high bits,
2372 // so we can ASHR the compare constant without needing a mask and eliminate
2373 // the shift.
2374 if (Shl->hasNoSignedWrap()) {
2375 if (Pred == ICmpInst::ICMP_SGT) {
2376 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2377 APInt ShiftedC = C.ashr(ShiftAmt: *ShiftAmt);
2378 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2379 }
2380 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2381 C.ashr(ShiftAmt: *ShiftAmt).shl(ShiftAmt: *ShiftAmt) == C) {
2382 APInt ShiftedC = C.ashr(ShiftAmt: *ShiftAmt);
2383 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2384 }
2385 if (Pred == ICmpInst::ICMP_SLT) {
2386 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2387 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2388 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2389 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2390 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2391 APInt ShiftedC = (C - 1).ashr(ShiftAmt: *ShiftAmt) + 1;
2392 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2393 }
2394 }
2395
2396 // NUW guarantees that we are only shifting out zero bits from the high bits,
2397 // so we can LSHR the compare constant without needing a mask and eliminate
2398 // the shift.
2399 if (Shl->hasNoUnsignedWrap()) {
2400 if (Pred == ICmpInst::ICMP_UGT) {
2401 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2402 APInt ShiftedC = C.lshr(ShiftAmt: *ShiftAmt);
2403 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2404 }
2405 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2406 C.lshr(ShiftAmt: *ShiftAmt).shl(ShiftAmt: *ShiftAmt) == C) {
2407 APInt ShiftedC = C.lshr(ShiftAmt: *ShiftAmt);
2408 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2409 }
2410 if (Pred == ICmpInst::ICMP_ULT) {
2411 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2412 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2413 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2414 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2415 assert(C.ugt(0) && "ult 0 should have been eliminated");
2416 APInt ShiftedC = (C - 1).lshr(ShiftAmt: *ShiftAmt) + 1;
2417 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2418 }
2419 }
2420
2421 if (Cmp.isEquality() && Shl->hasOneUse()) {
2422 // Strength-reduce the shift into an 'and'.
2423 Constant *Mask = ConstantInt::get(
2424 Ty: ShType,
2425 V: APInt::getLowBitsSet(numBits: TypeBits, loBitsSet: TypeBits - ShiftAmt->getZExtValue()));
2426 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask, Name: Shl->getName() + ".mask");
2427 Constant *LShrC = ConstantInt::get(Ty: ShType, V: C.lshr(ShiftAmt: *ShiftAmt));
2428 return new ICmpInst(Pred, And, LShrC);
2429 }
2430
2431 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2432 bool TrueIfSigned = false;
2433 if (Shl->hasOneUse() && isSignBitCheck(Pred, RHS: C, TrueIfSigned)) {
2434 // (X << 31) <s 0 --> (X & 1) != 0
2435 Constant *Mask = ConstantInt::get(
2436 Ty: ShType,
2437 V: APInt::getOneBitSet(numBits: TypeBits, BitNo: TypeBits - ShiftAmt->getZExtValue() - 1));
2438 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask, Name: Shl->getName() + ".mask");
2439 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2440 And, Constant::getNullValue(Ty: ShType));
2441 }
2442
2443 // Simplify 'shl' inequality test into 'and' equality test.
2444 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2445 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2446 if ((C + 1).isPowerOf2() &&
2447 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2448 Value *And = Builder.CreateAnd(LHS: X, RHS: (~C).lshr(shiftAmt: ShiftAmt->getZExtValue()));
2449 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2450 : ICmpInst::ICMP_NE,
2451 And, Constant::getNullValue(Ty: ShType));
2452 }
2453 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2454 if (C.isPowerOf2() &&
2455 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2456 Value *And =
2457 Builder.CreateAnd(LHS: X, RHS: (~(C - 1)).lshr(shiftAmt: ShiftAmt->getZExtValue()));
2458 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2459 : ICmpInst::ICMP_NE,
2460 And, Constant::getNullValue(Ty: ShType));
2461 }
2462 }
2463
2464 // Transform (icmp pred iM (shl iM %v, N), C)
2465 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2466 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2467 // This enables us to get rid of the shift in favor of a trunc that may be
2468 // free on the target. It has the additional benefit of comparing to a
2469 // smaller constant that may be more target-friendly.
2470 unsigned Amt = ShiftAmt->getLimitedValue(Limit: TypeBits - 1);
2471 if (Shl->hasOneUse() && Amt != 0 &&
2472 shouldChangeType(FromBitWidth: ShType->getScalarSizeInBits(), ToBitWidth: TypeBits - Amt)) {
2473 ICmpInst::Predicate CmpPred = Pred;
2474 APInt RHSC = C;
2475
2476 if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(predicate: CmpPred)) {
2477 // Try the flipped strictness predicate.
2478 // e.g.:
2479 // icmp ult i64 (shl X, 32), 8589934593 ->
2480 // icmp ule i64 (shl X, 32), 8589934592 ->
2481 // icmp ule i32 (trunc X, i32), 2 ->
2482 // icmp ult i32 (trunc X, i32), 3
2483 if (auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(
2484 Pred, C: ConstantInt::get(Context&: ShType->getContext(), V: C))) {
2485 CmpPred = FlippedStrictness->first;
2486 RHSC = cast<ConstantInt>(Val: FlippedStrictness->second)->getValue();
2487 }
2488 }
2489
2490 if (RHSC.countr_zero() >= Amt) {
2491 Type *TruncTy = ShType->getWithNewBitWidth(NewBitWidth: TypeBits - Amt);
2492 Constant *NewC =
2493 ConstantInt::get(Ty: TruncTy, V: RHSC.ashr(ShiftAmt: *ShiftAmt).trunc(width: TypeBits - Amt));
2494 return new ICmpInst(CmpPred,
2495 Builder.CreateTrunc(V: X, DestTy: TruncTy, Name: "", /*IsNUW=*/false,
2496 IsNSW: Shl->hasNoSignedWrap()),
2497 NewC);
2498 }
2499 }
2500
2501 return nullptr;
2502}
2503
2504/// Fold icmp ({al}shr X, Y), C.
2505Instruction *InstCombinerImpl::foldICmpShrConstant(ICmpInst &Cmp,
2506 BinaryOperator *Shr,
2507 const APInt &C) {
2508 // An exact shr only shifts out zero bits, so:
2509 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2510 Value *X = Shr->getOperand(i_nocapture: 0);
2511 CmpInst::Predicate Pred = Cmp.getPredicate();
2512 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2513 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
2514
2515 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2516 const APInt *ShiftValC;
2517 if (match(V: X, P: m_APInt(Res&: ShiftValC))) {
2518 if (Cmp.isEquality())
2519 return foldICmpShrConstConst(I&: Cmp, A: Shr->getOperand(i_nocapture: 1), AP1: C, AP2: *ShiftValC);
2520
2521 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2522 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2523 bool TrueIfSigned;
2524 if (!IsAShr && ShiftValC->isNegative() &&
2525 isSignBitCheck(Pred, RHS: C, TrueIfSigned))
2526 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2527 Shr->getOperand(i_nocapture: 1),
2528 ConstantInt::getNullValue(Ty: X->getType()));
2529
2530 // If the shifted constant is a power-of-2, test the shift amount directly:
2531 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2532 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2533 if (!IsAShr && ShiftValC->isPowerOf2() &&
2534 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2535 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2536 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2537 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2538
2539 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2540 unsigned ShiftLZ = ShiftValC->countl_zero();
2541 Constant *NewC = ConstantInt::get(Ty: Shr->getType(), V: CmpLZ - ShiftLZ);
2542 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2543 return new ICmpInst(NewPred, Shr->getOperand(i_nocapture: 1), NewC);
2544 }
2545 }
2546
2547 const APInt *ShiftAmtC;
2548 if (!match(V: Shr->getOperand(i_nocapture: 1), P: m_APInt(Res&: ShiftAmtC)))
2549 return nullptr;
2550
2551 // Check that the shift amount is in range. If not, don't perform undefined
2552 // shifts. When the shift is visited it will be simplified.
2553 unsigned TypeBits = C.getBitWidth();
2554 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(Limit: TypeBits);
2555 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2556 return nullptr;
2557
2558 bool IsExact = Shr->isExact();
2559 Type *ShrTy = Shr->getType();
2560 // TODO: If we could guarantee that InstSimplify would handle all of the
2561 // constant-value-based preconditions in the folds below, then we could assert
2562 // those conditions rather than checking them. This is difficult because of
2563 // undef/poison (PR34838).
2564 if (IsAShr && Shr->hasOneUse()) {
2565 if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&
2566 (C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {
2567 // When C - 1 is a power of two and the transform can be legally
2568 // performed, prefer this form so the produced constant is close to a
2569 // power of two.
2570 // icmp slt/ult (ashr exact X, ShAmtC), C
2571 // --> icmp slt/ult X, (C - 1) << ShAmtC) + 1
2572 APInt ShiftedC = (C - 1).shl(shiftAmt: ShAmtVal) + 1;
2573 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2574 }
2575 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2576 // When ShAmtC can be shifted losslessly:
2577 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2578 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2579 APInt ShiftedC = C.shl(shiftAmt: ShAmtVal);
2580 if (ShiftedC.ashr(ShiftAmt: ShAmtVal) == C)
2581 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2582 }
2583 if (Pred == CmpInst::ICMP_SGT) {
2584 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2585 APInt ShiftedC = (C + 1).shl(shiftAmt: ShAmtVal) - 1;
2586 if (!C.isMaxSignedValue() && !(C + 1).shl(shiftAmt: ShAmtVal).isMinSignedValue() &&
2587 (ShiftedC + 1).ashr(ShiftAmt: ShAmtVal) == (C + 1))
2588 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2589 }
2590 if (Pred == CmpInst::ICMP_UGT) {
2591 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2592 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2593 // clause accounts for that pattern.
2594 APInt ShiftedC = (C + 1).shl(shiftAmt: ShAmtVal) - 1;
2595 if ((ShiftedC + 1).ashr(ShiftAmt: ShAmtVal) == (C + 1) ||
2596 (C + 1).shl(shiftAmt: ShAmtVal).isMinSignedValue())
2597 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2598 }
2599
2600 // If the compare constant has significant bits above the lowest sign-bit,
2601 // then convert an unsigned cmp to a test of the sign-bit:
2602 // (ashr X, ShiftC) u> C --> X s< 0
2603 // (ashr X, ShiftC) u< C --> X s> -1
2604 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2605 if (Pred == CmpInst::ICMP_UGT) {
2606 return new ICmpInst(CmpInst::ICMP_SLT, X,
2607 ConstantInt::getNullValue(Ty: ShrTy));
2608 }
2609 if (Pred == CmpInst::ICMP_ULT) {
2610 return new ICmpInst(CmpInst::ICMP_SGT, X,
2611 ConstantInt::getAllOnesValue(Ty: ShrTy));
2612 }
2613 }
2614 } else if (!IsAShr) {
2615 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2616 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2617 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2618 APInt ShiftedC = C.shl(shiftAmt: ShAmtVal);
2619 if (ShiftedC.lshr(shiftAmt: ShAmtVal) == C)
2620 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2621 }
2622 if (Pred == CmpInst::ICMP_UGT) {
2623 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2624 APInt ShiftedC = (C + 1).shl(shiftAmt: ShAmtVal) - 1;
2625 if ((ShiftedC + 1).lshr(shiftAmt: ShAmtVal) == (C + 1))
2626 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2627 }
2628 }
2629
2630 if (!Cmp.isEquality())
2631 return nullptr;
2632
2633 // Handle equality comparisons of shift-by-constant.
2634
2635 // If the comparison constant changes with the shift, the comparison cannot
2636 // succeed (bits of the comparison constant cannot match the shifted value).
2637 // This should be known by InstSimplify and already be folded to true/false.
2638 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2639 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2640 "Expected icmp+shr simplify did not occur.");
2641
2642 // If the bits shifted out are known zero, compare the unshifted value:
2643 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2644 if (Shr->isExact())
2645 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: C << ShAmtVal));
2646
2647 if (C.isZero()) {
2648 // == 0 is u< 1.
2649 if (Pred == CmpInst::ICMP_EQ)
2650 return new ICmpInst(CmpInst::ICMP_ULT, X,
2651 ConstantInt::get(Ty: ShrTy, V: (C + 1).shl(shiftAmt: ShAmtVal)));
2652 else
2653 return new ICmpInst(CmpInst::ICMP_UGT, X,
2654 ConstantInt::get(Ty: ShrTy, V: (C + 1).shl(shiftAmt: ShAmtVal) - 1));
2655 }
2656
2657 if (Shr->hasOneUse()) {
2658 // Canonicalize the shift into an 'and':
2659 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2660 APInt Val(APInt::getHighBitsSet(numBits: TypeBits, hiBitsSet: TypeBits - ShAmtVal));
2661 Constant *Mask = ConstantInt::get(Ty: ShrTy, V: Val);
2662 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask, Name: Shr->getName() + ".mask");
2663 return new ICmpInst(Pred, And, ConstantInt::get(Ty: ShrTy, V: C << ShAmtVal));
2664 }
2665
2666 return nullptr;
2667}
2668
2669Instruction *InstCombinerImpl::foldICmpSRemConstant(ICmpInst &Cmp,
2670 BinaryOperator *SRem,
2671 const APInt &C) {
2672 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2673 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT) {
2674 // Canonicalize unsigned predicates to signed:
2675 // (X s% DivisorC) u> C -> (X s% DivisorC) s< 0
2676 // iff (C s< 0 ? ~C : C) u>= abs(DivisorC)-1
2677 // (X s% DivisorC) u< C+1 -> (X s% DivisorC) s> -1
2678 // iff (C+1 s< 0 ? ~C : C) u>= abs(DivisorC)-1
2679
2680 const APInt *DivisorC;
2681 if (!match(V: SRem->getOperand(i_nocapture: 1), P: m_APInt(Res&: DivisorC)))
2682 return nullptr;
2683
2684 APInt NormalizedC = C;
2685 if (Pred == ICmpInst::ICMP_ULT) {
2686 assert(!NormalizedC.isZero() &&
2687 "ult X, 0 should have been simplified already.");
2688 --NormalizedC;
2689 }
2690 if (C.isNegative())
2691 NormalizedC.flipAllBits();
2692 assert(!DivisorC->isZero() &&
2693 "srem X, 0 should have been simplified already.");
2694 if (!NormalizedC.uge(RHS: DivisorC->abs() - 1))
2695 return nullptr;
2696
2697 Type *Ty = SRem->getType();
2698 if (Pred == ICmpInst::ICMP_UGT)
2699 return new ICmpInst(ICmpInst::ICMP_SLT, SRem,
2700 ConstantInt::getNullValue(Ty));
2701 return new ICmpInst(ICmpInst::ICMP_SGT, SRem,
2702 ConstantInt::getAllOnesValue(Ty));
2703 }
2704 // Match an 'is positive' or 'is negative' comparison of remainder by a
2705 // constant power-of-2 value:
2706 // (X % pow2C) sgt/slt 0
2707 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2708 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2709 return nullptr;
2710
2711 // TODO: The one-use check is standard because we do not typically want to
2712 // create longer instruction sequences, but this might be a special-case
2713 // because srem is not good for analysis or codegen.
2714 if (!SRem->hasOneUse())
2715 return nullptr;
2716
2717 const APInt *DivisorC;
2718 if (!match(V: SRem->getOperand(i_nocapture: 1), P: m_Power2(V&: DivisorC)))
2719 return nullptr;
2720
2721 // For cmp_sgt/cmp_slt only zero valued C is handled.
2722 // For cmp_eq/cmp_ne only positive valued C is handled.
2723 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2724 !C.isZero()) ||
2725 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2726 !C.isStrictlyPositive()))
2727 return nullptr;
2728
2729 // Mask off the sign bit and the modulo bits (low-bits).
2730 Type *Ty = SRem->getType();
2731 APInt SignMask = APInt::getSignMask(BitWidth: Ty->getScalarSizeInBits());
2732 Constant *MaskC = ConstantInt::get(Ty, V: SignMask | (*DivisorC - 1));
2733 Value *And = Builder.CreateAnd(LHS: SRem->getOperand(i_nocapture: 0), RHS: MaskC);
2734
2735 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2736 return new ICmpInst(Pred, And, ConstantInt::get(Ty, V: C));
2737
2738 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2739 // bit is set. Example:
2740 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2741 if (Pred == ICmpInst::ICMP_SGT)
2742 return new ICmpInst(ICmpInst::ICMP_SGT, And, ConstantInt::getNullValue(Ty));
2743
2744 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2745 // bit is set. Example:
2746 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2747 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, V: SignMask));
2748}
2749
2750/// Fold icmp (udiv X, Y), C.
2751Instruction *InstCombinerImpl::foldICmpUDivConstant(ICmpInst &Cmp,
2752 BinaryOperator *UDiv,
2753 const APInt &C) {
2754 ICmpInst::Predicate Pred = Cmp.getPredicate();
2755 Value *X = UDiv->getOperand(i_nocapture: 0);
2756 Value *Y = UDiv->getOperand(i_nocapture: 1);
2757 Type *Ty = UDiv->getType();
2758
2759 const APInt *C2;
2760 if (!match(V: X, P: m_APInt(Res&: C2)))
2761 return nullptr;
2762
2763 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2764
2765 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2766 if (Pred == ICmpInst::ICMP_UGT) {
2767 assert(!C.isMaxValue() &&
2768 "icmp ugt X, UINT_MAX should have been simplified already.");
2769 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2770 ConstantInt::get(Ty, V: C2->udiv(RHS: C + 1)));
2771 }
2772
2773 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2774 if (Pred == ICmpInst::ICMP_ULT) {
2775 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2776 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2777 ConstantInt::get(Ty, V: C2->udiv(RHS: C)));
2778 }
2779
2780 return nullptr;
2781}
2782
2783/// Fold icmp ({su}div X, Y), C.
2784Instruction *InstCombinerImpl::foldICmpDivConstant(ICmpInst &Cmp,
2785 BinaryOperator *Div,
2786 const APInt &C) {
2787 ICmpInst::Predicate Pred = Cmp.getPredicate();
2788 Value *X = Div->getOperand(i_nocapture: 0);
2789 Value *Y = Div->getOperand(i_nocapture: 1);
2790 Type *Ty = Div->getType();
2791 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2792
2793 // If unsigned division and the compare constant is bigger than
2794 // UMAX/2 (negative), there's only one pair of values that satisfies an
2795 // equality check, so eliminate the division:
2796 // (X u/ Y) == C --> (X == C) && (Y == 1)
2797 // (X u/ Y) != C --> (X != C) || (Y != 1)
2798 // Similarly, if signed division and the compare constant is exactly SMIN:
2799 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2800 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2801 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2802 (!DivIsSigned || C.isMinSignedValue())) {
2803 Value *XBig = Builder.CreateICmp(P: Pred, LHS: X, RHS: ConstantInt::get(Ty, V: C));
2804 Value *YOne = Builder.CreateICmp(P: Pred, LHS: Y, RHS: ConstantInt::get(Ty, V: 1));
2805 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2806 return BinaryOperator::Create(Op: Logic, S1: XBig, S2: YOne);
2807 }
2808
2809 // Fold: icmp pred ([us]div X, C2), C -> range test
2810 // Fold this div into the comparison, producing a range check.
2811 // Determine, based on the divide type, what the range is being
2812 // checked. If there is an overflow on the low or high side, remember
2813 // it, otherwise compute the range [low, hi) bounding the new value.
2814 // See: InsertRangeTest above for the kinds of replacements possible.
2815 const APInt *C2;
2816 if (!match(V: Y, P: m_APInt(Res&: C2)))
2817 return nullptr;
2818
2819 // FIXME: If the operand types don't match the type of the divide
2820 // then don't attempt this transform. The code below doesn't have the
2821 // logic to deal with a signed divide and an unsigned compare (and
2822 // vice versa). This is because (x /s C2) <s C produces different
2823 // results than (x /s C2) <u C or (x /u C2) <s C or even
2824 // (x /u C2) <u C. Simply casting the operands and result won't
2825 // work. :( The if statement below tests that condition and bails
2826 // if it finds it.
2827 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
2828 return nullptr;
2829
2830 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2831 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2832 // division-by-constant cases should be present, we can not assert that they
2833 // have happened before we reach this icmp instruction.
2834 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2835 return nullptr;
2836
2837 // Compute Prod = C * C2. We are essentially solving an equation of
2838 // form X / C2 = C. We solve for X by multiplying C2 and C.
2839 // By solving for X, we can turn this into a range check instead of computing
2840 // a divide.
2841 APInt Prod = C * *C2;
2842
2843 // Determine if the product overflows by seeing if the product is not equal to
2844 // the divide. Make sure we do the same kind of divide as in the LHS
2845 // instruction that we're folding.
2846 bool ProdOV = (DivIsSigned ? Prod.sdiv(RHS: *C2) : Prod.udiv(RHS: *C2)) != C;
2847
2848 // If the division is known to be exact, then there is no remainder from the
2849 // divide, so the covered range size is unit, otherwise it is the divisor.
2850 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2851
2852 // Figure out the interval that is being checked. For example, a comparison
2853 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2854 // Compute this interval based on the constants involved and the signedness of
2855 // the compare/divide. This computes a half-open interval, keeping track of
2856 // whether either value in the interval overflows. After analysis each
2857 // overflow variable is set to 0 if it's corresponding bound variable is valid
2858 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2859 int LoOverflow = 0, HiOverflow = 0;
2860 APInt LoBound, HiBound;
2861
2862 if (!DivIsSigned) { // udiv
2863 // e.g. X/5 op 3 --> [15, 20)
2864 LoBound = Prod;
2865 HiOverflow = LoOverflow = ProdOV;
2866 if (!HiOverflow) {
2867 // If this is not an exact divide, then many values in the range collapse
2868 // to the same result value.
2869 HiOverflow = addWithOverflow(Result&: HiBound, In1: LoBound, In2: RangeSize, IsSigned: false);
2870 }
2871 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2872 if (C.isZero()) { // (X / pos) op 0
2873 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2874 LoBound = -(RangeSize - 1);
2875 HiBound = RangeSize;
2876 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2877 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2878 HiOverflow = LoOverflow = ProdOV;
2879 if (!HiOverflow)
2880 HiOverflow = addWithOverflow(Result&: HiBound, In1: Prod, In2: RangeSize, IsSigned: true);
2881 } else { // (X / pos) op neg
2882 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2883 HiBound = Prod + 1;
2884 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2885 if (!LoOverflow) {
2886 APInt DivNeg = -RangeSize;
2887 LoOverflow = addWithOverflow(Result&: LoBound, In1: HiBound, In2: DivNeg, IsSigned: true) ? -1 : 0;
2888 }
2889 }
2890 } else if (C2->isNegative()) { // Divisor is < 0.
2891 if (Div->isExact())
2892 RangeSize.negate();
2893 if (C.isZero()) { // (X / neg) op 0
2894 // e.g. X/-5 op 0 --> [-4, 5)
2895 LoBound = RangeSize + 1;
2896 HiBound = -RangeSize;
2897 if (HiBound == *C2) { // -INTMIN = INTMIN
2898 HiOverflow = 1; // [INTMIN+1, overflow)
2899 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2900 }
2901 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2902 // e.g. X/-5 op 3 --> [-19, -14)
2903 HiBound = Prod + 1;
2904 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2905 if (!LoOverflow)
2906 LoOverflow =
2907 addWithOverflow(Result&: LoBound, In1: HiBound, In2: RangeSize, IsSigned: true) ? -1 : 0;
2908 } else { // (X / neg) op neg
2909 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2910 LoOverflow = HiOverflow = ProdOV;
2911 if (!HiOverflow)
2912 HiOverflow = subWithOverflow(Result&: HiBound, In1: Prod, In2: RangeSize, IsSigned: true);
2913 }
2914
2915 // Dividing by a negative swaps the condition. LT <-> GT
2916 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
2917 }
2918
2919 switch (Pred) {
2920 default:
2921 llvm_unreachable("Unhandled icmp predicate!");
2922 case ICmpInst::ICMP_EQ:
2923 if (LoOverflow && HiOverflow)
2924 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
2925 if (HiOverflow)
2926 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2927 X, ConstantInt::get(Ty, V: LoBound));
2928 if (LoOverflow)
2929 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2930 X, ConstantInt::get(Ty, V: HiBound));
2931 return replaceInstUsesWith(
2932 I&: Cmp, V: insertRangeTest(V: X, Lo: LoBound, Hi: HiBound, isSigned: DivIsSigned, Inside: true));
2933 case ICmpInst::ICMP_NE:
2934 if (LoOverflow && HiOverflow)
2935 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
2936 if (HiOverflow)
2937 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2938 X, ConstantInt::get(Ty, V: LoBound));
2939 if (LoOverflow)
2940 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2941 X, ConstantInt::get(Ty, V: HiBound));
2942 return replaceInstUsesWith(
2943 I&: Cmp, V: insertRangeTest(V: X, Lo: LoBound, Hi: HiBound, isSigned: DivIsSigned, Inside: false));
2944 case ICmpInst::ICMP_ULT:
2945 case ICmpInst::ICMP_SLT:
2946 if (LoOverflow == +1) // Low bound is greater than input range.
2947 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
2948 if (LoOverflow == -1) // Low bound is less than input range.
2949 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
2950 return new ICmpInst(Pred, X, ConstantInt::get(Ty, V: LoBound));
2951 case ICmpInst::ICMP_UGT:
2952 case ICmpInst::ICMP_SGT:
2953 if (HiOverflow == +1) // High bound greater than input range.
2954 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
2955 if (HiOverflow == -1) // High bound less than input range.
2956 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
2957 if (Pred == ICmpInst::ICMP_UGT)
2958 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, V: HiBound));
2959 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, V: HiBound));
2960 }
2961
2962 return nullptr;
2963}
2964
2965/// Fold icmp (sub X, Y), C.
2966Instruction *InstCombinerImpl::foldICmpSubConstant(ICmpInst &Cmp,
2967 BinaryOperator *Sub,
2968 const APInt &C) {
2969 Value *X = Sub->getOperand(i_nocapture: 0), *Y = Sub->getOperand(i_nocapture: 1);
2970 ICmpInst::Predicate Pred = Cmp.getPredicate();
2971 Type *Ty = Sub->getType();
2972
2973 // (SubC - Y) == C) --> Y == (SubC - C)
2974 // (SubC - Y) != C) --> Y != (SubC - C)
2975 Constant *SubC;
2976 if (Cmp.isEquality() && match(V: X, P: m_ImmConstant(C&: SubC))) {
2977 return new ICmpInst(Pred, Y,
2978 ConstantExpr::getSub(C1: SubC, C2: ConstantInt::get(Ty, V: C)));
2979 }
2980
2981 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
2982 const APInt *C2;
2983 APInt SubResult;
2984 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
2985 bool HasNSW = Sub->hasNoSignedWrap();
2986 bool HasNUW = Sub->hasNoUnsignedWrap();
2987 if (match(V: X, P: m_APInt(Res&: C2)) &&
2988 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
2989 !subWithOverflow(Result&: SubResult, In1: *C2, In2: C, IsSigned: Cmp.isSigned()))
2990 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, V: SubResult));
2991
2992 // X - Y == 0 --> X == Y.
2993 // X - Y != 0 --> X != Y.
2994 // TODO: We allow this with multiple uses as long as the other uses are not
2995 // in phis. The phi use check is guarding against a codegen regression
2996 // for a loop test. If the backend could undo this (and possibly
2997 // subsequent transforms), we would not need this hack.
2998 if (Cmp.isEquality() && C.isZero() &&
2999 none_of(Range: (Sub->users()), P: [](const User *U) { return isa<PHINode>(Val: U); }))
3000 return new ICmpInst(Pred, X, Y);
3001
3002 // The following transforms are only worth it if the only user of the subtract
3003 // is the icmp.
3004 // TODO: This is an artificial restriction for all of the transforms below
3005 // that only need a single replacement icmp. Can these use the phi test
3006 // like the transform above here?
3007 if (!Sub->hasOneUse())
3008 return nullptr;
3009
3010 if (Sub->hasNoSignedWrap()) {
3011 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
3012 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3013 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3014
3015 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
3016 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
3017 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3018
3019 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
3020 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
3021 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3022
3023 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
3024 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3025 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3026 }
3027
3028 if (!match(V: X, P: m_APInt(Res&: C2)))
3029 return nullptr;
3030
3031 // C2 - Y <u C -> (Y | (C - 1)) == C2
3032 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
3033 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
3034 (*C2 & (C - 1)) == (C - 1))
3035 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(LHS: Y, RHS: C - 1), X);
3036
3037 // C2 - Y >u C -> (Y | C) != C2
3038 // iff C2 & C == C and C + 1 is a power of 2
3039 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
3040 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(LHS: Y, RHS: C), X);
3041
3042 // We have handled special cases that reduce.
3043 // Canonicalize any remaining sub to add as:
3044 // (C2 - Y) > C --> (Y + ~C2) < ~C
3045 Value *Add = Builder.CreateAdd(LHS: Y, RHS: ConstantInt::get(Ty, V: ~(*C2)), Name: "notsub",
3046 HasNUW, HasNSW);
3047 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, V: ~C));
3048}
3049
3050static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
3051 Value *Op1, IRBuilderBase &Builder,
3052 bool HasOneUse) {
3053 auto FoldConstant = [&](bool Val) {
3054 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3055 if (Op0->getType()->isVectorTy())
3056 Res = ConstantVector::getSplat(
3057 EC: cast<VectorType>(Val: Op0->getType())->getElementCount(), Elt: Res);
3058 return Res;
3059 };
3060
3061 switch (Table.to_ulong()) {
3062 case 0: // 0 0 0 0
3063 return FoldConstant(false);
3064 case 1: // 0 0 0 1
3065 return HasOneUse ? Builder.CreateNot(V: Builder.CreateOr(LHS: Op0, RHS: Op1)) : nullptr;
3066 case 2: // 0 0 1 0
3067 return HasOneUse ? Builder.CreateAnd(LHS: Builder.CreateNot(V: Op0), RHS: Op1) : nullptr;
3068 case 3: // 0 0 1 1
3069 return Builder.CreateNot(V: Op0);
3070 case 4: // 0 1 0 0
3071 return HasOneUse ? Builder.CreateAnd(LHS: Op0, RHS: Builder.CreateNot(V: Op1)) : nullptr;
3072 case 5: // 0 1 0 1
3073 return Builder.CreateNot(V: Op1);
3074 case 6: // 0 1 1 0
3075 return Builder.CreateXor(LHS: Op0, RHS: Op1);
3076 case 7: // 0 1 1 1
3077 return HasOneUse ? Builder.CreateNot(V: Builder.CreateAnd(LHS: Op0, RHS: Op1)) : nullptr;
3078 case 8: // 1 0 0 0
3079 return Builder.CreateAnd(LHS: Op0, RHS: Op1);
3080 case 9: // 1 0 0 1
3081 return HasOneUse ? Builder.CreateNot(V: Builder.CreateXor(LHS: Op0, RHS: Op1)) : nullptr;
3082 case 10: // 1 0 1 0
3083 return Op1;
3084 case 11: // 1 0 1 1
3085 return HasOneUse ? Builder.CreateOr(LHS: Builder.CreateNot(V: Op0), RHS: Op1) : nullptr;
3086 case 12: // 1 1 0 0
3087 return Op0;
3088 case 13: // 1 1 0 1
3089 return HasOneUse ? Builder.CreateOr(LHS: Op0, RHS: Builder.CreateNot(V: Op1)) : nullptr;
3090 case 14: // 1 1 1 0
3091 return Builder.CreateOr(LHS: Op0, RHS: Op1);
3092 case 15: // 1 1 1 1
3093 return FoldConstant(true);
3094 default:
3095 llvm_unreachable("Invalid Operation");
3096 }
3097 return nullptr;
3098}
3099
3100Instruction *InstCombinerImpl::foldICmpBinOpWithConstantViaTruthTable(
3101 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3102 Value *A, *B;
3103 Constant *C1, *C2, *C3, *C4;
3104 if (!(match(V: BO->getOperand(i_nocapture: 0),
3105 P: m_Select(C: m_Value(V&: A), L: m_Constant(C&: C1), R: m_Constant(C&: C2)))) ||
3106 !match(V: BO->getOperand(i_nocapture: 1),
3107 P: m_Select(C: m_Value(V&: B), L: m_Constant(C&: C3), R: m_Constant(C&: C4))) ||
3108 Cmp.getType() != A->getType())
3109 return nullptr;
3110
3111 std::bitset<4> Table;
3112 auto ComputeTable = [&](bool First, bool Second) -> std::optional<bool> {
3113 Constant *L = First ? C1 : C2;
3114 Constant *R = Second ? C3 : C4;
3115 if (auto *Res = ConstantFoldBinaryOpOperands(Opcode: BO->getOpcode(), LHS: L, RHS: R, DL)) {
3116 auto *Val = Res->getType()->isVectorTy() ? Res->getSplatValue() : Res;
3117 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val))
3118 return ICmpInst::compare(LHS: CI->getValue(), RHS: C, Pred: Cmp.getPredicate());
3119 }
3120 return std::nullopt;
3121 };
3122
3123 for (unsigned I = 0; I < 4; ++I) {
3124 bool First = (I >> 1) & 1;
3125 bool Second = I & 1;
3126 if (auto Res = ComputeTable(First, Second))
3127 Table[I] = *Res;
3128 else
3129 return nullptr;
3130 }
3131
3132 // Synthesize optimal logic.
3133 if (auto *Cond = createLogicFromTable(Table, Op0: A, Op1: B, Builder, HasOneUse: BO->hasOneUse()))
3134 return replaceInstUsesWith(I&: Cmp, V: Cond);
3135 return nullptr;
3136}
3137
3138/// Fold icmp (add X, Y), C.
3139Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp,
3140 BinaryOperator *Add,
3141 const APInt &C) {
3142 Value *Y = Add->getOperand(i_nocapture: 1);
3143 Value *X = Add->getOperand(i_nocapture: 0);
3144
3145 Value *Op0, *Op1;
3146 Instruction *Ext0, *Ext1;
3147 const CmpInst::Predicate Pred = Cmp.getPredicate();
3148 if (match(V: Add,
3149 P: m_Add(L: m_CombineAnd(L: m_Instruction(I&: Ext0), R: m_ZExtOrSExt(Op: m_Value(V&: Op0))),
3150 R: m_CombineAnd(L: m_Instruction(I&: Ext1),
3151 R: m_ZExtOrSExt(Op: m_Value(V&: Op1))))) &&
3152 Op0->getType()->isIntOrIntVectorTy(BitWidth: 1) &&
3153 Op1->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
3154 unsigned BW = C.getBitWidth();
3155 std::bitset<4> Table;
3156 auto ComputeTable = [&](bool Op0Val, bool Op1Val) {
3157 APInt Res(BW, 0);
3158 if (Op0Val)
3159 Res += APInt(BW, isa<ZExtInst>(Val: Ext0) ? 1 : -1, /*isSigned=*/true);
3160 if (Op1Val)
3161 Res += APInt(BW, isa<ZExtInst>(Val: Ext1) ? 1 : -1, /*isSigned=*/true);
3162 return ICmpInst::compare(LHS: Res, RHS: C, Pred);
3163 };
3164
3165 Table[0] = ComputeTable(false, false);
3166 Table[1] = ComputeTable(false, true);
3167 Table[2] = ComputeTable(true, false);
3168 Table[3] = ComputeTable(true, true);
3169 if (auto *Cond =
3170 createLogicFromTable(Table, Op0, Op1, Builder, HasOneUse: Add->hasOneUse()))
3171 return replaceInstUsesWith(I&: Cmp, V: Cond);
3172 }
3173 const APInt *C2;
3174 if (Cmp.isEquality() || !match(V: Y, P: m_APInt(Res&: C2)))
3175 return nullptr;
3176
3177 // Fold icmp pred (add X, C2), C.
3178 Type *Ty = Add->getType();
3179
3180 // If the add does not wrap, we can always adjust the compare by subtracting
3181 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3182 // are canonicalized to SGT/SLT/UGT/ULT.
3183 if ((Add->hasNoSignedWrap() &&
3184 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) ||
3185 (Add->hasNoUnsignedWrap() &&
3186 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) {
3187 bool Overflow;
3188 APInt NewC =
3189 Cmp.isSigned() ? C.ssub_ov(RHS: *C2, Overflow) : C.usub_ov(RHS: *C2, Overflow);
3190 // If there is overflow, the result must be true or false.
3191 // TODO: Can we assert there is no overflow because InstSimplify always
3192 // handles those cases?
3193 if (!Overflow)
3194 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
3195 return new ICmpInst(Pred, X, ConstantInt::get(Ty, V: NewC));
3196 }
3197
3198 if (ICmpInst::isUnsigned(predicate: Pred) && Add->hasNoSignedWrap() &&
3199 C.isNonNegative() && (C - *C2).isNonNegative() &&
3200 computeConstantRange(V: X, /*ForSigned=*/true).add(Other: *C2).isAllNonNegative())
3201 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), X,
3202 ConstantInt::get(Ty, V: C - *C2));
3203
3204 auto CR = ConstantRange::makeExactICmpRegion(Pred, Other: C).subtract(CI: *C2);
3205 const APInt &Upper = CR.getUpper();
3206 const APInt &Lower = CR.getLower();
3207 if (Cmp.isSigned()) {
3208 if (Lower.isSignMask())
3209 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, V: Upper));
3210 if (Upper.isSignMask())
3211 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, V: Lower));
3212 } else {
3213 if (Lower.isMinValue())
3214 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, V: Upper));
3215 if (Upper.isMinValue())
3216 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, V: Lower));
3217 }
3218
3219 // This set of folds is intentionally placed after folds that use no-wrapping
3220 // flags because those folds are likely better for later analysis/codegen.
3221 const APInt SMax = APInt::getSignedMaxValue(numBits: Ty->getScalarSizeInBits());
3222 const APInt SMin = APInt::getSignedMinValue(numBits: Ty->getScalarSizeInBits());
3223
3224 // Fold compare with offset to opposite sign compare if it eliminates offset:
3225 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3226 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3227 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, V: -(*C2)));
3228
3229 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3230 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3231 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, V: ~(*C2)));
3232
3233 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3234 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3235 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, V: SMax - C));
3236
3237 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3238 if (Pred == CmpInst::ICMP_SLT && C == *C2)
3239 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, V: C ^ SMax));
3240
3241 // (X + -1) <u C --> X <=u C (if X is never null)
3242 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3243 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
3244 if (llvm::isKnownNonZero(V: X, Q))
3245 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, V: C));
3246 }
3247
3248 if (!Add->hasOneUse())
3249 return nullptr;
3250
3251 // X+C <u C2 -> (X & -C2) == C
3252 // iff C & (C2-1) == 0
3253 // C2 is a power of 2
3254 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3255 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(LHS: X, RHS: -C),
3256 ConstantExpr::getNeg(C: cast<Constant>(Val: Y)));
3257
3258 // X+C2 <u C -> (X & C) == 2C
3259 // iff C == -(C2)
3260 // C2 is a power of 2
3261 if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)
3262 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(LHS: X, RHS: C),
3263 ConstantInt::get(Ty, V: C * 2));
3264
3265 // X+C >u C2 -> (X & ~C2) != C
3266 // iff C & C2 == 0
3267 // C2+1 is a power of 2
3268 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3269 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(LHS: X, RHS: ~C),
3270 ConstantExpr::getNeg(C: cast<Constant>(Val: Y)));
3271
3272 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3273 // to the ult form.
3274 // X+C2 >u C -> X+(C2-C-1) <u ~C
3275 if (Pred == ICmpInst::ICMP_UGT)
3276 return new ICmpInst(ICmpInst::ICMP_ULT,
3277 Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: *C2 - C - 1)),
3278 ConstantInt::get(Ty, V: ~C));
3279
3280 // zext(V) + C2 pred C -> V + C3 pred' C4
3281 Value *V;
3282 if (match(V: X, P: m_ZExt(Op: m_Value(V)))) {
3283 Type *NewCmpTy = V->getType();
3284 unsigned NewCmpBW = NewCmpTy->getScalarSizeInBits();
3285 if (shouldChangeType(From: Ty, To: NewCmpTy)) {
3286 if (CR.getActiveBits() <= NewCmpBW) {
3287 ConstantRange SrcCR = CR.truncate(BitWidth: NewCmpBW);
3288 CmpInst::Predicate EquivPred;
3289 APInt EquivInt;
3290 APInt EquivOffset;
3291
3292 SrcCR.getEquivalentICmp(Pred&: EquivPred, RHS&: EquivInt, Offset&: EquivOffset);
3293 return new ICmpInst(
3294 EquivPred,
3295 EquivOffset.isZero()
3296 ? V
3297 : Builder.CreateAdd(LHS: V, RHS: ConstantInt::get(Ty: NewCmpTy, V: EquivOffset)),
3298 ConstantInt::get(Ty: NewCmpTy, V: EquivInt));
3299 }
3300 }
3301 }
3302
3303 return nullptr;
3304}
3305
3306bool InstCombinerImpl::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS,
3307 Value *&RHS, ConstantInt *&Less,
3308 ConstantInt *&Equal,
3309 ConstantInt *&Greater) {
3310 // TODO: Generalize this to work with other comparison idioms or ensure
3311 // they get canonicalized into this form.
3312
3313 // select i1 (a == b),
3314 // i32 Equal,
3315 // i32 (select i1 (a < b), i32 Less, i32 Greater)
3316 // where Equal, Less and Greater are placeholders for any three constants.
3317 CmpPredicate PredA;
3318 if (!match(V: SI->getCondition(), P: m_ICmp(Pred&: PredA, L: m_Value(V&: LHS), R: m_Value(V&: RHS))) ||
3319 !ICmpInst::isEquality(P: PredA))
3320 return false;
3321 Value *EqualVal = SI->getTrueValue();
3322 Value *UnequalVal = SI->getFalseValue();
3323 // We still can get non-canonical predicate here, so canonicalize.
3324 if (PredA == ICmpInst::ICMP_NE)
3325 std::swap(a&: EqualVal, b&: UnequalVal);
3326 if (!match(V: EqualVal, P: m_ConstantInt(CI&: Equal)))
3327 return false;
3328 CmpPredicate PredB;
3329 Value *LHS2, *RHS2;
3330 if (!match(V: UnequalVal, P: m_Select(C: m_ICmp(Pred&: PredB, L: m_Value(V&: LHS2), R: m_Value(V&: RHS2)),
3331 L: m_ConstantInt(CI&: Less), R: m_ConstantInt(CI&: Greater))))
3332 return false;
3333 // We can get predicate mismatch here, so canonicalize if possible:
3334 // First, ensure that 'LHS' match.
3335 if (LHS2 != LHS) {
3336 // x sgt y <--> y slt x
3337 std::swap(a&: LHS2, b&: RHS2);
3338 PredB = ICmpInst::getSwappedPredicate(pred: PredB);
3339 }
3340 if (LHS2 != LHS)
3341 return false;
3342 // We also need to canonicalize 'RHS'.
3343 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(Val: RHS2)) {
3344 // x sgt C-1 <--> x sge C <--> not(x slt C)
3345 auto FlippedStrictness =
3346 getFlippedStrictnessPredicateAndConstant(Pred: PredB, C: cast<Constant>(Val: RHS2));
3347 if (!FlippedStrictness)
3348 return false;
3349 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3350 "basic correctness failure");
3351 RHS2 = FlippedStrictness->second;
3352 // And kind-of perform the result swap.
3353 std::swap(a&: Less, b&: Greater);
3354 PredB = ICmpInst::ICMP_SLT;
3355 }
3356 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3357}
3358
3359Instruction *InstCombinerImpl::foldICmpSelectConstant(ICmpInst &Cmp,
3360 SelectInst *Select,
3361 ConstantInt *C) {
3362
3363 assert(C && "Cmp RHS should be a constant int!");
3364 // If we're testing a constant value against the result of a three way
3365 // comparison, the result can be expressed directly in terms of the
3366 // original values being compared. Note: We could possibly be more
3367 // aggressive here and remove the hasOneUse test. The original select is
3368 // really likely to simplify or sink when we remove a test of the result.
3369 Value *OrigLHS, *OrigRHS;
3370 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3371 if (Cmp.hasOneUse() &&
3372 matchThreeWayIntCompare(SI: Select, LHS&: OrigLHS, RHS&: OrigRHS, Less&: C1LessThan, Equal&: C2Equal,
3373 Greater&: C3GreaterThan)) {
3374 assert(C1LessThan && C2Equal && C3GreaterThan);
3375
3376 bool TrueWhenLessThan = ICmpInst::compare(
3377 LHS: C1LessThan->getValue(), RHS: C->getValue(), Pred: Cmp.getPredicate());
3378 bool TrueWhenEqual = ICmpInst::compare(LHS: C2Equal->getValue(), RHS: C->getValue(),
3379 Pred: Cmp.getPredicate());
3380 bool TrueWhenGreaterThan = ICmpInst::compare(
3381 LHS: C3GreaterThan->getValue(), RHS: C->getValue(), Pred: Cmp.getPredicate());
3382
3383 // This generates the new instruction that will replace the original Cmp
3384 // Instruction. Instead of enumerating the various combinations when
3385 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3386 // false, we rely on chaining of ORs and future passes of InstCombine to
3387 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3388
3389 // When none of the three constants satisfy the predicate for the RHS (C),
3390 // the entire original Cmp can be simplified to a false.
3391 Value *Cond = Builder.getFalse();
3392 if (TrueWhenLessThan)
3393 Cond = Builder.CreateOr(
3394 LHS: Cond, RHS: Builder.CreateICmp(P: ICmpInst::ICMP_SLT, LHS: OrigLHS, RHS: OrigRHS));
3395 if (TrueWhenEqual)
3396 Cond = Builder.CreateOr(
3397 LHS: Cond, RHS: Builder.CreateICmp(P: ICmpInst::ICMP_EQ, LHS: OrigLHS, RHS: OrigRHS));
3398 if (TrueWhenGreaterThan)
3399 Cond = Builder.CreateOr(
3400 LHS: Cond, RHS: Builder.CreateICmp(P: ICmpInst::ICMP_SGT, LHS: OrigLHS, RHS: OrigRHS));
3401
3402 return replaceInstUsesWith(I&: Cmp, V: Cond);
3403 }
3404 return nullptr;
3405}
3406
3407Instruction *InstCombinerImpl::foldICmpBitCast(ICmpInst &Cmp) {
3408 auto *Bitcast = dyn_cast<BitCastInst>(Val: Cmp.getOperand(i_nocapture: 0));
3409 if (!Bitcast)
3410 return nullptr;
3411
3412 ICmpInst::Predicate Pred = Cmp.getPredicate();
3413 Value *Op1 = Cmp.getOperand(i_nocapture: 1);
3414 Value *BCSrcOp = Bitcast->getOperand(i_nocapture: 0);
3415 Type *SrcType = Bitcast->getSrcTy();
3416 Type *DstType = Bitcast->getType();
3417
3418 // Make sure the bitcast doesn't change between scalar and vector and
3419 // doesn't change the number of vector elements.
3420 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3421 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3422 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3423 Value *X;
3424 if (match(V: BCSrcOp, P: m_SIToFP(Op: m_Value(V&: X)))) {
3425 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3426 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3427 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3428 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3429 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3430 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3431 match(V: Op1, P: m_Zero()))
3432 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: X->getType()));
3433
3434 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3435 if (Pred == ICmpInst::ICMP_SLT && match(V: Op1, P: m_One()))
3436 return new ICmpInst(Pred, X, ConstantInt::get(Ty: X->getType(), V: 1));
3437
3438 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3439 if (Pred == ICmpInst::ICMP_SGT && match(V: Op1, P: m_AllOnes()))
3440 return new ICmpInst(Pred, X,
3441 ConstantInt::getAllOnesValue(Ty: X->getType()));
3442 }
3443
3444 // Zero-equality checks are preserved through unsigned floating-point casts:
3445 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3446 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3447 if (match(V: BCSrcOp, P: m_UIToFP(Op: m_Value(V&: X))))
3448 if (Cmp.isEquality() && match(V: Op1, P: m_Zero()))
3449 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: X->getType()));
3450
3451 const APInt *C;
3452 bool TrueIfSigned;
3453 if (match(V: Op1, P: m_APInt(Res&: C)) && Bitcast->hasOneUse()) {
3454 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3455 // the FP extend/truncate because that cast does not change the sign-bit.
3456 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3457 // The sign-bit is always the most significant bit in those types.
3458 if (isSignBitCheck(Pred, RHS: *C, TrueIfSigned) &&
3459 (match(V: BCSrcOp, P: m_FPExt(Op: m_Value(V&: X))) ||
3460 match(V: BCSrcOp, P: m_FPTrunc(Op: m_Value(V&: X))))) {
3461 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3462 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3463 Type *XType = X->getType();
3464
3465 // We can't currently handle Power style floating point operations here.
3466 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3467 Type *NewType = Builder.getIntNTy(N: XType->getScalarSizeInBits());
3468 if (auto *XVTy = dyn_cast<VectorType>(Val: XType))
3469 NewType = VectorType::get(ElementType: NewType, EC: XVTy->getElementCount());
3470 Value *NewBitcast = Builder.CreateBitCast(V: X, DestTy: NewType);
3471 if (TrueIfSigned)
3472 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3473 ConstantInt::getNullValue(Ty: NewType));
3474 else
3475 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3476 ConstantInt::getAllOnesValue(Ty: NewType));
3477 }
3478 }
3479
3480 // icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)
3481 Type *FPType = SrcType->getScalarType();
3482 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3483 Kind: Attribute::NoImplicitFloat) &&
3484 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3485 FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();
3486 if (Mask & (fcInf | fcZero)) {
3487 if (Pred == ICmpInst::ICMP_NE)
3488 Mask = ~Mask;
3489 return replaceInstUsesWith(I&: Cmp,
3490 V: Builder.createIsFPClass(FPNum: BCSrcOp, Test: Mask));
3491 }
3492 }
3493 }
3494 }
3495
3496 const APInt *C;
3497 if (!match(V: Cmp.getOperand(i_nocapture: 1), P: m_APInt(Res&: C)) || !DstType->isIntegerTy() ||
3498 !SrcType->isIntOrIntVectorTy())
3499 return nullptr;
3500
3501 // If this is checking if all elements of a vector compare are set or not,
3502 // invert the casted vector equality compare and test if all compare
3503 // elements are clear or not. Compare against zero is generally easier for
3504 // analysis and codegen.
3505 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3506 // Example: are all elements equal? --> are zero elements not equal?
3507 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3508 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3509 if (Value *NotBCSrcOp =
3510 getFreelyInverted(V: BCSrcOp, WillInvertAllUses: BCSrcOp->hasOneUse(), Builder: &Builder)) {
3511 Value *Cast = Builder.CreateBitCast(V: NotBCSrcOp, DestTy: DstType);
3512 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(Ty: DstType));
3513 }
3514 }
3515
3516 // If this is checking if all elements of an extended vector are clear or not,
3517 // compare in a narrow type to eliminate the extend:
3518 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3519 Value *X;
3520 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3521 match(V: BCSrcOp, P: m_ZExtOrSExt(Op: m_Value(V&: X)))) {
3522 if (auto *VecTy = dyn_cast<FixedVectorType>(Val: X->getType())) {
3523 Type *NewType = Builder.getIntNTy(N: VecTy->getPrimitiveSizeInBits());
3524 Value *NewCast = Builder.CreateBitCast(V: X, DestTy: NewType);
3525 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(Ty: NewType));
3526 }
3527 }
3528
3529 // Folding: icmp <pred> iN X, C
3530 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3531 // and C is a splat of a K-bit pattern
3532 // and SC is a constant vector = <C', C', C', ..., C'>
3533 // Into:
3534 // %E = extractelement <M x iK> %vec, i32 C'
3535 // icmp <pred> iK %E, trunc(C)
3536 Value *Vec;
3537 ArrayRef<int> Mask;
3538 if (match(V: BCSrcOp, P: m_Shuffle(v1: m_Value(V&: Vec), v2: m_Undef(), mask: m_Mask(Mask)))) {
3539 // Check whether every element of Mask is the same constant
3540 if (all_equal(Range&: Mask)) {
3541 auto *VecTy = cast<VectorType>(Val: SrcType);
3542 auto *EltTy = cast<IntegerType>(Val: VecTy->getElementType());
3543 if (C->isSplat(SplatSizeInBits: EltTy->getBitWidth())) {
3544 // Fold the icmp based on the value of C
3545 // If C is M copies of an iK sized bit pattern,
3546 // then:
3547 // => %E = extractelement <N x iK> %vec, i32 Elem
3548 // icmp <pred> iK %SplatVal, <pattern>
3549 Value *Elem = Builder.getInt32(C: Mask[0]);
3550 Value *Extract = Builder.CreateExtractElement(Vec, Idx: Elem);
3551 Value *NewC = ConstantInt::get(Ty: EltTy, V: C->trunc(width: EltTy->getBitWidth()));
3552 return new ICmpInst(Pred, Extract, NewC);
3553 }
3554 }
3555 }
3556 return nullptr;
3557}
3558
3559/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3560/// where X is some kind of instruction.
3561Instruction *InstCombinerImpl::foldICmpInstWithConstant(ICmpInst &Cmp) {
3562 const APInt *C;
3563
3564 if (match(V: Cmp.getOperand(i_nocapture: 1), P: m_APInt(Res&: C))) {
3565 if (auto *BO = dyn_cast<BinaryOperator>(Val: Cmp.getOperand(i_nocapture: 0)))
3566 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, C: *C))
3567 return I;
3568
3569 if (auto *SI = dyn_cast<SelectInst>(Val: Cmp.getOperand(i_nocapture: 0)))
3570 // For now, we only support constant integers while folding the
3571 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3572 // similar to the cases handled by binary ops above.
3573 if (auto *ConstRHS = dyn_cast<ConstantInt>(Val: Cmp.getOperand(i_nocapture: 1)))
3574 if (Instruction *I = foldICmpSelectConstant(Cmp, Select: SI, C: ConstRHS))
3575 return I;
3576
3577 if (auto *TI = dyn_cast<TruncInst>(Val: Cmp.getOperand(i_nocapture: 0)))
3578 if (Instruction *I = foldICmpTruncConstant(Cmp, Trunc: TI, C: *C))
3579 return I;
3580
3581 if (auto *II = dyn_cast<IntrinsicInst>(Val: Cmp.getOperand(i_nocapture: 0)))
3582 if (Instruction *I = foldICmpIntrinsicWithConstant(ICI&: Cmp, II, C: *C))
3583 return I;
3584
3585 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3586 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3587 // TODO: This checks one-use, but that is not strictly necessary.
3588 Value *Cmp0 = Cmp.getOperand(i_nocapture: 0);
3589 Value *X, *Y;
3590 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3591 (match(V: Cmp0,
3592 P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::ssub_with_overflow>(
3593 Op0: m_Value(V&: X), Op1: m_Value(V&: Y)))) ||
3594 match(V: Cmp0,
3595 P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::usub_with_overflow>(
3596 Op0: m_Value(V&: X), Op1: m_Value(V&: Y))))))
3597 return new ICmpInst(Cmp.getPredicate(), X, Y);
3598 }
3599
3600 if (match(V: Cmp.getOperand(i_nocapture: 1), P: m_APIntAllowPoison(Res&: C)))
3601 return foldICmpInstWithConstantAllowPoison(Cmp, C: *C);
3602
3603 return nullptr;
3604}
3605
3606/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3607/// icmp eq/ne BO, C.
3608Instruction *InstCombinerImpl::foldICmpBinOpEqualityWithConstant(
3609 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3610 // TODO: Some of these folds could work with arbitrary constants, but this
3611 // function is limited to scalar and vector splat constants.
3612 if (!Cmp.isEquality())
3613 return nullptr;
3614
3615 ICmpInst::Predicate Pred = Cmp.getPredicate();
3616 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3617 Constant *RHS = cast<Constant>(Val: Cmp.getOperand(i_nocapture: 1));
3618 Value *BOp0 = BO->getOperand(i_nocapture: 0), *BOp1 = BO->getOperand(i_nocapture: 1);
3619
3620 switch (BO->getOpcode()) {
3621 case Instruction::SRem:
3622 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3623 if (C.isZero() && BO->hasOneUse()) {
3624 const APInt *BOC;
3625 if (match(V: BOp1, P: m_APInt(Res&: BOC)) && BOC->sgt(RHS: 1) && BOC->isPowerOf2()) {
3626 Value *NewRem = Builder.CreateURem(LHS: BOp0, RHS: BOp1, Name: BO->getName());
3627 return new ICmpInst(Pred, NewRem,
3628 Constant::getNullValue(Ty: BO->getType()));
3629 }
3630 }
3631 break;
3632 case Instruction::Add: {
3633 // (A + C2) == C --> A == (C - C2)
3634 // (A + C2) != C --> A != (C - C2)
3635 // TODO: Remove the one-use limitation? See discussion in D58633.
3636 if (Constant *C2 = dyn_cast<Constant>(Val: BOp1)) {
3637 if (BO->hasOneUse())
3638 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(C1: RHS, C2));
3639 } else if (C.isZero()) {
3640 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3641 // efficiently invertible, or if the add has just this one use.
3642 if (Value *NegVal = dyn_castNegVal(V: BOp1))
3643 return new ICmpInst(Pred, BOp0, NegVal);
3644 if (Value *NegVal = dyn_castNegVal(V: BOp0))
3645 return new ICmpInst(Pred, NegVal, BOp1);
3646 if (BO->hasOneUse()) {
3647 // (add nuw A, B) != 0 -> (or A, B) != 0
3648 if (match(V: BO, P: m_NUWAdd(L: m_Value(), R: m_Value()))) {
3649 Value *Or = Builder.CreateOr(LHS: BOp0, RHS: BOp1);
3650 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty: BO->getType()));
3651 }
3652 Value *Neg = Builder.CreateNeg(V: BOp1);
3653 Neg->takeName(V: BO);
3654 return new ICmpInst(Pred, BOp0, Neg);
3655 }
3656 }
3657 break;
3658 }
3659 case Instruction::Xor:
3660 if (Constant *BOC = dyn_cast<Constant>(Val: BOp1)) {
3661 // For the xor case, we can xor two constants together, eliminating
3662 // the explicit xor.
3663 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(C1: RHS, C2: BOC));
3664 } else if (C.isZero()) {
3665 // Replace ((xor A, B) != 0) with (A != B)
3666 return new ICmpInst(Pred, BOp0, BOp1);
3667 }
3668 break;
3669 case Instruction::Or: {
3670 const APInt *BOC;
3671 if (match(V: BOp1, P: m_APInt(Res&: BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3672 // Comparing if all bits outside of a constant mask are set?
3673 // Replace (X | C) == -1 with (X & ~C) == ~C.
3674 // This removes the -1 constant.
3675 Constant *NotBOC = ConstantExpr::getNot(C: cast<Constant>(Val: BOp1));
3676 Value *And = Builder.CreateAnd(LHS: BOp0, RHS: NotBOC);
3677 return new ICmpInst(Pred, And, NotBOC);
3678 }
3679 // (icmp eq (or (select cond, 0, NonZero), Other), 0)
3680 // -> (and cond, (icmp eq Other, 0))
3681 // (icmp ne (or (select cond, NonZero, 0), Other), 0)
3682 // -> (or cond, (icmp ne Other, 0))
3683 Value *Cond, *TV, *FV, *Other, *Sel;
3684 if (C.isZero() &&
3685 match(V: BO,
3686 P: m_OneUse(SubPattern: m_c_Or(L: m_CombineAnd(L: m_Value(V&: Sel),
3687 R: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: TV),
3688 R: m_Value(V&: FV))),
3689 R: m_Value(V&: Other)))) &&
3690 Cond->getType() == Cmp.getType()) {
3691 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
3692 // Easy case is if eq/ne matches whether 0 is trueval/falseval.
3693 if (Pred == ICmpInst::ICMP_EQ
3694 ? (match(V: TV, P: m_Zero()) && isKnownNonZero(V: FV, Q))
3695 : (match(V: FV, P: m_Zero()) && isKnownNonZero(V: TV, Q))) {
3696 Value *Cmp = Builder.CreateICmp(
3697 P: Pred, LHS: Other, RHS: Constant::getNullValue(Ty: Other->getType()));
3698 return BinaryOperator::Create(
3699 Op: Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, S1: Cmp,
3700 S2: Cond);
3701 }
3702 // Harder case is if eq/ne matches whether 0 is falseval/trueval. In this
3703 // case we need to invert the select condition so we need to be careful to
3704 // avoid creating extra instructions.
3705 // (icmp ne (or (select cond, 0, NonZero), Other), 0)
3706 // -> (or (not cond), (icmp ne Other, 0))
3707 // (icmp eq (or (select cond, NonZero, 0), Other), 0)
3708 // -> (and (not cond), (icmp eq Other, 0))
3709 //
3710 // Only do this if the inner select has one use, in which case we are
3711 // replacing `select` with `(not cond)`. Otherwise, we will create more
3712 // uses. NB: Trying to freely invert cond doesn't make sense here, as if
3713 // cond was freely invertable, the select arms would have been inverted.
3714 if (Sel->hasOneUse() &&
3715 (Pred == ICmpInst::ICMP_EQ
3716 ? (match(V: FV, P: m_Zero()) && isKnownNonZero(V: TV, Q))
3717 : (match(V: TV, P: m_Zero()) && isKnownNonZero(V: FV, Q)))) {
3718 Value *NotCond = Builder.CreateNot(V: Cond);
3719 Value *Cmp = Builder.CreateICmp(
3720 P: Pred, LHS: Other, RHS: Constant::getNullValue(Ty: Other->getType()));
3721 return BinaryOperator::Create(
3722 Op: Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, S1: Cmp,
3723 S2: NotCond);
3724 }
3725 }
3726 break;
3727 }
3728 case Instruction::UDiv:
3729 case Instruction::SDiv:
3730 if (BO->isExact()) {
3731 // div exact X, Y eq/ne 0 -> X eq/ne 0
3732 // div exact X, Y eq/ne 1 -> X eq/ne Y
3733 // div exact X, Y eq/ne C ->
3734 // if Y * C never-overflow && OneUse:
3735 // -> Y * C eq/ne X
3736 if (C.isZero())
3737 return new ICmpInst(Pred, BOp0, Constant::getNullValue(Ty: BO->getType()));
3738 else if (C.isOne())
3739 return new ICmpInst(Pred, BOp0, BOp1);
3740 else if (BO->hasOneUse()) {
3741 OverflowResult OR = computeOverflow(
3742 BinaryOp: Instruction::Mul, IsSigned: BO->getOpcode() == Instruction::SDiv, LHS: BOp1,
3743 RHS: Cmp.getOperand(i_nocapture: 1), CxtI: BO);
3744 if (OR == OverflowResult::NeverOverflows) {
3745 Value *YC =
3746 Builder.CreateMul(LHS: BOp1, RHS: ConstantInt::get(Ty: BO->getType(), V: C));
3747 return new ICmpInst(Pred, YC, BOp0);
3748 }
3749 }
3750 }
3751 if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3752 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3753 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3754 return new ICmpInst(NewPred, BOp1, BOp0);
3755 }
3756 break;
3757 default:
3758 break;
3759 }
3760 return nullptr;
3761}
3762
3763static Instruction *foldCtpopPow2Test(ICmpInst &I, IntrinsicInst *CtpopLhs,
3764 const APInt &CRhs,
3765 InstCombiner::BuilderTy &Builder,
3766 const SimplifyQuery &Q) {
3767 assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3768 "Non-ctpop intrin in ctpop fold");
3769 if (!CtpopLhs->hasOneUse())
3770 return nullptr;
3771
3772 // Power of 2 test:
3773 // isPow2OrZero : ctpop(X) u< 2
3774 // isPow2 : ctpop(X) == 1
3775 // NotPow2OrZero: ctpop(X) u> 1
3776 // NotPow2 : ctpop(X) != 1
3777 // If we know any bit of X can be folded to:
3778 // IsPow2 : X & (~Bit) == 0
3779 // NotPow2 : X & (~Bit) != 0
3780 const ICmpInst::Predicate Pred = I.getPredicate();
3781 if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3782 (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3783 Value *Op = CtpopLhs->getArgOperand(i: 0);
3784 KnownBits OpKnown = computeKnownBits(V: Op, DL: Q.DL, AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT);
3785 // No need to check for count > 1, that should be already constant folded.
3786 if (OpKnown.countMinPopulation() == 1) {
3787 Value *And = Builder.CreateAnd(
3788 LHS: Op, RHS: Constant::getIntegerValue(Ty: Op->getType(), V: ~(OpKnown.One)));
3789 return new ICmpInst(
3790 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3791 ? ICmpInst::ICMP_EQ
3792 : ICmpInst::ICMP_NE,
3793 And, Constant::getNullValue(Ty: Op->getType()));
3794 }
3795 }
3796
3797 return nullptr;
3798}
3799
3800/// Fold an equality icmp with LLVM intrinsic and constant operand.
3801Instruction *InstCombinerImpl::foldICmpEqIntrinsicWithConstant(
3802 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3803 Type *Ty = II->getType();
3804 unsigned BitWidth = C.getBitWidth();
3805 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3806
3807 switch (II->getIntrinsicID()) {
3808 case Intrinsic::abs:
3809 // abs(A) == 0 -> A == 0
3810 // abs(A) == INT_MIN -> A == INT_MIN
3811 if (C.isZero() || C.isMinSignedValue())
3812 return new ICmpInst(Pred, II->getArgOperand(i: 0), ConstantInt::get(Ty, V: C));
3813 break;
3814
3815 case Intrinsic::bswap:
3816 // bswap(A) == C -> A == bswap(C)
3817 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3818 ConstantInt::get(Ty, V: C.byteSwap()));
3819
3820 case Intrinsic::bitreverse:
3821 // bitreverse(A) == C -> A == bitreverse(C)
3822 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3823 ConstantInt::get(Ty, V: C.reverseBits()));
3824
3825 case Intrinsic::ctlz:
3826 case Intrinsic::cttz: {
3827 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3828 if (C == BitWidth)
3829 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3830 ConstantInt::getNullValue(Ty));
3831
3832 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3833 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3834 // Limit to one use to ensure we don't increase instruction count.
3835 unsigned Num = C.getLimitedValue(Limit: BitWidth);
3836 if (Num != BitWidth && II->hasOneUse()) {
3837 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3838 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: Num + 1)
3839 : APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: Num + 1);
3840 APInt Mask2 = IsTrailing
3841 ? APInt::getOneBitSet(numBits: BitWidth, BitNo: Num)
3842 : APInt::getOneBitSet(numBits: BitWidth, BitNo: BitWidth - Num - 1);
3843 return new ICmpInst(Pred, Builder.CreateAnd(LHS: II->getArgOperand(i: 0), RHS: Mask1),
3844 ConstantInt::get(Ty, V: Mask2));
3845 }
3846 break;
3847 }
3848
3849 case Intrinsic::ctpop: {
3850 // popcount(A) == 0 -> A == 0 and likewise for !=
3851 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3852 bool IsZero = C.isZero();
3853 if (IsZero || C == BitWidth)
3854 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3855 IsZero ? Constant::getNullValue(Ty)
3856 : Constant::getAllOnesValue(Ty));
3857
3858 break;
3859 }
3860
3861 case Intrinsic::fshl:
3862 case Intrinsic::fshr:
3863 if (II->getArgOperand(i: 0) == II->getArgOperand(i: 1)) {
3864 const APInt *RotAmtC;
3865 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3866 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3867 if (match(V: II->getArgOperand(i: 2), P: m_APInt(Res&: RotAmtC)))
3868 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3869 II->getIntrinsicID() == Intrinsic::fshl
3870 ? ConstantInt::get(Ty, V: C.rotr(rotateAmt: *RotAmtC))
3871 : ConstantInt::get(Ty, V: C.rotl(rotateAmt: *RotAmtC)));
3872 }
3873 break;
3874
3875 case Intrinsic::umax:
3876 case Intrinsic::uadd_sat: {
3877 // uadd.sat(a, b) == 0 -> (a | b) == 0
3878 // umax(a, b) == 0 -> (a | b) == 0
3879 if (C.isZero() && II->hasOneUse()) {
3880 Value *Or = Builder.CreateOr(LHS: II->getArgOperand(i: 0), RHS: II->getArgOperand(i: 1));
3881 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
3882 }
3883 break;
3884 }
3885
3886 case Intrinsic::ssub_sat:
3887 // ssub.sat(a, b) == 0 -> a == b
3888 if (C.isZero())
3889 return new ICmpInst(Pred, II->getArgOperand(i: 0), II->getArgOperand(i: 1));
3890 break;
3891 case Intrinsic::usub_sat: {
3892 // usub.sat(a, b) == 0 -> a <= b
3893 if (C.isZero()) {
3894 ICmpInst::Predicate NewPred =
3895 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3896 return new ICmpInst(NewPred, II->getArgOperand(i: 0), II->getArgOperand(i: 1));
3897 }
3898 break;
3899 }
3900 default:
3901 break;
3902 }
3903
3904 return nullptr;
3905}
3906
3907/// Fold an icmp with LLVM intrinsics
3908static Instruction *
3909foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp,
3910 InstCombiner::BuilderTy &Builder) {
3911 assert(Cmp.isEquality());
3912
3913 ICmpInst::Predicate Pred = Cmp.getPredicate();
3914 Value *Op0 = Cmp.getOperand(i_nocapture: 0);
3915 Value *Op1 = Cmp.getOperand(i_nocapture: 1);
3916 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Val: Op0);
3917 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Val: Op1);
3918 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
3919 return nullptr;
3920
3921 switch (IIOp0->getIntrinsicID()) {
3922 case Intrinsic::bswap:
3923 case Intrinsic::bitreverse:
3924 // If both operands are byte-swapped or bit-reversed, just compare the
3925 // original values.
3926 return new ICmpInst(Pred, IIOp0->getOperand(i_nocapture: 0), IIOp1->getOperand(i_nocapture: 0));
3927 case Intrinsic::fshl:
3928 case Intrinsic::fshr: {
3929 // If both operands are rotated by same amount, just compare the
3930 // original values.
3931 if (IIOp0->getOperand(i_nocapture: 0) != IIOp0->getOperand(i_nocapture: 1))
3932 break;
3933 if (IIOp1->getOperand(i_nocapture: 0) != IIOp1->getOperand(i_nocapture: 1))
3934 break;
3935 if (IIOp0->getOperand(i_nocapture: 2) == IIOp1->getOperand(i_nocapture: 2))
3936 return new ICmpInst(Pred, IIOp0->getOperand(i_nocapture: 0), IIOp1->getOperand(i_nocapture: 0));
3937
3938 // rotate(X, AmtX) == rotate(Y, AmtY)
3939 // -> rotate(X, AmtX - AmtY) == Y
3940 // Do this if either both rotates have one use or if only one has one use
3941 // and AmtX/AmtY are constants.
3942 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
3943 if (OneUses == 2 ||
3944 (OneUses == 1 && match(V: IIOp0->getOperand(i_nocapture: 2), P: m_ImmConstant()) &&
3945 match(V: IIOp1->getOperand(i_nocapture: 2), P: m_ImmConstant()))) {
3946 Value *SubAmt =
3947 Builder.CreateSub(LHS: IIOp0->getOperand(i_nocapture: 2), RHS: IIOp1->getOperand(i_nocapture: 2));
3948 Value *CombinedRotate = Builder.CreateIntrinsic(
3949 RetTy: Op0->getType(), ID: IIOp0->getIntrinsicID(),
3950 Args: {IIOp0->getOperand(i_nocapture: 0), IIOp0->getOperand(i_nocapture: 0), SubAmt});
3951 return new ICmpInst(Pred, IIOp1->getOperand(i_nocapture: 0), CombinedRotate);
3952 }
3953 } break;
3954 default:
3955 break;
3956 }
3957
3958 return nullptr;
3959}
3960
3961/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3962/// where X is some kind of instruction and C is AllowPoison.
3963/// TODO: Move more folds which allow poison to this function.
3964Instruction *
3965InstCombinerImpl::foldICmpInstWithConstantAllowPoison(ICmpInst &Cmp,
3966 const APInt &C) {
3967 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3968 if (auto *II = dyn_cast<IntrinsicInst>(Val: Cmp.getOperand(i_nocapture: 0))) {
3969 switch (II->getIntrinsicID()) {
3970 default:
3971 break;
3972 case Intrinsic::fshl:
3973 case Intrinsic::fshr:
3974 if (Cmp.isEquality() && II->getArgOperand(i: 0) == II->getArgOperand(i: 1)) {
3975 // (rot X, ?) == 0/-1 --> X == 0/-1
3976 if (C.isZero() || C.isAllOnes())
3977 return new ICmpInst(Pred, II->getArgOperand(i: 0), Cmp.getOperand(i_nocapture: 1));
3978 }
3979 break;
3980 }
3981 }
3982
3983 return nullptr;
3984}
3985
3986/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
3987Instruction *InstCombinerImpl::foldICmpBinOpWithConstant(ICmpInst &Cmp,
3988 BinaryOperator *BO,
3989 const APInt &C) {
3990 switch (BO->getOpcode()) {
3991 case Instruction::Xor:
3992 if (Instruction *I = foldICmpXorConstant(Cmp, Xor: BO, C))
3993 return I;
3994 break;
3995 case Instruction::And:
3996 if (Instruction *I = foldICmpAndConstant(Cmp, And: BO, C))
3997 return I;
3998 break;
3999 case Instruction::Or:
4000 if (Instruction *I = foldICmpOrConstant(Cmp, Or: BO, C))
4001 return I;
4002 break;
4003 case Instruction::Mul:
4004 if (Instruction *I = foldICmpMulConstant(Cmp, Mul: BO, C))
4005 return I;
4006 break;
4007 case Instruction::Shl:
4008 if (Instruction *I = foldICmpShlConstant(Cmp, Shl: BO, C))
4009 return I;
4010 break;
4011 case Instruction::LShr:
4012 case Instruction::AShr:
4013 if (Instruction *I = foldICmpShrConstant(Cmp, Shr: BO, C))
4014 return I;
4015 break;
4016 case Instruction::SRem:
4017 if (Instruction *I = foldICmpSRemConstant(Cmp, SRem: BO, C))
4018 return I;
4019 break;
4020 case Instruction::UDiv:
4021 if (Instruction *I = foldICmpUDivConstant(Cmp, UDiv: BO, C))
4022 return I;
4023 [[fallthrough]];
4024 case Instruction::SDiv:
4025 if (Instruction *I = foldICmpDivConstant(Cmp, Div: BO, C))
4026 return I;
4027 break;
4028 case Instruction::Sub:
4029 if (Instruction *I = foldICmpSubConstant(Cmp, Sub: BO, C))
4030 return I;
4031 break;
4032 case Instruction::Add:
4033 if (Instruction *I = foldICmpAddConstant(Cmp, Add: BO, C))
4034 return I;
4035 break;
4036 default:
4037 break;
4038 }
4039
4040 // TODO: These folds could be refactored to be part of the above calls.
4041 if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, C))
4042 return I;
4043
4044 // Fall back to handling `icmp pred (select A ? C1 : C2) binop (select B ? C3
4045 // : C4), C5` pattern, by computing a truth table of the four constant
4046 // variants.
4047 return foldICmpBinOpWithConstantViaTruthTable(Cmp, BO, C);
4048}
4049
4050static Instruction *
4051foldICmpUSubSatOrUAddSatWithConstant(CmpPredicate Pred, SaturatingInst *II,
4052 const APInt &C,
4053 InstCombiner::BuilderTy &Builder) {
4054 // This transform may end up producing more than one instruction for the
4055 // intrinsic, so limit it to one user of the intrinsic.
4056 if (!II->hasOneUse())
4057 return nullptr;
4058
4059 // Let Y = [add/sub]_sat(X, C) pred C2
4060 // SatVal = The saturating value for the operation
4061 // WillWrap = Whether or not the operation will underflow / overflow
4062 // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
4063 // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
4064 //
4065 // When (SatVal pred C2) is true, then
4066 // Y = WillWrap ? true : ((X binop C) pred C2)
4067 // => Y = WillWrap || ((X binop C) pred C2)
4068 // else
4069 // Y = WillWrap ? false : ((X binop C) pred C2)
4070 // => Y = !WillWrap ? ((X binop C) pred C2) : false
4071 // => Y = !WillWrap && ((X binop C) pred C2)
4072 Value *Op0 = II->getOperand(i_nocapture: 0);
4073 Value *Op1 = II->getOperand(i_nocapture: 1);
4074
4075 const APInt *COp1;
4076 // This transform only works when the intrinsic has an integral constant or
4077 // splat vector as the second operand.
4078 if (!match(V: Op1, P: m_APInt(Res&: COp1)))
4079 return nullptr;
4080
4081 APInt SatVal;
4082 switch (II->getIntrinsicID()) {
4083 default:
4084 llvm_unreachable(
4085 "This function only works with usub_sat and uadd_sat for now!");
4086 case Intrinsic::uadd_sat:
4087 SatVal = APInt::getAllOnes(numBits: C.getBitWidth());
4088 break;
4089 case Intrinsic::usub_sat:
4090 SatVal = APInt::getZero(numBits: C.getBitWidth());
4091 break;
4092 }
4093
4094 // Check (SatVal pred C2)
4095 bool SatValCheck = ICmpInst::compare(LHS: SatVal, RHS: C, Pred);
4096
4097 // !WillWrap.
4098 ConstantRange C1 = ConstantRange::makeExactNoWrapRegion(
4099 BinOp: II->getBinaryOp(), Other: *COp1, NoWrapKind: II->getNoWrapKind());
4100
4101 // WillWrap.
4102 if (SatValCheck)
4103 C1 = C1.inverse();
4104
4105 ConstantRange C2 = ConstantRange::makeExactICmpRegion(Pred, Other: C);
4106 if (II->getBinaryOp() == Instruction::Add)
4107 C2 = C2.sub(Other: *COp1);
4108 else
4109 C2 = C2.add(Other: *COp1);
4110
4111 Instruction::BinaryOps CombiningOp =
4112 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4113
4114 std::optional<ConstantRange> Combination;
4115 if (CombiningOp == Instruction::BinaryOps::Or)
4116 Combination = C1.exactUnionWith(CR: C2);
4117 else /* CombiningOp == Instruction::BinaryOps::And */
4118 Combination = C1.exactIntersectWith(CR: C2);
4119
4120 if (!Combination)
4121 return nullptr;
4122
4123 CmpInst::Predicate EquivPred;
4124 APInt EquivInt;
4125 APInt EquivOffset;
4126
4127 Combination->getEquivalentICmp(Pred&: EquivPred, RHS&: EquivInt, Offset&: EquivOffset);
4128
4129 return new ICmpInst(
4130 EquivPred,
4131 Builder.CreateAdd(LHS: Op0, RHS: ConstantInt::get(Ty: Op1->getType(), V: EquivOffset)),
4132 ConstantInt::get(Ty: Op1->getType(), V: EquivInt));
4133}
4134
4135static Instruction *
4136foldICmpOfCmpIntrinsicWithConstant(CmpPredicate Pred, IntrinsicInst *I,
4137 const APInt &C,
4138 InstCombiner::BuilderTy &Builder) {
4139 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4140 switch (Pred) {
4141 case ICmpInst::ICMP_EQ:
4142 case ICmpInst::ICMP_NE:
4143 if (C.isZero())
4144 NewPredicate = Pred;
4145 else if (C.isOne())
4146 NewPredicate =
4147 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
4148 else if (C.isAllOnes())
4149 NewPredicate =
4150 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
4151 break;
4152
4153 case ICmpInst::ICMP_SGT:
4154 if (C.isAllOnes())
4155 NewPredicate = ICmpInst::ICMP_UGE;
4156 else if (C.isZero())
4157 NewPredicate = ICmpInst::ICMP_UGT;
4158 break;
4159
4160 case ICmpInst::ICMP_SLT:
4161 if (C.isZero())
4162 NewPredicate = ICmpInst::ICMP_ULT;
4163 else if (C.isOne())
4164 NewPredicate = ICmpInst::ICMP_ULE;
4165 break;
4166
4167 case ICmpInst::ICMP_ULT:
4168 if (C.ugt(RHS: 1))
4169 NewPredicate = ICmpInst::ICMP_UGE;
4170 break;
4171
4172 case ICmpInst::ICMP_UGT:
4173 if (!C.isZero() && !C.isAllOnes())
4174 NewPredicate = ICmpInst::ICMP_ULT;
4175 break;
4176
4177 default:
4178 break;
4179 }
4180
4181 if (!NewPredicate)
4182 return nullptr;
4183
4184 if (I->getIntrinsicID() == Intrinsic::scmp)
4185 NewPredicate = ICmpInst::getSignedPredicate(Pred: *NewPredicate);
4186 Value *LHS = I->getOperand(i_nocapture: 0);
4187 Value *RHS = I->getOperand(i_nocapture: 1);
4188 return new ICmpInst(*NewPredicate, LHS, RHS);
4189}
4190
4191/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
4192Instruction *InstCombinerImpl::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
4193 IntrinsicInst *II,
4194 const APInt &C) {
4195 ICmpInst::Predicate Pred = Cmp.getPredicate();
4196
4197 // Handle folds that apply for any kind of icmp.
4198 switch (II->getIntrinsicID()) {
4199 default:
4200 break;
4201 case Intrinsic::uadd_sat:
4202 case Intrinsic::usub_sat:
4203 if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(
4204 Pred, II: cast<SaturatingInst>(Val: II), C, Builder))
4205 return Folded;
4206 break;
4207 case Intrinsic::ctpop: {
4208 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
4209 if (Instruction *R = foldCtpopPow2Test(I&: Cmp, CtpopLhs: II, CRhs: C, Builder, Q))
4210 return R;
4211 } break;
4212 case Intrinsic::scmp:
4213 case Intrinsic::ucmp:
4214 if (auto *Folded = foldICmpOfCmpIntrinsicWithConstant(Pred, I: II, C, Builder))
4215 return Folded;
4216 break;
4217 }
4218
4219 if (Cmp.isEquality())
4220 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
4221
4222 Type *Ty = II->getType();
4223 unsigned BitWidth = C.getBitWidth();
4224 switch (II->getIntrinsicID()) {
4225 case Intrinsic::ctpop: {
4226 // (ctpop X > BitWidth - 1) --> X == -1
4227 Value *X = II->getArgOperand(i: 0);
4228 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
4229 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_EQ, S1: X,
4230 S2: ConstantInt::getAllOnesValue(Ty));
4231 // (ctpop X < BitWidth) --> X != -1
4232 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
4233 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_NE, S1: X,
4234 S2: ConstantInt::getAllOnesValue(Ty));
4235 break;
4236 }
4237 case Intrinsic::ctlz: {
4238 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
4239 if (Pred == ICmpInst::ICMP_UGT && C.ult(RHS: BitWidth)) {
4240 unsigned Num = C.getLimitedValue();
4241 APInt Limit = APInt::getOneBitSet(numBits: BitWidth, BitNo: BitWidth - Num - 1);
4242 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_ULT,
4243 S1: II->getArgOperand(i: 0), S2: ConstantInt::get(Ty, V: Limit));
4244 }
4245
4246 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
4247 if (Pred == ICmpInst::ICMP_ULT && C.uge(RHS: 1) && C.ule(RHS: BitWidth)) {
4248 unsigned Num = C.getLimitedValue();
4249 APInt Limit = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: BitWidth - Num);
4250 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_UGT,
4251 S1: II->getArgOperand(i: 0), S2: ConstantInt::get(Ty, V: Limit));
4252 }
4253 break;
4254 }
4255 case Intrinsic::cttz: {
4256 // Limit to one use to ensure we don't increase instruction count.
4257 if (!II->hasOneUse())
4258 return nullptr;
4259
4260 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
4261 if (Pred == ICmpInst::ICMP_UGT && C.ult(RHS: BitWidth)) {
4262 APInt Mask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: C.getLimitedValue() + 1);
4263 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_EQ,
4264 S1: Builder.CreateAnd(LHS: II->getArgOperand(i: 0), RHS: Mask),
4265 S2: ConstantInt::getNullValue(Ty));
4266 }
4267
4268 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
4269 if (Pred == ICmpInst::ICMP_ULT && C.uge(RHS: 1) && C.ule(RHS: BitWidth)) {
4270 APInt Mask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: C.getLimitedValue());
4271 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_NE,
4272 S1: Builder.CreateAnd(LHS: II->getArgOperand(i: 0), RHS: Mask),
4273 S2: ConstantInt::getNullValue(Ty));
4274 }
4275 break;
4276 }
4277 case Intrinsic::ssub_sat:
4278 // ssub.sat(a, b) spred 0 -> a spred b
4279 if (ICmpInst::isSigned(predicate: Pred)) {
4280 if (C.isZero())
4281 return new ICmpInst(Pred, II->getArgOperand(i: 0), II->getArgOperand(i: 1));
4282 // X s<= 0 is cannonicalized to X s< 1
4283 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
4284 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(i: 0),
4285 II->getArgOperand(i: 1));
4286 // X s>= 0 is cannonicalized to X s> -1
4287 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
4288 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(i: 0),
4289 II->getArgOperand(i: 1));
4290 }
4291 break;
4292 default:
4293 break;
4294 }
4295
4296 return nullptr;
4297}
4298
4299/// Handle icmp with constant (but not simple integer constant) RHS.
4300Instruction *InstCombinerImpl::foldICmpInstWithConstantNotInt(ICmpInst &I) {
4301 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
4302 Constant *RHSC = dyn_cast<Constant>(Val: Op1);
4303 Instruction *LHSI = dyn_cast<Instruction>(Val: Op0);
4304 if (!RHSC || !LHSI)
4305 return nullptr;
4306
4307 switch (LHSI->getOpcode()) {
4308 case Instruction::PHI:
4309 if (Instruction *NV = foldOpIntoPhi(I, PN: cast<PHINode>(Val: LHSI)))
4310 return NV;
4311 break;
4312 case Instruction::IntToPtr:
4313 // icmp pred inttoptr(X), null -> icmp pred X, 0
4314 if (RHSC->isNullValue() &&
4315 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(i: 0)->getType())
4316 return new ICmpInst(
4317 I.getPredicate(), LHSI->getOperand(i: 0),
4318 Constant::getNullValue(Ty: LHSI->getOperand(i: 0)->getType()));
4319 break;
4320
4321 case Instruction::Load:
4322 // Try to optimize things like "A[i] > 4" to index computations.
4323 if (GetElementPtrInst *GEP =
4324 dyn_cast<GetElementPtrInst>(Val: LHSI->getOperand(i: 0)))
4325 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: GEP->getOperand(i_nocapture: 0)))
4326 if (Instruction *Res =
4327 foldCmpLoadFromIndexedGlobal(LI: cast<LoadInst>(Val: LHSI), GEP, GV, ICI&: I))
4328 return Res;
4329 break;
4330 }
4331
4332 return nullptr;
4333}
4334
4335Instruction *InstCombinerImpl::foldSelectICmp(CmpPredicate Pred, SelectInst *SI,
4336 Value *RHS, const ICmpInst &I) {
4337 // Try to fold the comparison into the select arms, which will cause the
4338 // select to be converted into a logical and/or.
4339 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
4340 if (Value *Res = simplifyICmpInst(Pred, LHS: Op, RHS, Q: SQ))
4341 return Res;
4342 if (std::optional<bool> Impl = isImpliedCondition(
4343 LHS: SI->getCondition(), RHSPred: Pred, RHSOp0: Op, RHSOp1: RHS, DL, LHSIsTrue: SelectCondIsTrue))
4344 return ConstantInt::get(Ty: I.getType(), V: *Impl);
4345 return nullptr;
4346 };
4347
4348 ConstantInt *CI = nullptr;
4349 Value *Op1 = SimplifyOp(SI->getOperand(i_nocapture: 1), true);
4350 if (Op1)
4351 CI = dyn_cast<ConstantInt>(Val: Op1);
4352
4353 Value *Op2 = SimplifyOp(SI->getOperand(i_nocapture: 2), false);
4354 if (Op2)
4355 CI = dyn_cast<ConstantInt>(Val: Op2);
4356
4357 auto Simplifies = [&](Value *Op, unsigned Idx) {
4358 // A comparison of ucmp/scmp with a constant will fold into an icmp.
4359 const APInt *Dummy;
4360 return Op ||
4361 (isa<CmpIntrinsic>(Val: SI->getOperand(i_nocapture: Idx)) &&
4362 SI->getOperand(i_nocapture: Idx)->hasOneUse() && match(V: RHS, P: m_APInt(Res&: Dummy)));
4363 };
4364
4365 // We only want to perform this transformation if it will not lead to
4366 // additional code. This is true if either both sides of the select
4367 // fold to a constant (in which case the icmp is replaced with a select
4368 // which will usually simplify) or this is the only user of the
4369 // select (in which case we are trading a select+icmp for a simpler
4370 // select+icmp) or all uses of the select can be replaced based on
4371 // dominance information ("Global cases").
4372 bool Transform = false;
4373 if (Op1 && Op2)
4374 Transform = true;
4375 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4376 // Local case
4377 if (SI->hasOneUse())
4378 Transform = true;
4379 // Global cases
4380 else if (CI && !CI->isZero())
4381 // When Op1 is constant try replacing select with second operand.
4382 // Otherwise Op2 is constant and try replacing select with first
4383 // operand.
4384 Transform = replacedSelectWithOperand(SI, Icmp: &I, SIOpd: Op1 ? 2 : 1);
4385 }
4386 if (Transform) {
4387 if (!Op1)
4388 Op1 = Builder.CreateICmp(P: Pred, LHS: SI->getOperand(i_nocapture: 1), RHS, Name: I.getName());
4389 if (!Op2)
4390 Op2 = Builder.CreateICmp(P: Pred, LHS: SI->getOperand(i_nocapture: 2), RHS, Name: I.getName());
4391 return SelectInst::Create(C: SI->getOperand(i_nocapture: 0), S1: Op1, S2: Op2);
4392 }
4393
4394 return nullptr;
4395}
4396
4397// Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)
4398static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,
4399 unsigned Depth = 0) {
4400 if (Not ? match(V, P: m_NegatedPower2OrZero()) : match(V, P: m_LowBitMaskOrZero()))
4401 return true;
4402 if (V->getType()->getScalarSizeInBits() == 1)
4403 return true;
4404 if (Depth++ >= MaxAnalysisRecursionDepth)
4405 return false;
4406 Value *X;
4407 const Instruction *I = dyn_cast<Instruction>(Val: V);
4408 if (!I)
4409 return false;
4410 switch (I->getOpcode()) {
4411 case Instruction::ZExt:
4412 // ZExt(Mask) is a Mask.
4413 return !Not && isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4414 case Instruction::SExt:
4415 // SExt(Mask) is a Mask.
4416 // SExt(~Mask) is a ~Mask.
4417 return isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4418 case Instruction::And:
4419 case Instruction::Or:
4420 // Mask0 | Mask1 is a Mask.
4421 // Mask0 & Mask1 is a Mask.
4422 // ~Mask0 | ~Mask1 is a ~Mask.
4423 // ~Mask0 & ~Mask1 is a ~Mask.
4424 return isMaskOrZero(V: I->getOperand(i: 1), Not, Q, Depth) &&
4425 isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4426 case Instruction::Xor:
4427 if (match(V, P: m_Not(V: m_Value(V&: X))))
4428 return isMaskOrZero(V: X, Not: !Not, Q, Depth);
4429
4430 // (X ^ -X) is a ~Mask
4431 if (Not)
4432 return match(V, P: m_c_Xor(L: m_Value(V&: X), R: m_Neg(V: m_Deferred(V: X))));
4433 // (X ^ (X - 1)) is a Mask
4434 else
4435 return match(V, P: m_c_Xor(L: m_Value(V&: X), R: m_Add(L: m_Deferred(V: X), R: m_AllOnes())));
4436 case Instruction::Select:
4437 // c ? Mask0 : Mask1 is a Mask.
4438 return isMaskOrZero(V: I->getOperand(i: 1), Not, Q, Depth) &&
4439 isMaskOrZero(V: I->getOperand(i: 2), Not, Q, Depth);
4440 case Instruction::Shl:
4441 // (~Mask) << X is a ~Mask.
4442 return Not && isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4443 case Instruction::LShr:
4444 // Mask >> X is a Mask.
4445 return !Not && isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4446 case Instruction::AShr:
4447 // Mask s>> X is a Mask.
4448 // ~Mask s>> X is a ~Mask.
4449 return isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4450 case Instruction::Add:
4451 // Pow2 - 1 is a Mask.
4452 if (!Not && match(V: I->getOperand(i: 1), P: m_AllOnes()))
4453 return isKnownToBeAPowerOfTwo(V: I->getOperand(i: 0), DL: Q.DL, /*OrZero*/ true,
4454 AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT, UseInstrInfo: Depth);
4455 break;
4456 case Instruction::Sub:
4457 // -Pow2 is a ~Mask.
4458 if (Not && match(V: I->getOperand(i: 0), P: m_Zero()))
4459 return isKnownToBeAPowerOfTwo(V: I->getOperand(i: 1), DL: Q.DL, /*OrZero*/ true,
4460 AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT, UseInstrInfo: Depth);
4461 break;
4462 case Instruction::Call: {
4463 if (auto *II = dyn_cast<IntrinsicInst>(Val: I)) {
4464 switch (II->getIntrinsicID()) {
4465 // min/max(Mask0, Mask1) is a Mask.
4466 // min/max(~Mask0, ~Mask1) is a ~Mask.
4467 case Intrinsic::umax:
4468 case Intrinsic::smax:
4469 case Intrinsic::umin:
4470 case Intrinsic::smin:
4471 return isMaskOrZero(V: II->getArgOperand(i: 1), Not, Q, Depth) &&
4472 isMaskOrZero(V: II->getArgOperand(i: 0), Not, Q, Depth);
4473
4474 // In the context of masks, bitreverse(Mask) == ~Mask
4475 case Intrinsic::bitreverse:
4476 return isMaskOrZero(V: II->getArgOperand(i: 0), Not: !Not, Q, Depth);
4477 default:
4478 break;
4479 }
4480 }
4481 break;
4482 }
4483 default:
4484 break;
4485 }
4486 return false;
4487}
4488
4489/// Some comparisons can be simplified.
4490/// In this case, we are looking for comparisons that look like
4491/// a check for a lossy truncation.
4492/// Folds:
4493/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
4494/// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask
4495/// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask
4496/// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask
4497/// Where Mask is some pattern that produces all-ones in low bits:
4498/// (-1 >> y)
4499/// ((-1 << y) >> y) <- non-canonical, has extra uses
4500/// ~(-1 << y)
4501/// ((1 << y) + (-1)) <- non-canonical, has extra uses
4502/// The Mask can be a constant, too.
4503/// For some predicates, the operands are commutative.
4504/// For others, x can only be on a specific side.
4505static Value *foldICmpWithLowBitMaskedVal(CmpPredicate Pred, Value *Op0,
4506 Value *Op1, const SimplifyQuery &Q,
4507 InstCombiner &IC) {
4508
4509 ICmpInst::Predicate DstPred;
4510 switch (Pred) {
4511 case ICmpInst::Predicate::ICMP_EQ:
4512 // x & Mask == x
4513 // x & ~Mask == 0
4514 // ~x | Mask == -1
4515 // -> x u<= Mask
4516 // x & ~Mask == ~Mask
4517 // -> ~Mask u<= x
4518 DstPred = ICmpInst::Predicate::ICMP_ULE;
4519 break;
4520 case ICmpInst::Predicate::ICMP_NE:
4521 // x & Mask != x
4522 // x & ~Mask != 0
4523 // ~x | Mask != -1
4524 // -> x u> Mask
4525 // x & ~Mask != ~Mask
4526 // -> ~Mask u> x
4527 DstPred = ICmpInst::Predicate::ICMP_UGT;
4528 break;
4529 case ICmpInst::Predicate::ICMP_ULT:
4530 // x & Mask u< x
4531 // -> x u> Mask
4532 // x & ~Mask u< ~Mask
4533 // -> ~Mask u> x
4534 DstPred = ICmpInst::Predicate::ICMP_UGT;
4535 break;
4536 case ICmpInst::Predicate::ICMP_UGE:
4537 // x & Mask u>= x
4538 // -> x u<= Mask
4539 // x & ~Mask u>= ~Mask
4540 // -> ~Mask u<= x
4541 DstPred = ICmpInst::Predicate::ICMP_ULE;
4542 break;
4543 case ICmpInst::Predicate::ICMP_SLT:
4544 // x & Mask s< x [iff Mask s>= 0]
4545 // -> x s> Mask
4546 // x & ~Mask s< ~Mask [iff ~Mask != 0]
4547 // -> ~Mask s> x
4548 DstPred = ICmpInst::Predicate::ICMP_SGT;
4549 break;
4550 case ICmpInst::Predicate::ICMP_SGE:
4551 // x & Mask s>= x [iff Mask s>= 0]
4552 // -> x s<= Mask
4553 // x & ~Mask s>= ~Mask [iff ~Mask != 0]
4554 // -> ~Mask s<= x
4555 DstPred = ICmpInst::Predicate::ICMP_SLE;
4556 break;
4557 default:
4558 // We don't support sgt,sle
4559 // ult/ugt are simplified to true/false respectively.
4560 return nullptr;
4561 }
4562
4563 Value *X, *M;
4564 // Put search code in lambda for early positive returns.
4565 auto IsLowBitMask = [&]() {
4566 if (match(V: Op0, P: m_c_And(L: m_Specific(V: Op1), R: m_Value(V&: M)))) {
4567 X = Op1;
4568 // Look for: x & Mask pred x
4569 if (isMaskOrZero(V: M, /*Not=*/false, Q)) {
4570 return !ICmpInst::isSigned(predicate: Pred) ||
4571 (match(V: M, P: m_NonNegative()) || isKnownNonNegative(V: M, SQ: Q));
4572 }
4573
4574 // Look for: x & ~Mask pred ~Mask
4575 if (isMaskOrZero(V: X, /*Not=*/true, Q)) {
4576 return !ICmpInst::isSigned(predicate: Pred) || isKnownNonZero(V: X, Q);
4577 }
4578 return false;
4579 }
4580 if (ICmpInst::isEquality(P: Pred) && match(V: Op1, P: m_AllOnes()) &&
4581 match(V: Op0, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: X), R: m_Value(V&: M))))) {
4582
4583 auto Check = [&]() {
4584 // Look for: ~x | Mask == -1
4585 if (isMaskOrZero(V: M, /*Not=*/false, Q)) {
4586 if (Value *NotX =
4587 IC.getFreelyInverted(V: X, WillInvertAllUses: X->hasOneUse(), Builder: &IC.Builder)) {
4588 X = NotX;
4589 return true;
4590 }
4591 }
4592 return false;
4593 };
4594 if (Check())
4595 return true;
4596 std::swap(a&: X, b&: M);
4597 return Check();
4598 }
4599 if (ICmpInst::isEquality(P: Pred) && match(V: Op1, P: m_Zero()) &&
4600 match(V: Op0, P: m_OneUse(SubPattern: m_And(L: m_Value(V&: X), R: m_Value(V&: M))))) {
4601 auto Check = [&]() {
4602 // Look for: x & ~Mask == 0
4603 if (isMaskOrZero(V: M, /*Not=*/true, Q)) {
4604 if (Value *NotM =
4605 IC.getFreelyInverted(V: M, WillInvertAllUses: M->hasOneUse(), Builder: &IC.Builder)) {
4606 M = NotM;
4607 return true;
4608 }
4609 }
4610 return false;
4611 };
4612 if (Check())
4613 return true;
4614 std::swap(a&: X, b&: M);
4615 return Check();
4616 }
4617 return false;
4618 };
4619
4620 if (!IsLowBitMask())
4621 return nullptr;
4622
4623 return IC.Builder.CreateICmp(P: DstPred, LHS: X, RHS: M);
4624}
4625
4626/// Some comparisons can be simplified.
4627/// In this case, we are looking for comparisons that look like
4628/// a check for a lossy signed truncation.
4629/// Folds: (MaskedBits is a constant.)
4630/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4631/// Into:
4632/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4633/// Where KeptBits = bitwidth(%x) - MaskedBits
4634static Value *
4635foldICmpWithTruncSignExtendedVal(ICmpInst &I,
4636 InstCombiner::BuilderTy &Builder) {
4637 CmpPredicate SrcPred;
4638 Value *X;
4639 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4640 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4641 if (!match(V: &I, P: m_c_ICmp(Pred&: SrcPred,
4642 L: m_OneUse(SubPattern: m_AShr(L: m_Shl(L: m_Value(V&: X), R: m_APInt(Res&: C0)),
4643 R: m_APInt(Res&: C1))),
4644 R: m_Deferred(V: X))))
4645 return nullptr;
4646
4647 // Potential handling of non-splats: for each element:
4648 // * if both are undef, replace with constant 0.
4649 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4650 // * if both are not undef, and are different, bailout.
4651 // * else, only one is undef, then pick the non-undef one.
4652
4653 // The shift amount must be equal.
4654 if (*C0 != *C1)
4655 return nullptr;
4656 const APInt &MaskedBits = *C0;
4657 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4658
4659 ICmpInst::Predicate DstPred;
4660 switch (SrcPred) {
4661 case ICmpInst::Predicate::ICMP_EQ:
4662 // ((%x << MaskedBits) a>> MaskedBits) == %x
4663 // =>
4664 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4665 DstPred = ICmpInst::Predicate::ICMP_ULT;
4666 break;
4667 case ICmpInst::Predicate::ICMP_NE:
4668 // ((%x << MaskedBits) a>> MaskedBits) != %x
4669 // =>
4670 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4671 DstPred = ICmpInst::Predicate::ICMP_UGE;
4672 break;
4673 // FIXME: are more folds possible?
4674 default:
4675 return nullptr;
4676 }
4677
4678 auto *XType = X->getType();
4679 const unsigned XBitWidth = XType->getScalarSizeInBits();
4680 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4681 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4682
4683 // KeptBits = bitwidth(%x) - MaskedBits
4684 const APInt KeptBits = BitWidth - MaskedBits;
4685 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4686 // ICmpCst = (1 << KeptBits)
4687 const APInt ICmpCst = APInt(XBitWidth, 1).shl(ShiftAmt: KeptBits);
4688 assert(ICmpCst.isPowerOf2());
4689 // AddCst = (1 << (KeptBits-1))
4690 const APInt AddCst = ICmpCst.lshr(shiftAmt: 1);
4691 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4692
4693 // T0 = add %x, AddCst
4694 Value *T0 = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty: XType, V: AddCst));
4695 // T1 = T0 DstPred ICmpCst
4696 Value *T1 = Builder.CreateICmp(P: DstPred, LHS: T0, RHS: ConstantInt::get(Ty: XType, V: ICmpCst));
4697
4698 return T1;
4699}
4700
4701// Given pattern:
4702// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4703// we should move shifts to the same hand of 'and', i.e. rewrite as
4704// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4705// We are only interested in opposite logical shifts here.
4706// One of the shifts can be truncated.
4707// If we can, we want to end up creating 'lshr' shift.
4708static Value *
4709foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ,
4710 InstCombiner::BuilderTy &Builder) {
4711 if (!I.isEquality() || !match(V: I.getOperand(i_nocapture: 1), P: m_Zero()) ||
4712 !I.getOperand(i_nocapture: 0)->hasOneUse())
4713 return nullptr;
4714
4715 auto m_AnyLogicalShift = m_LogicalShift(L: m_Value(), R: m_Value());
4716
4717 // Look for an 'and' of two logical shifts, one of which may be truncated.
4718 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4719 Instruction *XShift, *MaybeTruncation, *YShift;
4720 if (!match(
4721 V: I.getOperand(i_nocapture: 0),
4722 P: m_c_And(L: m_CombineAnd(L: m_AnyLogicalShift, R: m_Instruction(I&: XShift)),
4723 R: m_CombineAnd(L: m_TruncOrSelf(Op: m_CombineAnd(
4724 L: m_AnyLogicalShift, R: m_Instruction(I&: YShift))),
4725 R: m_Instruction(I&: MaybeTruncation)))))
4726 return nullptr;
4727
4728 // We potentially looked past 'trunc', but only when matching YShift,
4729 // therefore YShift must have the widest type.
4730 Instruction *WidestShift = YShift;
4731 // Therefore XShift must have the shallowest type.
4732 // Or they both have identical types if there was no truncation.
4733 Instruction *NarrowestShift = XShift;
4734
4735 Type *WidestTy = WidestShift->getType();
4736 Type *NarrowestTy = NarrowestShift->getType();
4737 assert(NarrowestTy == I.getOperand(0)->getType() &&
4738 "We did not look past any shifts while matching XShift though.");
4739 bool HadTrunc = WidestTy != I.getOperand(i_nocapture: 0)->getType();
4740
4741 // If YShift is a 'lshr', swap the shifts around.
4742 if (match(V: YShift, P: m_LShr(L: m_Value(), R: m_Value())))
4743 std::swap(a&: XShift, b&: YShift);
4744
4745 // The shifts must be in opposite directions.
4746 auto XShiftOpcode = XShift->getOpcode();
4747 if (XShiftOpcode == YShift->getOpcode())
4748 return nullptr; // Do not care about same-direction shifts here.
4749
4750 Value *X, *XShAmt, *Y, *YShAmt;
4751 match(V: XShift, P: m_BinOp(L: m_Value(V&: X), R: m_ZExtOrSelf(Op: m_Value(V&: XShAmt))));
4752 match(V: YShift, P: m_BinOp(L: m_Value(V&: Y), R: m_ZExtOrSelf(Op: m_Value(V&: YShAmt))));
4753
4754 // If one of the values being shifted is a constant, then we will end with
4755 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4756 // however, we will need to ensure that we won't increase instruction count.
4757 if (!isa<Constant>(Val: X) && !isa<Constant>(Val: Y)) {
4758 // At least one of the hands of the 'and' should be one-use shift.
4759 if (!match(V: I.getOperand(i_nocapture: 0),
4760 P: m_c_And(L: m_OneUse(SubPattern: m_AnyLogicalShift), R: m_Value())))
4761 return nullptr;
4762 if (HadTrunc) {
4763 // Due to the 'trunc', we will need to widen X. For that either the old
4764 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4765 if (!MaybeTruncation->hasOneUse() &&
4766 !NarrowestShift->getOperand(i: 1)->hasOneUse())
4767 return nullptr;
4768 }
4769 }
4770
4771 // We have two shift amounts from two different shifts. The types of those
4772 // shift amounts may not match. If that's the case let's bailout now.
4773 if (XShAmt->getType() != YShAmt->getType())
4774 return nullptr;
4775
4776 // As input, we have the following pattern:
4777 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4778 // We want to rewrite that as:
4779 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4780 // While we know that originally (Q+K) would not overflow
4781 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
4782 // shift amounts. so it may now overflow in smaller bitwidth.
4783 // To ensure that does not happen, we need to ensure that the total maximal
4784 // shift amount is still representable in that smaller bit width.
4785 unsigned MaximalPossibleTotalShiftAmount =
4786 (WidestTy->getScalarSizeInBits() - 1) +
4787 (NarrowestTy->getScalarSizeInBits() - 1);
4788 APInt MaximalRepresentableShiftAmount =
4789 APInt::getAllOnes(numBits: XShAmt->getType()->getScalarSizeInBits());
4790 if (MaximalRepresentableShiftAmount.ult(RHS: MaximalPossibleTotalShiftAmount))
4791 return nullptr;
4792
4793 // Can we fold (XShAmt+YShAmt) ?
4794 auto *NewShAmt = dyn_cast_or_null<Constant>(
4795 Val: simplifyAddInst(LHS: XShAmt, RHS: YShAmt, /*isNSW=*/IsNSW: false,
4796 /*isNUW=*/IsNUW: false, Q: SQ.getWithInstruction(I: &I)));
4797 if (!NewShAmt)
4798 return nullptr;
4799 if (NewShAmt->getType() != WidestTy) {
4800 NewShAmt =
4801 ConstantFoldCastOperand(Opcode: Instruction::ZExt, C: NewShAmt, DestTy: WidestTy, DL: SQ.DL);
4802 if (!NewShAmt)
4803 return nullptr;
4804 }
4805 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
4806
4807 // Is the new shift amount smaller than the bit width?
4808 // FIXME: could also rely on ConstantRange.
4809 if (!match(V: NewShAmt,
4810 P: m_SpecificInt_ICMP(Predicate: ICmpInst::Predicate::ICMP_ULT,
4811 Threshold: APInt(WidestBitWidth, WidestBitWidth))))
4812 return nullptr;
4813
4814 // An extra legality check is needed if we had trunc-of-lshr.
4815 if (HadTrunc && match(V: WidestShift, P: m_LShr(L: m_Value(), R: m_Value()))) {
4816 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
4817 WidestShift]() {
4818 // It isn't obvious whether it's worth it to analyze non-constants here.
4819 // Also, let's basically give up on non-splat cases, pessimizing vectors.
4820 // If *any* of these preconditions matches we can perform the fold.
4821 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
4822 ? NewShAmt->getSplatValue()
4823 : NewShAmt;
4824 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
4825 if (NewShAmtSplat &&
4826 (NewShAmtSplat->isNullValue() ||
4827 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
4828 return true;
4829 // We consider *min* leading zeros so a single outlier
4830 // blocks the transform as opposed to allowing it.
4831 if (auto *C = dyn_cast<Constant>(Val: NarrowestShift->getOperand(i: 0))) {
4832 KnownBits Known = computeKnownBits(V: C, DL: SQ.DL);
4833 unsigned MinLeadZero = Known.countMinLeadingZeros();
4834 // If the value being shifted has at most lowest bit set we can fold.
4835 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4836 if (MaxActiveBits <= 1)
4837 return true;
4838 // Precondition: NewShAmt u<= countLeadingZeros(C)
4839 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(RHS: MinLeadZero))
4840 return true;
4841 }
4842 if (auto *C = dyn_cast<Constant>(Val: WidestShift->getOperand(i: 0))) {
4843 KnownBits Known = computeKnownBits(V: C, DL: SQ.DL);
4844 unsigned MinLeadZero = Known.countMinLeadingZeros();
4845 // If the value being shifted has at most lowest bit set we can fold.
4846 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4847 if (MaxActiveBits <= 1)
4848 return true;
4849 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
4850 if (NewShAmtSplat) {
4851 APInt AdjNewShAmt =
4852 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
4853 if (AdjNewShAmt.ule(RHS: MinLeadZero))
4854 return true;
4855 }
4856 }
4857 return false; // Can't tell if it's ok.
4858 };
4859 if (!CanFold())
4860 return nullptr;
4861 }
4862
4863 // All good, we can do this fold.
4864 X = Builder.CreateZExt(V: X, DestTy: WidestTy);
4865 Y = Builder.CreateZExt(V: Y, DestTy: WidestTy);
4866 // The shift is the same that was for X.
4867 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
4868 ? Builder.CreateLShr(LHS: X, RHS: NewShAmt)
4869 : Builder.CreateShl(LHS: X, RHS: NewShAmt);
4870 Value *T1 = Builder.CreateAnd(LHS: T0, RHS: Y);
4871 return Builder.CreateICmp(P: I.getPredicate(), LHS: T1,
4872 RHS: Constant::getNullValue(Ty: WidestTy));
4873}
4874
4875/// Fold
4876/// (-1 u/ x) u< y
4877/// ((x * y) ?/ x) != y
4878/// to
4879/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
4880/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
4881/// will mean that we are looking for the opposite answer.
4882Value *InstCombinerImpl::foldMultiplicationOverflowCheck(ICmpInst &I) {
4883 CmpPredicate Pred;
4884 Value *X, *Y;
4885 Instruction *Mul;
4886 Instruction *Div;
4887 bool NeedNegation;
4888 // Look for: (-1 u/ x) u</u>= y
4889 if (!I.isEquality() &&
4890 match(V: &I, P: m_c_ICmp(Pred,
4891 L: m_CombineAnd(L: m_OneUse(SubPattern: m_UDiv(L: m_AllOnes(), R: m_Value(V&: X))),
4892 R: m_Instruction(I&: Div)),
4893 R: m_Value(V&: Y)))) {
4894 Mul = nullptr;
4895
4896 // Are we checking that overflow does not happen, or does happen?
4897 switch (Pred) {
4898 case ICmpInst::Predicate::ICMP_ULT:
4899 NeedNegation = false;
4900 break; // OK
4901 case ICmpInst::Predicate::ICMP_UGE:
4902 NeedNegation = true;
4903 break; // OK
4904 default:
4905 return nullptr; // Wrong predicate.
4906 }
4907 } else // Look for: ((x * y) / x) !=/== y
4908 if (I.isEquality() &&
4909 match(V: &I, P: m_c_ICmp(Pred, L: m_Value(V&: Y),
4910 R: m_CombineAnd(L: m_OneUse(SubPattern: m_IDiv(
4911 L: m_CombineAnd(L: m_c_Mul(L: m_Deferred(V: Y),
4912 R: m_Value(V&: X)),
4913 R: m_Instruction(I&: Mul)),
4914 R: m_Deferred(V: X))),
4915 R: m_Instruction(I&: Div))))) {
4916 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
4917 } else
4918 return nullptr;
4919
4920 BuilderTy::InsertPointGuard Guard(Builder);
4921 // If the pattern included (x * y), we'll want to insert new instructions
4922 // right before that original multiplication so that we can replace it.
4923 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
4924 if (MulHadOtherUses)
4925 Builder.SetInsertPoint(Mul);
4926
4927 CallInst *Call = Builder.CreateIntrinsic(
4928 ID: Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
4929 : Intrinsic::smul_with_overflow,
4930 Types: X->getType(), Args: {X, Y}, /*FMFSource=*/nullptr, Name: "mul");
4931
4932 // If the multiplication was used elsewhere, to ensure that we don't leave
4933 // "duplicate" instructions, replace uses of that original multiplication
4934 // with the multiplication result from the with.overflow intrinsic.
4935 if (MulHadOtherUses)
4936 replaceInstUsesWith(I&: *Mul, V: Builder.CreateExtractValue(Agg: Call, Idxs: 0, Name: "mul.val"));
4937
4938 Value *Res = Builder.CreateExtractValue(Agg: Call, Idxs: 1, Name: "mul.ov");
4939 if (NeedNegation) // This technically increases instruction count.
4940 Res = Builder.CreateNot(V: Res, Name: "mul.not.ov");
4941
4942 // If we replaced the mul, erase it. Do this after all uses of Builder,
4943 // as the mul is used as insertion point.
4944 if (MulHadOtherUses)
4945 eraseInstFromFunction(I&: *Mul);
4946
4947 return Res;
4948}
4949
4950static Instruction *foldICmpXNegX(ICmpInst &I,
4951 InstCombiner::BuilderTy &Builder) {
4952 CmpPredicate Pred;
4953 Value *X;
4954 if (match(V: &I, P: m_c_ICmp(Pred, L: m_NSWNeg(V: m_Value(V&: X)), R: m_Deferred(V: X)))) {
4955
4956 if (ICmpInst::isSigned(predicate: Pred))
4957 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
4958 else if (ICmpInst::isUnsigned(predicate: Pred))
4959 Pred = ICmpInst::getSignedPredicate(Pred);
4960 // else for equality-comparisons just keep the predicate.
4961
4962 return ICmpInst::Create(Op: Instruction::ICmp, Pred, S1: X,
4963 S2: Constant::getNullValue(Ty: X->getType()), Name: I.getName());
4964 }
4965
4966 // A value is not equal to its negation unless that value is 0 or
4967 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
4968 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))) &&
4969 ICmpInst::isEquality(P: Pred)) {
4970 Type *Ty = X->getType();
4971 uint32_t BitWidth = Ty->getScalarSizeInBits();
4972 Constant *MaxSignedVal =
4973 ConstantInt::get(Ty, V: APInt::getSignedMaxValue(numBits: BitWidth));
4974 Value *And = Builder.CreateAnd(LHS: X, RHS: MaxSignedVal);
4975 Constant *Zero = Constant::getNullValue(Ty);
4976 return CmpInst::Create(Op: Instruction::ICmp, Pred, S1: And, S2: Zero);
4977 }
4978
4979 return nullptr;
4980}
4981
4982static Instruction *foldICmpAndXX(ICmpInst &I, const SimplifyQuery &Q,
4983 InstCombinerImpl &IC) {
4984 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *A;
4985 // Normalize and operand as operand 0.
4986 CmpInst::Predicate Pred = I.getPredicate();
4987 if (match(V: Op1, P: m_c_And(L: m_Specific(V: Op0), R: m_Value()))) {
4988 std::swap(a&: Op0, b&: Op1);
4989 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
4990 }
4991
4992 if (!match(V: Op0, P: m_c_And(L: m_Specific(V: Op1), R: m_Value(V&: A))))
4993 return nullptr;
4994
4995 // (icmp (X & Y) u< X --> (X & Y) != X
4996 if (Pred == ICmpInst::ICMP_ULT)
4997 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4998
4999 // (icmp (X & Y) u>= X --> (X & Y) == X
5000 if (Pred == ICmpInst::ICMP_UGE)
5001 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5002
5003 if (ICmpInst::isEquality(P: Pred) && Op0->hasOneUse()) {
5004 // icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and
5005 // Y is non-constant. If Y is constant the `X & C == C` form is preferable
5006 // so don't do this fold.
5007 if (!match(V: Op1, P: m_ImmConstant()))
5008 if (auto *NotOp1 =
5009 IC.getFreelyInverted(V: Op1, WillInvertAllUses: !Op1->hasNUsesOrMore(N: 3), Builder: &IC.Builder))
5010 return new ICmpInst(Pred, IC.Builder.CreateOr(LHS: A, RHS: NotOp1),
5011 Constant::getAllOnesValue(Ty: Op1->getType()));
5012 // icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.
5013 if (auto *NotA = IC.getFreelyInverted(V: A, WillInvertAllUses: A->hasOneUse(), Builder: &IC.Builder))
5014 return new ICmpInst(Pred, IC.Builder.CreateAnd(LHS: Op1, RHS: NotA),
5015 Constant::getNullValue(Ty: Op1->getType()));
5016 }
5017
5018 if (!ICmpInst::isSigned(predicate: Pred))
5019 return nullptr;
5020
5021 KnownBits KnownY = IC.computeKnownBits(V: A, CxtI: &I);
5022 // (X & NegY) spred X --> (X & NegY) upred X
5023 if (KnownY.isNegative())
5024 return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);
5025
5026 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGT)
5027 return nullptr;
5028
5029 if (KnownY.isNonNegative())
5030 // (X & PosY) s<= X --> X s>= 0
5031 // (X & PosY) s> X --> X s< 0
5032 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
5033 Constant::getNullValue(Ty: Op1->getType()));
5034
5035 if (isKnownNegative(V: Op1, SQ: IC.getSimplifyQuery().getWithInstruction(I: &I)))
5036 // (NegX & Y) s<= NegX --> Y s< 0
5037 // (NegX & Y) s> NegX --> Y s>= 0
5038 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), A,
5039 Constant::getNullValue(Ty: A->getType()));
5040
5041 return nullptr;
5042}
5043
5044static Instruction *foldICmpOrXX(ICmpInst &I, const SimplifyQuery &Q,
5045 InstCombinerImpl &IC) {
5046 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *A;
5047
5048 // Normalize or operand as operand 0.
5049 CmpInst::Predicate Pred = I.getPredicate();
5050 if (match(V: Op1, P: m_c_Or(L: m_Specific(V: Op0), R: m_Value(V&: A)))) {
5051 std::swap(a&: Op0, b&: Op1);
5052 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5053 } else if (!match(V: Op0, P: m_c_Or(L: m_Specific(V: Op1), R: m_Value(V&: A)))) {
5054 return nullptr;
5055 }
5056
5057 // icmp (X | Y) u<= X --> (X | Y) == X
5058 if (Pred == ICmpInst::ICMP_ULE)
5059 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5060
5061 // icmp (X | Y) u> X --> (X | Y) != X
5062 if (Pred == ICmpInst::ICMP_UGT)
5063 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5064
5065 if (ICmpInst::isEquality(P: Pred) && Op0->hasOneUse()) {
5066 // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
5067 if (Value *NotOp1 = IC.getFreelyInverted(
5068 V: Op1, WillInvertAllUses: !isa<Constant>(Val: Op1) && !Op1->hasNUsesOrMore(N: 3), Builder: &IC.Builder))
5069 return new ICmpInst(Pred, IC.Builder.CreateAnd(LHS: A, RHS: NotOp1),
5070 Constant::getNullValue(Ty: Op1->getType()));
5071 // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.
5072 if (Value *NotA = IC.getFreelyInverted(V: A, WillInvertAllUses: A->hasOneUse(), Builder: &IC.Builder))
5073 return new ICmpInst(Pred, IC.Builder.CreateOr(LHS: Op1, RHS: NotA),
5074 Constant::getAllOnesValue(Ty: Op1->getType()));
5075 }
5076 return nullptr;
5077}
5078
5079static Instruction *foldICmpXorXX(ICmpInst &I, const SimplifyQuery &Q,
5080 InstCombinerImpl &IC) {
5081 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *A;
5082 // Normalize xor operand as operand 0.
5083 CmpInst::Predicate Pred = I.getPredicate();
5084 if (match(V: Op1, P: m_c_Xor(L: m_Specific(V: Op0), R: m_Value()))) {
5085 std::swap(a&: Op0, b&: Op1);
5086 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5087 }
5088 if (!match(V: Op0, P: m_c_Xor(L: m_Specific(V: Op1), R: m_Value(V&: A))))
5089 return nullptr;
5090
5091 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
5092 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
5093 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
5094 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
5095 CmpInst::Predicate PredOut = CmpInst::getStrictPredicate(pred: Pred);
5096 if (PredOut != Pred && isKnownNonZero(V: A, Q))
5097 return new ICmpInst(PredOut, Op0, Op1);
5098
5099 // These transform work when A is negative.
5100 // X s< X^A, X s<= X^A, X u> X^A, X u>= X^A --> X s< 0
5101 // X s> X^A, X s>= X^A, X u< X^A, X u<= X^A --> X s>= 0
5102 if (match(V: A, P: m_Negative())) {
5103 CmpInst::Predicate NewPred;
5104 switch (ICmpInst::getStrictPredicate(pred: Pred)) {
5105 default:
5106 return nullptr;
5107 case ICmpInst::ICMP_SLT:
5108 case ICmpInst::ICMP_UGT:
5109 NewPred = ICmpInst::ICMP_SLT;
5110 break;
5111 case ICmpInst::ICMP_SGT:
5112 case ICmpInst::ICMP_ULT:
5113 NewPred = ICmpInst::ICMP_SGE;
5114 break;
5115 }
5116 Constant *Const = Constant::getNullValue(Ty: Op0->getType());
5117 return new ICmpInst(NewPred, Op0, Const);
5118 }
5119
5120 return nullptr;
5121}
5122
5123/// Try to fold icmp (binop), X or icmp X, (binop).
5124/// TODO: A large part of this logic is duplicated in InstSimplify's
5125/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
5126/// duplication.
5127Instruction *InstCombinerImpl::foldICmpBinOp(ICmpInst &I,
5128 const SimplifyQuery &SQ) {
5129 const SimplifyQuery Q = SQ.getWithInstruction(I: &I);
5130 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
5131
5132 // Special logic for binary operators.
5133 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Val: Op0);
5134 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Val: Op1);
5135 if (!BO0 && !BO1)
5136 return nullptr;
5137
5138 if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
5139 return NewICmp;
5140
5141 const CmpInst::Predicate Pred = I.getPredicate();
5142 Value *X;
5143
5144 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
5145 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
5146 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: Op1), R: m_Value(V&: X)))) &&
5147 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5148 return new ICmpInst(Pred, Builder.CreateNot(V: Op1), X);
5149 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
5150 if (match(V: Op1, P: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: Op0), R: m_Value(V&: X)))) &&
5151 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5152 return new ICmpInst(Pred, X, Builder.CreateNot(V: Op0));
5153
5154 {
5155 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
5156 Constant *C;
5157 if (match(V: Op0, P: m_OneUse(SubPattern: m_Add(L: m_c_Add(L: m_Specific(V: Op1), R: m_Value(V&: X)),
5158 R: m_ImmConstant(C)))) &&
5159 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
5160 Constant *C2 = ConstantExpr::getNot(C);
5161 return new ICmpInst(Pred, Builder.CreateSub(LHS: C2, RHS: X), Op1);
5162 }
5163 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
5164 if (match(V: Op1, P: m_OneUse(SubPattern: m_Add(L: m_c_Add(L: m_Specific(V: Op0), R: m_Value(V&: X)),
5165 R: m_ImmConstant(C)))) &&
5166 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
5167 Constant *C2 = ConstantExpr::getNot(C);
5168 return new ICmpInst(Pred, Op0, Builder.CreateSub(LHS: C2, RHS: X));
5169 }
5170 }
5171
5172 // (icmp eq/ne (X, -P2), INT_MIN)
5173 // -> (icmp slt/sge X, INT_MIN + P2)
5174 if (ICmpInst::isEquality(P: Pred) && BO0 &&
5175 match(V: I.getOperand(i_nocapture: 1), P: m_SignMask()) &&
5176 match(V: BO0, P: m_And(L: m_Value(), R: m_NegatedPower2OrZero()))) {
5177 // Will Constant fold.
5178 Value *NewC = Builder.CreateSub(LHS: I.getOperand(i_nocapture: 1), RHS: BO0->getOperand(i_nocapture: 1));
5179 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SLT
5180 : ICmpInst::ICMP_SGE,
5181 BO0->getOperand(i_nocapture: 0), NewC);
5182 }
5183
5184 {
5185 // Similar to above: an unsigned overflow comparison may use offset + mask:
5186 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
5187 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
5188 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
5189 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
5190 BinaryOperator *BO;
5191 const APInt *C;
5192 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
5193 match(V: Op0, P: m_And(L: m_BinOp(I&: BO), R: m_LowBitMask(V&: C))) &&
5194 match(V: BO, P: m_Add(L: m_Specific(V: Op1), R: m_SpecificIntAllowPoison(V: *C)))) {
5195 CmpInst::Predicate NewPred =
5196 Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
5197 Constant *Zero = ConstantInt::getNullValue(Ty: Op1->getType());
5198 return new ICmpInst(NewPred, Op1, Zero);
5199 }
5200
5201 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5202 match(V: Op1, P: m_And(L: m_BinOp(I&: BO), R: m_LowBitMask(V&: C))) &&
5203 match(V: BO, P: m_Add(L: m_Specific(V: Op0), R: m_SpecificIntAllowPoison(V: *C)))) {
5204 CmpInst::Predicate NewPred =
5205 Pred == ICmpInst::ICMP_UGT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
5206 Constant *Zero = ConstantInt::getNullValue(Ty: Op1->getType());
5207 return new ICmpInst(NewPred, Op0, Zero);
5208 }
5209 }
5210
5211 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
5212 bool Op0HasNUW = false, Op1HasNUW = false;
5213 bool Op0HasNSW = false, Op1HasNSW = false;
5214 // Analyze the case when either Op0 or Op1 is an add instruction.
5215 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
5216 auto hasNoWrapProblem = [](const BinaryOperator &BO, CmpInst::Predicate Pred,
5217 bool &HasNSW, bool &HasNUW) -> bool {
5218 if (isa<OverflowingBinaryOperator>(Val: BO)) {
5219 HasNUW = BO.hasNoUnsignedWrap();
5220 HasNSW = BO.hasNoSignedWrap();
5221 return ICmpInst::isEquality(P: Pred) ||
5222 (CmpInst::isUnsigned(predicate: Pred) && HasNUW) ||
5223 (CmpInst::isSigned(predicate: Pred) && HasNSW);
5224 } else if (BO.getOpcode() == Instruction::Or) {
5225 HasNUW = true;
5226 HasNSW = true;
5227 return true;
5228 } else {
5229 return false;
5230 }
5231 };
5232 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5233
5234 if (BO0) {
5235 match(V: BO0, P: m_AddLike(L: m_Value(V&: A), R: m_Value(V&: B)));
5236 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5237 }
5238 if (BO1) {
5239 match(V: BO1, P: m_AddLike(L: m_Value(V&: C), R: m_Value(V&: D)));
5240 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5241 }
5242
5243 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5244 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5245 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5246 return new ICmpInst(Pred, A == Op1 ? B : A,
5247 Constant::getNullValue(Ty: Op1->getType()));
5248
5249 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5250 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5251 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5252 return new ICmpInst(Pred, Constant::getNullValue(Ty: Op0->getType()),
5253 C == Op0 ? D : C);
5254
5255 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
5256 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
5257 NoOp1WrapProblem) {
5258 // Determine Y and Z in the form icmp (X+Y), (X+Z).
5259 Value *Y, *Z;
5260 if (A == C) {
5261 // C + B == C + D -> B == D
5262 Y = B;
5263 Z = D;
5264 } else if (A == D) {
5265 // D + B == C + D -> B == C
5266 Y = B;
5267 Z = C;
5268 } else if (B == C) {
5269 // A + C == C + D -> A == D
5270 Y = A;
5271 Z = D;
5272 } else {
5273 assert(B == D);
5274 // A + D == C + D -> A == C
5275 Y = A;
5276 Z = C;
5277 }
5278 return new ICmpInst(Pred, Y, Z);
5279 }
5280
5281 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5282 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
5283 match(V: B, P: m_AllOnes()))
5284 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
5285
5286 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5287 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
5288 match(V: B, P: m_AllOnes()))
5289 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
5290
5291 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5292 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(V: B, P: m_One()))
5293 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
5294
5295 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5296 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(V: B, P: m_One()))
5297 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
5298
5299 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5300 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
5301 match(V: D, P: m_AllOnes()))
5302 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
5303
5304 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5305 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
5306 match(V: D, P: m_AllOnes()))
5307 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
5308
5309 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5310 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(V: D, P: m_One()))
5311 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
5312
5313 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5314 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(V: D, P: m_One()))
5315 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
5316
5317 // TODO: The subtraction-related identities shown below also hold, but
5318 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
5319 // wouldn't happen even if they were implemented.
5320 //
5321 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5322 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5323 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5324 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5325
5326 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5327 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(V: B, P: m_One()))
5328 return new ICmpInst(CmpInst::ICMP_ULT, A, Op1);
5329
5330 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5331 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(V: B, P: m_One()))
5332 return new ICmpInst(CmpInst::ICMP_UGE, A, Op1);
5333
5334 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5335 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(V: D, P: m_One()))
5336 return new ICmpInst(CmpInst::ICMP_UGT, Op0, C);
5337
5338 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5339 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(V: D, P: m_One()))
5340 return new ICmpInst(CmpInst::ICMP_ULE, Op0, C);
5341
5342 // if C1 has greater magnitude than C2:
5343 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5344 // s.t. C3 = C1 - C2
5345 //
5346 // if C2 has greater magnitude than C1:
5347 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5348 // s.t. C3 = C2 - C1
5349 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5350 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5351 const APInt *AP1, *AP2;
5352 // TODO: Support non-uniform vectors.
5353 // TODO: Allow poison passthrough if B or D's element is poison.
5354 if (match(V: B, P: m_APIntAllowPoison(Res&: AP1)) &&
5355 match(V: D, P: m_APIntAllowPoison(Res&: AP2)) &&
5356 AP1->isNegative() == AP2->isNegative()) {
5357 APInt AP1Abs = AP1->abs();
5358 APInt AP2Abs = AP2->abs();
5359 if (AP1Abs.uge(RHS: AP2Abs)) {
5360 APInt Diff = *AP1 - *AP2;
5361 Constant *C3 = Constant::getIntegerValue(Ty: BO0->getType(), V: Diff);
5362 Value *NewAdd = Builder.CreateAdd(
5363 LHS: A, RHS: C3, Name: "", HasNUW: Op0HasNUW && Diff.ule(RHS: *AP1), HasNSW: Op0HasNSW);
5364 return new ICmpInst(Pred, NewAdd, C);
5365 } else {
5366 APInt Diff = *AP2 - *AP1;
5367 Constant *C3 = Constant::getIntegerValue(Ty: BO0->getType(), V: Diff);
5368 Value *NewAdd = Builder.CreateAdd(
5369 LHS: C, RHS: C3, Name: "", HasNUW: Op1HasNUW && Diff.ule(RHS: *AP2), HasNSW: Op1HasNSW);
5370 return new ICmpInst(Pred, A, NewAdd);
5371 }
5372 }
5373 Constant *Cst1, *Cst2;
5374 if (match(V: B, P: m_ImmConstant(C&: Cst1)) && match(V: D, P: m_ImmConstant(C&: Cst2)) &&
5375 ICmpInst::isEquality(P: Pred)) {
5376 Constant *Diff = ConstantExpr::getSub(C1: Cst2, C2: Cst1);
5377 Value *NewAdd = Builder.CreateAdd(LHS: C, RHS: Diff);
5378 return new ICmpInst(Pred, A, NewAdd);
5379 }
5380 }
5381
5382 // Analyze the case when either Op0 or Op1 is a sub instruction.
5383 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5384 A = nullptr;
5385 B = nullptr;
5386 C = nullptr;
5387 D = nullptr;
5388 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5389 A = BO0->getOperand(i_nocapture: 0);
5390 B = BO0->getOperand(i_nocapture: 1);
5391 }
5392 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5393 C = BO1->getOperand(i_nocapture: 0);
5394 D = BO1->getOperand(i_nocapture: 1);
5395 }
5396
5397 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5398 if (A == Op1 && NoOp0WrapProblem)
5399 return new ICmpInst(Pred, Constant::getNullValue(Ty: Op1->getType()), B);
5400 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5401 if (C == Op0 && NoOp1WrapProblem)
5402 return new ICmpInst(Pred, D, Constant::getNullValue(Ty: Op0->getType()));
5403
5404 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5405 // (A - B) u>/u<= A --> B u>/u<= A
5406 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5407 return new ICmpInst(Pred, B, A);
5408 // C u</u>= (C - D) --> C u</u>= D
5409 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5410 return new ICmpInst(Pred, C, D);
5411 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5412 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5413 isKnownNonZero(V: B, Q))
5414 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(pred: Pred), B, A);
5415 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5416 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5417 isKnownNonZero(V: D, Q))
5418 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(pred: Pred), C, D);
5419
5420 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
5421 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
5422 return new ICmpInst(Pred, A, C);
5423
5424 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
5425 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
5426 return new ICmpInst(Pred, D, B);
5427
5428 // icmp (0-X) < cst --> x > -cst
5429 if (NoOp0WrapProblem && ICmpInst::isSigned(predicate: Pred)) {
5430 Value *X;
5431 if (match(V: BO0, P: m_Neg(V: m_Value(V&: X))))
5432 if (Constant *RHSC = dyn_cast<Constant>(Val: Op1))
5433 if (RHSC->isNotMinSignedValue())
5434 return new ICmpInst(I.getSwappedPredicate(), X,
5435 ConstantExpr::getNeg(C: RHSC));
5436 }
5437
5438 if (Instruction *R = foldICmpXorXX(I, Q, IC&: *this))
5439 return R;
5440 if (Instruction *R = foldICmpOrXX(I, Q, IC&: *this))
5441 return R;
5442
5443 {
5444 // Try to remove shared multiplier from comparison:
5445 // X * Z pred Y * Z
5446 Value *X, *Y, *Z;
5447 if ((match(V: Op0, P: m_Mul(L: m_Value(V&: X), R: m_Value(V&: Z))) &&
5448 match(V: Op1, P: m_c_Mul(L: m_Specific(V: Z), R: m_Value(V&: Y)))) ||
5449 (match(V: Op0, P: m_Mul(L: m_Value(V&: Z), R: m_Value(V&: X))) &&
5450 match(V: Op1, P: m_c_Mul(L: m_Specific(V: Z), R: m_Value(V&: Y))))) {
5451 if (ICmpInst::isSigned(predicate: Pred)) {
5452 if (Op0HasNSW && Op1HasNSW) {
5453 KnownBits ZKnown = computeKnownBits(V: Z, CxtI: &I);
5454 if (ZKnown.isStrictlyPositive())
5455 return new ICmpInst(Pred, X, Y);
5456 if (ZKnown.isNegative())
5457 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), X, Y);
5458 Value *LessThan = simplifyICmpInst(Pred: ICmpInst::ICMP_SLT, LHS: X, RHS: Y,
5459 Q: SQ.getWithInstruction(I: &I));
5460 if (LessThan && match(V: LessThan, P: m_One()))
5461 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Z,
5462 Constant::getNullValue(Ty: Z->getType()));
5463 Value *GreaterThan = simplifyICmpInst(Pred: ICmpInst::ICMP_SGT, LHS: X, RHS: Y,
5464 Q: SQ.getWithInstruction(I: &I));
5465 if (GreaterThan && match(V: GreaterThan, P: m_One()))
5466 return new ICmpInst(Pred, Z, Constant::getNullValue(Ty: Z->getType()));
5467 }
5468 } else {
5469 bool NonZero;
5470 if (ICmpInst::isEquality(P: Pred)) {
5471 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5472 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5473 isKnownNonEqual(V1: X, V2: Y, SQ))
5474 return new ICmpInst(Pred, Z, Constant::getNullValue(Ty: Z->getType()));
5475
5476 KnownBits ZKnown = computeKnownBits(V: Z, CxtI: &I);
5477 // if Z % 2 != 0
5478 // X * Z eq/ne Y * Z -> X eq/ne Y
5479 if (ZKnown.countMaxTrailingZeros() == 0)
5480 return new ICmpInst(Pred, X, Y);
5481 NonZero = !ZKnown.One.isZero() || isKnownNonZero(V: Z, Q);
5482 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5483 // X * Z eq/ne Y * Z -> X eq/ne Y
5484 if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)
5485 return new ICmpInst(Pred, X, Y);
5486 } else
5487 NonZero = isKnownNonZero(V: Z, Q);
5488
5489 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5490 // X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
5491 if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)
5492 return new ICmpInst(Pred, X, Y);
5493 }
5494 }
5495 }
5496
5497 BinaryOperator *SRem = nullptr;
5498 // icmp (srem X, Y), Y
5499 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(i_nocapture: 1))
5500 SRem = BO0;
5501 // icmp Y, (srem X, Y)
5502 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5503 Op0 == BO1->getOperand(i_nocapture: 1))
5504 SRem = BO1;
5505 if (SRem) {
5506 // We don't check hasOneUse to avoid increasing register pressure because
5507 // the value we use is the same value this instruction was already using.
5508 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(pred: Pred) : Pred) {
5509 default:
5510 break;
5511 case ICmpInst::ICMP_EQ:
5512 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
5513 case ICmpInst::ICMP_NE:
5514 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
5515 case ICmpInst::ICMP_SGT:
5516 case ICmpInst::ICMP_SGE:
5517 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(i_nocapture: 1),
5518 Constant::getAllOnesValue(Ty: SRem->getType()));
5519 case ICmpInst::ICMP_SLT:
5520 case ICmpInst::ICMP_SLE:
5521 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(i_nocapture: 1),
5522 Constant::getNullValue(Ty: SRem->getType()));
5523 }
5524 }
5525
5526 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5527 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5528 BO0->getOperand(i_nocapture: 1) == BO1->getOperand(i_nocapture: 1)) {
5529 switch (BO0->getOpcode()) {
5530 default:
5531 break;
5532 case Instruction::Add:
5533 case Instruction::Sub:
5534 case Instruction::Xor: {
5535 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5536 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5537
5538 const APInt *C;
5539 if (match(V: BO0->getOperand(i_nocapture: 1), P: m_APInt(Res&: C))) {
5540 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5541 if (C->isSignMask()) {
5542 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5543 return new ICmpInst(NewPred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5544 }
5545
5546 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5547 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5548 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5549 NewPred = I.getSwappedPredicate(pred: NewPred);
5550 return new ICmpInst(NewPred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5551 }
5552 }
5553 break;
5554 }
5555 case Instruction::Mul: {
5556 if (!I.isEquality())
5557 break;
5558
5559 const APInt *C;
5560 if (match(V: BO0->getOperand(i_nocapture: 1), P: m_APInt(Res&: C)) && !C->isZero() &&
5561 !C->isOne()) {
5562 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5563 // Mask = -1 >> count-trailing-zeros(C).
5564 if (unsigned TZs = C->countr_zero()) {
5565 Constant *Mask = ConstantInt::get(
5566 Ty: BO0->getType(),
5567 V: APInt::getLowBitsSet(numBits: C->getBitWidth(), loBitsSet: C->getBitWidth() - TZs));
5568 Value *And1 = Builder.CreateAnd(LHS: BO0->getOperand(i_nocapture: 0), RHS: Mask);
5569 Value *And2 = Builder.CreateAnd(LHS: BO1->getOperand(i_nocapture: 0), RHS: Mask);
5570 return new ICmpInst(Pred, And1, And2);
5571 }
5572 }
5573 break;
5574 }
5575 case Instruction::UDiv:
5576 case Instruction::LShr:
5577 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
5578 break;
5579 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5580
5581 case Instruction::SDiv:
5582 if (!(I.isEquality() || match(V: BO0->getOperand(i_nocapture: 1), P: m_NonNegative())) ||
5583 !BO0->isExact() || !BO1->isExact())
5584 break;
5585 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5586
5587 case Instruction::AShr:
5588 if (!BO0->isExact() || !BO1->isExact())
5589 break;
5590 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5591
5592 case Instruction::Shl: {
5593 bool NUW = Op0HasNUW && Op1HasNUW;
5594 bool NSW = Op0HasNSW && Op1HasNSW;
5595 if (!NUW && !NSW)
5596 break;
5597 if (!NSW && I.isSigned())
5598 break;
5599 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5600 }
5601 }
5602 }
5603
5604 if (BO0) {
5605 // Transform A & (L - 1) `ult` L --> L != 0
5606 auto LSubOne = m_Add(L: m_Specific(V: Op1), R: m_AllOnes());
5607 auto BitwiseAnd = m_c_And(L: m_Value(), R: LSubOne);
5608
5609 if (match(V: BO0, P: BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5610 auto *Zero = Constant::getNullValue(Ty: BO0->getType());
5611 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5612 }
5613 }
5614
5615 // For unsigned predicates / eq / ne:
5616 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5617 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5618 if (!ICmpInst::isSigned(predicate: Pred)) {
5619 if (match(V: Op0, P: m_Shl(L: m_Specific(V: Op1), R: m_One())))
5620 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5621 Constant::getNullValue(Ty: Op1->getType()));
5622 else if (match(V: Op1, P: m_Shl(L: m_Specific(V: Op0), R: m_One())))
5623 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5624 Constant::getNullValue(Ty: Op0->getType()), Op0);
5625 }
5626
5627 if (Value *V = foldMultiplicationOverflowCheck(I))
5628 return replaceInstUsesWith(I, V);
5629
5630 if (Instruction *R = foldICmpAndXX(I, Q, IC&: *this))
5631 return R;
5632
5633 if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder))
5634 return replaceInstUsesWith(I, V);
5635
5636 if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder))
5637 return replaceInstUsesWith(I, V);
5638
5639 return nullptr;
5640}
5641
5642/// Fold icmp Pred min|max(X, Y), Z.
5643Instruction *InstCombinerImpl::foldICmpWithMinMax(Instruction &I,
5644 MinMaxIntrinsic *MinMax,
5645 Value *Z, CmpPredicate Pred) {
5646 Value *X = MinMax->getLHS();
5647 Value *Y = MinMax->getRHS();
5648 if (ICmpInst::isSigned(predicate: Pred) && !MinMax->isSigned())
5649 return nullptr;
5650 if (ICmpInst::isUnsigned(predicate: Pred) && MinMax->isSigned()) {
5651 // Revert the transform signed pred -> unsigned pred
5652 // TODO: We can flip the signedness of predicate if both operands of icmp
5653 // are negative.
5654 if (isKnownNonNegative(V: Z, SQ: SQ.getWithInstruction(I: &I)) &&
5655 isKnownNonNegative(V: MinMax, SQ: SQ.getWithInstruction(I: &I))) {
5656 Pred = ICmpInst::getFlippedSignednessPredicate(Pred);
5657 } else
5658 return nullptr;
5659 }
5660 SimplifyQuery Q = SQ.getWithInstruction(I: &I);
5661 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5662 if (!Val)
5663 return std::nullopt;
5664 if (match(V: Val, P: m_One()))
5665 return true;
5666 if (match(V: Val, P: m_Zero()))
5667 return false;
5668 return std::nullopt;
5669 };
5670 // Remove samesign here since it is illegal to keep it when we speculatively
5671 // execute comparisons. For example, `icmp samesign ult umax(X, -46), -32`
5672 // cannot be decomposed into `(icmp samesign ult X, -46) or (icmp samesign ult
5673 // -46, -32)`. `X` is allowed to be non-negative here.
5674 Pred = Pred.dropSameSign();
5675 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, LHS: X, RHS: Z, Q));
5676 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, LHS: Y, RHS: Z, Q));
5677 if (!CmpXZ.has_value() && !CmpYZ.has_value())
5678 return nullptr;
5679 if (!CmpXZ.has_value()) {
5680 std::swap(a&: X, b&: Y);
5681 std::swap(lhs&: CmpXZ, rhs&: CmpYZ);
5682 }
5683
5684 auto FoldIntoCmpYZ = [&]() -> Instruction * {
5685 if (CmpYZ.has_value())
5686 return replaceInstUsesWith(I, V: ConstantInt::getBool(Ty: I.getType(), V: *CmpYZ));
5687 return ICmpInst::Create(Op: Instruction::ICmp, Pred, S1: Y, S2: Z);
5688 };
5689
5690 switch (Pred) {
5691 case ICmpInst::ICMP_EQ:
5692 case ICmpInst::ICMP_NE: {
5693 // If X == Z:
5694 // Expr Result
5695 // min(X, Y) == Z X <= Y
5696 // max(X, Y) == Z X >= Y
5697 // min(X, Y) != Z X > Y
5698 // max(X, Y) != Z X < Y
5699 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5700 ICmpInst::Predicate NewPred =
5701 ICmpInst::getNonStrictPredicate(pred: MinMax->getPredicate());
5702 if (Pred == ICmpInst::ICMP_NE)
5703 NewPred = ICmpInst::getInversePredicate(pred: NewPred);
5704 return ICmpInst::Create(Op: Instruction::ICmp, Pred: NewPred, S1: X, S2: Y);
5705 }
5706 // Otherwise (X != Z):
5707 ICmpInst::Predicate NewPred = MinMax->getPredicate();
5708 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred: NewPred, LHS: X, RHS: Z, Q));
5709 if (!MinMaxCmpXZ.has_value()) {
5710 std::swap(a&: X, b&: Y);
5711 std::swap(lhs&: CmpXZ, rhs&: CmpYZ);
5712 // Re-check pre-condition X != Z
5713 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5714 break;
5715 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred: NewPred, LHS: X, RHS: Z, Q));
5716 }
5717 if (!MinMaxCmpXZ.has_value())
5718 break;
5719 if (*MinMaxCmpXZ) {
5720 // Expr Fact Result
5721 // min(X, Y) == Z X < Z false
5722 // max(X, Y) == Z X > Z false
5723 // min(X, Y) != Z X < Z true
5724 // max(X, Y) != Z X > Z true
5725 return replaceInstUsesWith(
5726 I, V: ConstantInt::getBool(Ty: I.getType(), V: Pred == ICmpInst::ICMP_NE));
5727 } else {
5728 // Expr Fact Result
5729 // min(X, Y) == Z X > Z Y == Z
5730 // max(X, Y) == Z X < Z Y == Z
5731 // min(X, Y) != Z X > Z Y != Z
5732 // max(X, Y) != Z X < Z Y != Z
5733 return FoldIntoCmpYZ();
5734 }
5735 break;
5736 }
5737 case ICmpInst::ICMP_SLT:
5738 case ICmpInst::ICMP_ULT:
5739 case ICmpInst::ICMP_SLE:
5740 case ICmpInst::ICMP_ULE:
5741 case ICmpInst::ICMP_SGT:
5742 case ICmpInst::ICMP_UGT:
5743 case ICmpInst::ICMP_SGE:
5744 case ICmpInst::ICMP_UGE: {
5745 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(pred: Pred);
5746 if (*CmpXZ) {
5747 if (IsSame) {
5748 // Expr Fact Result
5749 // min(X, Y) < Z X < Z true
5750 // min(X, Y) <= Z X <= Z true
5751 // max(X, Y) > Z X > Z true
5752 // max(X, Y) >= Z X >= Z true
5753 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
5754 } else {
5755 // Expr Fact Result
5756 // max(X, Y) < Z X < Z Y < Z
5757 // max(X, Y) <= Z X <= Z Y <= Z
5758 // min(X, Y) > Z X > Z Y > Z
5759 // min(X, Y) >= Z X >= Z Y >= Z
5760 return FoldIntoCmpYZ();
5761 }
5762 } else {
5763 if (IsSame) {
5764 // Expr Fact Result
5765 // min(X, Y) < Z X >= Z Y < Z
5766 // min(X, Y) <= Z X > Z Y <= Z
5767 // max(X, Y) > Z X <= Z Y > Z
5768 // max(X, Y) >= Z X < Z Y >= Z
5769 return FoldIntoCmpYZ();
5770 } else {
5771 // Expr Fact Result
5772 // max(X, Y) < Z X >= Z false
5773 // max(X, Y) <= Z X > Z false
5774 // min(X, Y) > Z X <= Z false
5775 // min(X, Y) >= Z X < Z false
5776 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
5777 }
5778 }
5779 break;
5780 }
5781 default:
5782 break;
5783 }
5784
5785 return nullptr;
5786}
5787
5788// Canonicalize checking for a power-of-2-or-zero value:
5789static Instruction *foldICmpPow2Test(ICmpInst &I,
5790 InstCombiner::BuilderTy &Builder) {
5791 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
5792 const CmpInst::Predicate Pred = I.getPredicate();
5793 Value *A = nullptr;
5794 bool CheckIs;
5795 if (I.isEquality()) {
5796 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
5797 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
5798 if (!match(V: Op0, P: m_OneUse(SubPattern: m_c_And(L: m_Add(L: m_Value(V&: A), R: m_AllOnes()),
5799 R: m_Deferred(V: A)))) ||
5800 !match(V: Op1, P: m_ZeroInt()))
5801 A = nullptr;
5802
5803 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
5804 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
5805 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_And(L: m_Neg(V: m_Specific(V: Op1)), R: m_Specific(V: Op1)))))
5806 A = Op1;
5807 else if (match(V: Op1,
5808 P: m_OneUse(SubPattern: m_c_And(L: m_Neg(V: m_Specific(V: Op0)), R: m_Specific(V: Op0)))))
5809 A = Op0;
5810
5811 CheckIs = Pred == ICmpInst::ICMP_EQ;
5812 } else if (ICmpInst::isUnsigned(predicate: Pred)) {
5813 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
5814 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
5815
5816 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5817 match(V: Op0, P: m_OneUse(SubPattern: m_c_Xor(L: m_Add(L: m_Specific(V: Op1), R: m_AllOnes()),
5818 R: m_Specific(V: Op1))))) {
5819 A = Op1;
5820 CheckIs = Pred == ICmpInst::ICMP_UGE;
5821 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5822 match(V: Op1, P: m_OneUse(SubPattern: m_c_Xor(L: m_Add(L: m_Specific(V: Op0), R: m_AllOnes()),
5823 R: m_Specific(V: Op0))))) {
5824 A = Op0;
5825 CheckIs = Pred == ICmpInst::ICMP_ULE;
5826 }
5827 }
5828
5829 if (A) {
5830 Type *Ty = A->getType();
5831 CallInst *CtPop = Builder.CreateUnaryIntrinsic(ID: Intrinsic::ctpop, V: A);
5832 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
5833 ConstantInt::get(Ty, V: 2))
5834 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
5835 ConstantInt::get(Ty, V: 1));
5836 }
5837
5838 return nullptr;
5839}
5840
5841/// Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
5842using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
5843static void collectOffsetOp(Value *V, SmallVectorImpl<OffsetOp> &Offsets,
5844 bool AllowRecursion) {
5845 Instruction *Inst = dyn_cast<Instruction>(Val: V);
5846 if (!Inst || !Inst->hasOneUse())
5847 return;
5848
5849 switch (Inst->getOpcode()) {
5850 case Instruction::Add:
5851 Offsets.emplace_back(Args: Instruction::Sub, Args: Inst->getOperand(i: 1));
5852 Offsets.emplace_back(Args: Instruction::Sub, Args: Inst->getOperand(i: 0));
5853 break;
5854 case Instruction::Sub:
5855 Offsets.emplace_back(Args: Instruction::Add, Args: Inst->getOperand(i: 1));
5856 break;
5857 case Instruction::Xor:
5858 Offsets.emplace_back(Args: Instruction::Xor, Args: Inst->getOperand(i: 1));
5859 Offsets.emplace_back(Args: Instruction::Xor, Args: Inst->getOperand(i: 0));
5860 break;
5861 case Instruction::Select:
5862 if (AllowRecursion) {
5863 collectOffsetOp(V: Inst->getOperand(i: 1), Offsets, /*AllowRecursion=*/false);
5864 collectOffsetOp(V: Inst->getOperand(i: 2), Offsets, /*AllowRecursion=*/false);
5865 }
5866 break;
5867 default:
5868 break;
5869 }
5870}
5871
5872enum class OffsetKind { Invalid, Value, Select };
5873
5874struct OffsetResult {
5875 OffsetKind Kind;
5876 Value *V0, *V1, *V2;
5877
5878 static OffsetResult invalid() {
5879 return {.Kind: OffsetKind::Invalid, .V0: nullptr, .V1: nullptr, .V2: nullptr};
5880 }
5881 static OffsetResult value(Value *V) {
5882 return {.Kind: OffsetKind::Value, .V0: V, .V1: nullptr, .V2: nullptr};
5883 }
5884 static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV) {
5885 return {.Kind: OffsetKind::Select, .V0: Cond, .V1: TrueV, .V2: FalseV};
5886 }
5887 bool isValid() const { return Kind != OffsetKind::Invalid; }
5888 Value *materialize(InstCombiner::BuilderTy &Builder) const {
5889 switch (Kind) {
5890 case OffsetKind::Invalid:
5891 llvm_unreachable("Invalid offset result");
5892 case OffsetKind::Value:
5893 return V0;
5894 case OffsetKind::Select:
5895 return Builder.CreateSelect(C: V0, True: V1, False: V2);
5896 }
5897 llvm_unreachable("Unknown OffsetKind enum");
5898 }
5899};
5900
5901/// Offset both sides of an equality icmp to see if we can save some
5902/// instructions: icmp eq/ne X, Y -> icmp eq/ne X op Z, Y op Z.
5903/// Note: This operation should not introduce poison.
5904static Instruction *foldICmpEqualityWithOffset(ICmpInst &I,
5905 InstCombiner::BuilderTy &Builder,
5906 const SimplifyQuery &SQ) {
5907 assert(I.isEquality() && "Expected an equality icmp");
5908 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
5909 if (!Op0->getType()->isIntOrIntVectorTy())
5910 return nullptr;
5911
5912 SmallVector<OffsetOp, 4> OffsetOps;
5913 collectOffsetOp(V: Op0, Offsets&: OffsetOps, /*AllowRecursion=*/true);
5914 collectOffsetOp(V: Op1, Offsets&: OffsetOps, /*AllowRecursion=*/true);
5915
5916 auto ApplyOffsetImpl = [&](Value *V, unsigned BinOpc, Value *RHS) -> Value * {
5917 Value *Simplified = simplifyBinOp(Opcode: BinOpc, LHS: V, RHS, Q: SQ);
5918 // Avoid infinite loops by checking if RHS is an identity for the BinOp.
5919 if (!Simplified || Simplified == V)
5920 return nullptr;
5921 // Reject constant expressions as they don't simplify things.
5922 if (isa<Constant>(Val: Simplified) && !match(V: Simplified, P: m_ImmConstant()))
5923 return nullptr;
5924 // Check if the transformation introduces poison.
5925 return impliesPoison(ValAssumedPoison: RHS, V) ? Simplified : nullptr;
5926 };
5927
5928 auto ApplyOffset = [&](Value *V, unsigned BinOpc,
5929 Value *RHS) -> OffsetResult {
5930 if (auto *Sel = dyn_cast<SelectInst>(Val: V)) {
5931 if (!Sel->hasOneUse())
5932 return OffsetResult::invalid();
5933 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc, RHS);
5934 if (!TrueVal)
5935 return OffsetResult::invalid();
5936 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc, RHS);
5937 if (!FalseVal)
5938 return OffsetResult::invalid();
5939 return OffsetResult::select(Cond: Sel->getCondition(), TrueV: TrueVal, FalseV: FalseVal);
5940 }
5941 if (Value *Simplified = ApplyOffsetImpl(V, BinOpc, RHS))
5942 return OffsetResult::value(V: Simplified);
5943 return OffsetResult::invalid();
5944 };
5945
5946 for (auto [BinOp, RHS] : OffsetOps) {
5947 auto BinOpc = static_cast<unsigned>(BinOp);
5948
5949 auto Op0Result = ApplyOffset(Op0, BinOpc, RHS);
5950 if (!Op0Result.isValid())
5951 continue;
5952 auto Op1Result = ApplyOffset(Op1, BinOpc, RHS);
5953 if (!Op1Result.isValid())
5954 continue;
5955
5956 Value *NewLHS = Op0Result.materialize(Builder);
5957 Value *NewRHS = Op1Result.materialize(Builder);
5958 return new ICmpInst(I.getPredicate(), NewLHS, NewRHS);
5959 }
5960
5961 return nullptr;
5962}
5963
5964Instruction *InstCombinerImpl::foldICmpEquality(ICmpInst &I) {
5965 if (!I.isEquality())
5966 return nullptr;
5967
5968 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
5969 const CmpInst::Predicate Pred = I.getPredicate();
5970 Value *A, *B, *C, *D;
5971 if (match(V: Op0, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B)))) {
5972 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5973 Value *OtherVal = A == Op1 ? B : A;
5974 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(Ty: A->getType()));
5975 }
5976
5977 if (match(V: Op1, P: m_Xor(L: m_Value(V&: C), R: m_Value(V&: D)))) {
5978 // A^c1 == C^c2 --> A == C^(c1^c2)
5979 ConstantInt *C1, *C2;
5980 if (match(V: B, P: m_ConstantInt(CI&: C1)) && match(V: D, P: m_ConstantInt(CI&: C2)) &&
5981 Op1->hasOneUse()) {
5982 Constant *NC = Builder.getInt(AI: C1->getValue() ^ C2->getValue());
5983 Value *Xor = Builder.CreateXor(LHS: C, RHS: NC);
5984 return new ICmpInst(Pred, A, Xor);
5985 }
5986
5987 // A^B == A^D -> B == D
5988 if (A == C)
5989 return new ICmpInst(Pred, B, D);
5990 if (A == D)
5991 return new ICmpInst(Pred, B, C);
5992 if (B == C)
5993 return new ICmpInst(Pred, A, D);
5994 if (B == D)
5995 return new ICmpInst(Pred, A, C);
5996 }
5997 }
5998
5999 if (match(V: Op1, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))) && (A == Op0 || B == Op0)) {
6000 // A == (A^B) -> B == 0
6001 Value *OtherVal = A == Op0 ? B : A;
6002 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(Ty: A->getType()));
6003 }
6004
6005 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6006 if (match(V: Op0, P: m_And(L: m_Value(V&: A), R: m_Value(V&: B))) &&
6007 match(V: Op1, P: m_And(L: m_Value(V&: C), R: m_Value(V&: D)))) {
6008 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
6009
6010 if (A == C) {
6011 X = B;
6012 Y = D;
6013 Z = A;
6014 } else if (A == D) {
6015 X = B;
6016 Y = C;
6017 Z = A;
6018 } else if (B == C) {
6019 X = A;
6020 Y = D;
6021 Z = B;
6022 } else if (B == D) {
6023 X = A;
6024 Y = C;
6025 Z = B;
6026 }
6027
6028 if (X) {
6029 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
6030 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
6031 // instructions.
6032 const APInt *C0, *C1;
6033 bool XorIsNegP2 = match(V: X, P: m_APInt(Res&: C0)) && match(V: Y, P: m_APInt(Res&: C1)) &&
6034 (*C0 ^ *C1).isNegatedPowerOf2();
6035
6036 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
6037 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
6038 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
6039 int UseCnt =
6040 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
6041 (int(match(V: X, P: m_ImmConstant()) && match(V: Y, P: m_ImmConstant())));
6042 if (XorIsNegP2 || UseCnt >= 2) {
6043 // Build (X^Y) & Z
6044 Op1 = Builder.CreateXor(LHS: X, RHS: Y);
6045 Op1 = Builder.CreateAnd(LHS: Op1, RHS: Z);
6046 return new ICmpInst(Pred, Op1, Constant::getNullValue(Ty: Op1->getType()));
6047 }
6048 }
6049 }
6050
6051 {
6052 // Similar to above, but specialized for constant because invert is needed:
6053 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
6054 Value *X, *Y;
6055 Constant *C;
6056 if (match(V: Op0, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: X), R: m_Constant(C)))) &&
6057 match(V: Op1, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: Y), R: m_Specific(V: C))))) {
6058 Value *Xor = Builder.CreateXor(LHS: X, RHS: Y);
6059 Value *And = Builder.CreateAnd(LHS: Xor, RHS: ConstantExpr::getNot(C));
6060 return new ICmpInst(Pred, And, Constant::getNullValue(Ty: And->getType()));
6061 }
6062 }
6063
6064 if (match(V: Op1, P: m_ZExt(Op: m_Value(V&: A))) &&
6065 (Op0->hasOneUse() || Op1->hasOneUse())) {
6066 // (B & (Pow2C-1)) == zext A --> A == trunc B
6067 // (B & (Pow2C-1)) != zext A --> A != trunc B
6068 const APInt *MaskC;
6069 if (match(V: Op0, P: m_And(L: m_Value(V&: B), R: m_LowBitMask(V&: MaskC))) &&
6070 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
6071 return new ICmpInst(Pred, A, Builder.CreateTrunc(V: B, DestTy: A->getType()));
6072 }
6073
6074 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
6075 // For lshr and ashr pairs.
6076 const APInt *AP1, *AP2;
6077 if ((match(V: Op0, P: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: A), R: m_APIntAllowPoison(Res&: AP1)))) &&
6078 match(V: Op1, P: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: B), R: m_APIntAllowPoison(Res&: AP2))))) ||
6079 (match(V: Op0, P: m_OneUse(SubPattern: m_AShr(L: m_Value(V&: A), R: m_APIntAllowPoison(Res&: AP1)))) &&
6080 match(V: Op1, P: m_OneUse(SubPattern: m_AShr(L: m_Value(V&: B), R: m_APIntAllowPoison(Res&: AP2)))))) {
6081 if (AP1 != AP2)
6082 return nullptr;
6083 unsigned TypeBits = AP1->getBitWidth();
6084 unsigned ShAmt = AP1->getLimitedValue(Limit: TypeBits);
6085 if (ShAmt < TypeBits && ShAmt != 0) {
6086 ICmpInst::Predicate NewPred =
6087 Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6088 Value *Xor = Builder.CreateXor(LHS: A, RHS: B, Name: I.getName() + ".unshifted");
6089 APInt CmpVal = APInt::getOneBitSet(numBits: TypeBits, BitNo: ShAmt);
6090 return new ICmpInst(NewPred, Xor, ConstantInt::get(Ty: A->getType(), V: CmpVal));
6091 }
6092 }
6093
6094 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
6095 ConstantInt *Cst1;
6096 if (match(V: Op0, P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: A), R: m_ConstantInt(CI&: Cst1)))) &&
6097 match(V: Op1, P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: B), R: m_Specific(V: Cst1))))) {
6098 unsigned TypeBits = Cst1->getBitWidth();
6099 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(Limit: TypeBits);
6100 if (ShAmt < TypeBits && ShAmt != 0) {
6101 Value *Xor = Builder.CreateXor(LHS: A, RHS: B, Name: I.getName() + ".unshifted");
6102 APInt AndVal = APInt::getLowBitsSet(numBits: TypeBits, loBitsSet: TypeBits - ShAmt);
6103 Value *And =
6104 Builder.CreateAnd(LHS: Xor, RHS: Builder.getInt(AI: AndVal), Name: I.getName() + ".mask");
6105 return new ICmpInst(Pred, And, Constant::getNullValue(Ty: Cst1->getType()));
6106 }
6107 }
6108
6109 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
6110 // "icmp (and X, mask), cst"
6111 uint64_t ShAmt = 0;
6112 if (Op0->hasOneUse() &&
6113 match(V: Op0, P: m_Trunc(Op: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: A), R: m_ConstantInt(V&: ShAmt))))) &&
6114 match(V: Op1, P: m_ConstantInt(CI&: Cst1)) &&
6115 // Only do this when A has multiple uses. This is most important to do
6116 // when it exposes other optimizations.
6117 !A->hasOneUse()) {
6118 unsigned ASize = cast<IntegerType>(Val: A->getType())->getPrimitiveSizeInBits();
6119
6120 if (ShAmt < ASize) {
6121 APInt MaskV =
6122 APInt::getLowBitsSet(numBits: ASize, loBitsSet: Op0->getType()->getPrimitiveSizeInBits());
6123 MaskV <<= ShAmt;
6124
6125 APInt CmpV = Cst1->getValue().zext(width: ASize);
6126 CmpV <<= ShAmt;
6127
6128 Value *Mask = Builder.CreateAnd(LHS: A, RHS: Builder.getInt(AI: MaskV));
6129 return new ICmpInst(Pred, Mask, Builder.getInt(AI: CmpV));
6130 }
6131 }
6132
6133 if (Instruction *ICmp = foldICmpIntrinsicWithIntrinsic(Cmp&: I, Builder))
6134 return ICmp;
6135
6136 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
6137 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
6138 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
6139 // few steps of instcombine.
6140 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6141 if (match(V: Op0, P: m_AShr(L: m_Trunc(Op: m_Value(V&: A)), R: m_SpecificInt(V: BitWidth - 1))) &&
6142 match(V: Op1, P: m_Trunc(Op: m_LShr(L: m_Specific(V: A), R: m_SpecificInt(V: BitWidth)))) &&
6143 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
6144 (I.getOperand(i_nocapture: 0)->hasOneUse() || I.getOperand(i_nocapture: 1)->hasOneUse())) {
6145 APInt C = APInt::getOneBitSet(numBits: BitWidth * 2, BitNo: BitWidth - 1);
6146 Value *Add = Builder.CreateAdd(LHS: A, RHS: ConstantInt::get(Ty: A->getType(), V: C));
6147 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
6148 : ICmpInst::ICMP_UGE,
6149 Add, ConstantInt::get(Ty: A->getType(), V: C.shl(shiftAmt: 1)));
6150 }
6151
6152 // Canonicalize:
6153 // Assume B_Pow2 != 0
6154 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
6155 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
6156 if (match(V: Op0, P: m_c_And(L: m_Specific(V: Op1), R: m_Value())) &&
6157 isKnownToBeAPowerOfTwo(V: Op1, /* OrZero */ false, CxtI: &I))
6158 return new ICmpInst(CmpInst::getInversePredicate(pred: Pred), Op0,
6159 ConstantInt::getNullValue(Ty: Op0->getType()));
6160
6161 if (match(V: Op1, P: m_c_And(L: m_Specific(V: Op0), R: m_Value())) &&
6162 isKnownToBeAPowerOfTwo(V: Op0, /* OrZero */ false, CxtI: &I))
6163 return new ICmpInst(CmpInst::getInversePredicate(pred: Pred), Op1,
6164 ConstantInt::getNullValue(Ty: Op1->getType()));
6165
6166 // Canonicalize:
6167 // icmp eq/ne X, OneUse(rotate-right(X))
6168 // -> icmp eq/ne X, rotate-left(X)
6169 // We generally try to convert rotate-right -> rotate-left, this just
6170 // canonicalizes another case.
6171 if (match(V: &I, P: m_c_ICmp(L: m_Value(V&: A),
6172 R: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::fshr>(
6173 Op0: m_Deferred(V: A), Op1: m_Deferred(V: A), Op2: m_Value(V&: B))))))
6174 return new ICmpInst(
6175 Pred, A,
6176 Builder.CreateIntrinsic(RetTy: Op0->getType(), ID: Intrinsic::fshl, Args: {A, A, B}));
6177
6178 // Canonicalize:
6179 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
6180 Constant *Cst;
6181 if (match(V: &I, P: m_c_ICmp(L: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: A), R: m_ImmConstant(C&: Cst))),
6182 R: m_CombineAnd(L: m_Value(V&: B), R: m_Unless(M: m_ImmConstant())))))
6183 return new ICmpInst(Pred, Builder.CreateXor(LHS: A, RHS: B), Cst);
6184
6185 {
6186 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6187 auto m_Matcher =
6188 m_CombineOr(L: m_CombineOr(L: m_c_Add(L: m_Value(V&: B), R: m_Deferred(V: A)),
6189 R: m_c_Xor(L: m_Value(V&: B), R: m_Deferred(V: A))),
6190 R: m_Sub(L: m_Value(V&: B), R: m_Deferred(V: A)));
6191 std::optional<bool> IsZero = std::nullopt;
6192 if (match(V: &I, P: m_c_ICmp(L: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: A), R: m_Matcher)),
6193 R: m_Deferred(V: A))))
6194 IsZero = false;
6195 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6196 else if (match(V: &I,
6197 P: m_ICmp(L: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: A), R: m_Matcher)), R: m_Zero())))
6198 IsZero = true;
6199
6200 if (IsZero && isKnownToBeAPowerOfTwo(V: A, /* OrZero */ true, CxtI: &I))
6201 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6202 // -> (icmp eq/ne (and X, P2), 0)
6203 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6204 // -> (icmp eq/ne (and X, P2), P2)
6205 return new ICmpInst(Pred, Builder.CreateAnd(LHS: B, RHS: A),
6206 *IsZero ? A
6207 : ConstantInt::getNullValue(Ty: A->getType()));
6208 }
6209
6210 if (auto *Res = foldICmpEqualityWithOffset(
6211 I, Builder, SQ: getSimplifyQuery().getWithInstruction(I: &I)))
6212 return Res;
6213
6214 return nullptr;
6215}
6216
6217Instruction *InstCombinerImpl::foldICmpWithTrunc(ICmpInst &ICmp) {
6218 ICmpInst::Predicate Pred = ICmp.getPredicate();
6219 Value *Op0 = ICmp.getOperand(i_nocapture: 0), *Op1 = ICmp.getOperand(i_nocapture: 1);
6220
6221 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6222 // The trunc masks high bits while the compare may effectively mask low bits.
6223 Value *X;
6224 const APInt *C;
6225 if (!match(V: Op0, P: m_OneUse(SubPattern: m_Trunc(Op: m_Value(V&: X)))) || !match(V: Op1, P: m_APInt(Res&: C)))
6226 return nullptr;
6227
6228 // This matches patterns corresponding to tests of the signbit as well as:
6229 // (trunc X) pred C2 --> (X & Mask) == C
6230 if (auto Res = decomposeBitTestICmp(LHS: Op0, RHS: Op1, Pred, /*WithTrunc=*/LookThroughTrunc: true,
6231 /*AllowNonZeroC=*/true)) {
6232 Value *And = Builder.CreateAnd(LHS: Res->X, RHS: Res->Mask);
6233 Constant *C = ConstantInt::get(Ty: Res->X->getType(), V: Res->C);
6234 return new ICmpInst(Res->Pred, And, C);
6235 }
6236
6237 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6238 if (auto *II = dyn_cast<IntrinsicInst>(Val: X)) {
6239 if (II->getIntrinsicID() == Intrinsic::cttz ||
6240 II->getIntrinsicID() == Intrinsic::ctlz) {
6241 unsigned MaxRet = SrcBits;
6242 // If the "is_zero_poison" argument is set, then we know at least
6243 // one bit is set in the input, so the result is always at least one
6244 // less than the full bitwidth of that input.
6245 if (match(V: II->getArgOperand(i: 1), P: m_One()))
6246 MaxRet--;
6247
6248 // Make sure the destination is wide enough to hold the largest output of
6249 // the intrinsic.
6250 if (llvm::Log2_32(Value: MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6251 if (Instruction *I =
6252 foldICmpIntrinsicWithConstant(Cmp&: ICmp, II, C: C->zext(width: SrcBits)))
6253 return I;
6254 }
6255 }
6256
6257 return nullptr;
6258}
6259
6260Instruction *InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst &ICmp) {
6261 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6262 auto *CastOp0 = cast<CastInst>(Val: ICmp.getOperand(i_nocapture: 0));
6263 Value *X;
6264 if (!match(V: CastOp0, P: m_ZExtOrSExt(Op: m_Value(V&: X))))
6265 return nullptr;
6266
6267 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6268 bool IsSignedCmp = ICmp.isSigned();
6269
6270 // icmp Pred (ext X), (ext Y)
6271 Value *Y;
6272 if (match(V: ICmp.getOperand(i_nocapture: 1), P: m_ZExtOrSExt(Op: m_Value(V&: Y)))) {
6273 bool IsZext0 = isa<ZExtInst>(Val: ICmp.getOperand(i_nocapture: 0));
6274 bool IsZext1 = isa<ZExtInst>(Val: ICmp.getOperand(i_nocapture: 1));
6275
6276 if (IsZext0 != IsZext1) {
6277 // If X and Y and both i1
6278 // (icmp eq/ne (zext X) (sext Y))
6279 // eq -> (icmp eq (or X, Y), 0)
6280 // ne -> (icmp ne (or X, Y), 0)
6281 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(BitWidth: 1) &&
6282 Y->getType()->isIntOrIntVectorTy(BitWidth: 1))
6283 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(LHS: X, RHS: Y),
6284 Constant::getNullValue(Ty: X->getType()));
6285
6286 // If we have mismatched casts and zext has the nneg flag, we can
6287 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6288
6289 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(Val: ICmp.getOperand(i_nocapture: 0));
6290 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(Val: ICmp.getOperand(i_nocapture: 1));
6291
6292 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6293 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6294
6295 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6296 IsSignedExt = true;
6297 else
6298 return nullptr;
6299 }
6300
6301 // Not an extension from the same type?
6302 Type *XTy = X->getType(), *YTy = Y->getType();
6303 if (XTy != YTy) {
6304 // One of the casts must have one use because we are creating a new cast.
6305 if (!ICmp.getOperand(i_nocapture: 0)->hasOneUse() && !ICmp.getOperand(i_nocapture: 1)->hasOneUse())
6306 return nullptr;
6307 // Extend the narrower operand to the type of the wider operand.
6308 CastInst::CastOps CastOpcode =
6309 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6310 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6311 X = Builder.CreateCast(Op: CastOpcode, V: X, DestTy: YTy);
6312 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6313 Y = Builder.CreateCast(Op: CastOpcode, V: Y, DestTy: XTy);
6314 else
6315 return nullptr;
6316 }
6317
6318 // (zext X) == (zext Y) --> X == Y
6319 // (sext X) == (sext Y) --> X == Y
6320 if (ICmp.isEquality())
6321 return new ICmpInst(ICmp.getPredicate(), X, Y);
6322
6323 // A signed comparison of sign extended values simplifies into a
6324 // signed comparison.
6325 if (IsSignedCmp && IsSignedExt)
6326 return new ICmpInst(ICmp.getPredicate(), X, Y);
6327
6328 // The other three cases all fold into an unsigned comparison.
6329 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6330 }
6331
6332 // Below here, we are only folding a compare with constant.
6333 auto *C = dyn_cast<Constant>(Val: ICmp.getOperand(i_nocapture: 1));
6334 if (!C)
6335 return nullptr;
6336
6337 // If a lossless truncate is possible...
6338 Type *SrcTy = CastOp0->getSrcTy();
6339 Constant *Res = getLosslessTrunc(C, TruncTy: SrcTy, ExtOp: CastOp0->getOpcode());
6340 if (Res) {
6341 if (ICmp.isEquality())
6342 return new ICmpInst(ICmp.getPredicate(), X, Res);
6343
6344 // A signed comparison of sign extended values simplifies into a
6345 // signed comparison.
6346 if (IsSignedExt && IsSignedCmp)
6347 return new ICmpInst(ICmp.getPredicate(), X, Res);
6348
6349 // The other three cases all fold into an unsigned comparison.
6350 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6351 }
6352
6353 // The re-extended constant changed, partly changed (in the case of a vector),
6354 // or could not be determined to be equal (in the case of a constant
6355 // expression), so the constant cannot be represented in the shorter type.
6356 // All the cases that fold to true or false will have already been handled
6357 // by simplifyICmpInst, so only deal with the tricky case.
6358 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(Val: C))
6359 return nullptr;
6360
6361 // Is source op positive?
6362 // icmp ult (sext X), C --> icmp sgt X, -1
6363 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6364 return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(Ty: SrcTy));
6365
6366 // Is source op negative?
6367 // icmp ugt (sext X), C --> icmp slt X, 0
6368 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6369 return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(Ty: SrcTy));
6370}
6371
6372/// Handle icmp (cast x), (cast or constant).
6373Instruction *InstCombinerImpl::foldICmpWithCastOp(ICmpInst &ICmp) {
6374 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6375 // icmp compares only pointer's value.
6376 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6377 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(Val: ICmp.getOperand(i_nocapture: 0));
6378 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(Val: ICmp.getOperand(i_nocapture: 1));
6379 if (SimplifiedOp0 || SimplifiedOp1)
6380 return new ICmpInst(ICmp.getPredicate(),
6381 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(i_nocapture: 0),
6382 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(i_nocapture: 1));
6383
6384 auto *CastOp0 = dyn_cast<CastInst>(Val: ICmp.getOperand(i_nocapture: 0));
6385 if (!CastOp0)
6386 return nullptr;
6387 if (!isa<Constant>(Val: ICmp.getOperand(i_nocapture: 1)) && !isa<CastInst>(Val: ICmp.getOperand(i_nocapture: 1)))
6388 return nullptr;
6389
6390 Value *Op0Src = CastOp0->getOperand(i_nocapture: 0);
6391 Type *SrcTy = CastOp0->getSrcTy();
6392 Type *DestTy = CastOp0->getDestTy();
6393
6394 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6395 // integer type is the same size as the pointer type.
6396 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6397 if (isa<VectorType>(Val: PtrTy)) {
6398 PtrTy = cast<VectorType>(Val: PtrTy)->getElementType();
6399 IntTy = cast<VectorType>(Val: IntTy)->getElementType();
6400 }
6401 return DL.getPointerTypeSizeInBits(PtrTy) == IntTy->getIntegerBitWidth();
6402 };
6403 if (CastOp0->getOpcode() == Instruction::PtrToInt &&
6404 CompatibleSizes(SrcTy, DestTy)) {
6405 Value *NewOp1 = nullptr;
6406 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(Val: ICmp.getOperand(i_nocapture: 1))) {
6407 Value *PtrSrc = PtrToIntOp1->getOperand(i_nocapture: 0);
6408 if (PtrSrc->getType() == Op0Src->getType())
6409 NewOp1 = PtrToIntOp1->getOperand(i_nocapture: 0);
6410 } else if (auto *RHSC = dyn_cast<Constant>(Val: ICmp.getOperand(i_nocapture: 1))) {
6411 NewOp1 = ConstantExpr::getIntToPtr(C: RHSC, Ty: SrcTy);
6412 }
6413
6414 if (NewOp1)
6415 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6416 }
6417
6418 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6419 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6420 CompatibleSizes(DestTy, SrcTy)) {
6421 Value *NewOp1 = nullptr;
6422 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(Val: ICmp.getOperand(i_nocapture: 1))) {
6423 Value *IntSrc = IntToPtrOp1->getOperand(i_nocapture: 0);
6424 if (IntSrc->getType() == Op0Src->getType())
6425 NewOp1 = IntToPtrOp1->getOperand(i_nocapture: 0);
6426 } else if (auto *RHSC = dyn_cast<Constant>(Val: ICmp.getOperand(i_nocapture: 1))) {
6427 NewOp1 = ConstantFoldConstant(C: ConstantExpr::getPtrToInt(C: RHSC, Ty: SrcTy), DL);
6428 }
6429
6430 if (NewOp1)
6431 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6432 }
6433
6434 if (Instruction *R = foldICmpWithTrunc(ICmp))
6435 return R;
6436
6437 return foldICmpWithZextOrSext(ICmp);
6438}
6439
6440static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS,
6441 bool IsSigned) {
6442 switch (BinaryOp) {
6443 default:
6444 llvm_unreachable("Unsupported binary op");
6445 case Instruction::Add:
6446 case Instruction::Sub:
6447 return match(V: RHS, P: m_Zero());
6448 case Instruction::Mul:
6449 return !(RHS->getType()->isIntOrIntVectorTy(BitWidth: 1) && IsSigned) &&
6450 match(V: RHS, P: m_One());
6451 }
6452}
6453
6454OverflowResult
6455InstCombinerImpl::computeOverflow(Instruction::BinaryOps BinaryOp,
6456 bool IsSigned, Value *LHS, Value *RHS,
6457 Instruction *CxtI) const {
6458 switch (BinaryOp) {
6459 default:
6460 llvm_unreachable("Unsupported binary op");
6461 case Instruction::Add:
6462 if (IsSigned)
6463 return computeOverflowForSignedAdd(LHS, RHS, CxtI);
6464 else
6465 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
6466 case Instruction::Sub:
6467 if (IsSigned)
6468 return computeOverflowForSignedSub(LHS, RHS, CxtI);
6469 else
6470 return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
6471 case Instruction::Mul:
6472 if (IsSigned)
6473 return computeOverflowForSignedMul(LHS, RHS, CxtI);
6474 else
6475 return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
6476 }
6477}
6478
6479bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6480 bool IsSigned, Value *LHS,
6481 Value *RHS, Instruction &OrigI,
6482 Value *&Result,
6483 Constant *&Overflow) {
6484 if (OrigI.isCommutative() && isa<Constant>(Val: LHS) && !isa<Constant>(Val: RHS))
6485 std::swap(a&: LHS, b&: RHS);
6486
6487 // If the overflow check was an add followed by a compare, the insertion point
6488 // may be pointing to the compare. We want to insert the new instructions
6489 // before the add in case there are uses of the add between the add and the
6490 // compare.
6491 Builder.SetInsertPoint(&OrigI);
6492
6493 Type *OverflowTy = Type::getInt1Ty(C&: LHS->getContext());
6494 if (auto *LHSTy = dyn_cast<VectorType>(Val: LHS->getType()))
6495 OverflowTy = VectorType::get(ElementType: OverflowTy, EC: LHSTy->getElementCount());
6496
6497 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6498 Result = LHS;
6499 Overflow = ConstantInt::getFalse(Ty: OverflowTy);
6500 return true;
6501 }
6502
6503 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, CxtI: &OrigI)) {
6504 case OverflowResult::MayOverflow:
6505 return false;
6506 case OverflowResult::AlwaysOverflowsLow:
6507 case OverflowResult::AlwaysOverflowsHigh:
6508 Result = Builder.CreateBinOp(Opc: BinaryOp, LHS, RHS);
6509 Result->takeName(V: &OrigI);
6510 Overflow = ConstantInt::getTrue(Ty: OverflowTy);
6511 return true;
6512 case OverflowResult::NeverOverflows:
6513 Result = Builder.CreateBinOp(Opc: BinaryOp, LHS, RHS);
6514 Result->takeName(V: &OrigI);
6515 Overflow = ConstantInt::getFalse(Ty: OverflowTy);
6516 if (auto *Inst = dyn_cast<Instruction>(Val: Result)) {
6517 if (IsSigned)
6518 Inst->setHasNoSignedWrap();
6519 else
6520 Inst->setHasNoUnsignedWrap();
6521 }
6522 return true;
6523 }
6524
6525 llvm_unreachable("Unexpected overflow result");
6526}
6527
6528/// Recognize and process idiom involving test for multiplication
6529/// overflow.
6530///
6531/// The caller has matched a pattern of the form:
6532/// I = cmp u (mul(zext A, zext B), V
6533/// The function checks if this is a test for overflow and if so replaces
6534/// multiplication with call to 'mul.with.overflow' intrinsic.
6535///
6536/// \param I Compare instruction.
6537/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
6538/// the compare instruction. Must be of integer type.
6539/// \param OtherVal The other argument of compare instruction.
6540/// \returns Instruction which must replace the compare instruction, NULL if no
6541/// replacement required.
6542static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,
6543 const APInt *OtherVal,
6544 InstCombinerImpl &IC) {
6545 // Don't bother doing this transformation for pointers, don't do it for
6546 // vectors.
6547 if (!isa<IntegerType>(Val: MulVal->getType()))
6548 return nullptr;
6549
6550 auto *MulInstr = dyn_cast<Instruction>(Val: MulVal);
6551 if (!MulInstr)
6552 return nullptr;
6553 assert(MulInstr->getOpcode() == Instruction::Mul);
6554
6555 auto *LHS = cast<ZExtInst>(Val: MulInstr->getOperand(i: 0)),
6556 *RHS = cast<ZExtInst>(Val: MulInstr->getOperand(i: 1));
6557 assert(LHS->getOpcode() == Instruction::ZExt);
6558 assert(RHS->getOpcode() == Instruction::ZExt);
6559 Value *A = LHS->getOperand(i_nocapture: 0), *B = RHS->getOperand(i_nocapture: 0);
6560
6561 // Calculate type and width of the result produced by mul.with.overflow.
6562 Type *TyA = A->getType(), *TyB = B->getType();
6563 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6564 WidthB = TyB->getPrimitiveSizeInBits();
6565 unsigned MulWidth;
6566 Type *MulType;
6567 if (WidthB > WidthA) {
6568 MulWidth = WidthB;
6569 MulType = TyB;
6570 } else {
6571 MulWidth = WidthA;
6572 MulType = TyA;
6573 }
6574
6575 // In order to replace the original mul with a narrower mul.with.overflow,
6576 // all uses must ignore upper bits of the product. The number of used low
6577 // bits must be not greater than the width of mul.with.overflow.
6578 if (MulVal->hasNUsesOrMore(N: 2))
6579 for (User *U : MulVal->users()) {
6580 if (U == &I)
6581 continue;
6582 if (TruncInst *TI = dyn_cast<TruncInst>(Val: U)) {
6583 // Check if truncation ignores bits above MulWidth.
6584 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
6585 if (TruncWidth > MulWidth)
6586 return nullptr;
6587 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: U)) {
6588 // Check if AND ignores bits above MulWidth.
6589 if (BO->getOpcode() != Instruction::And)
6590 return nullptr;
6591 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: BO->getOperand(i_nocapture: 1))) {
6592 const APInt &CVal = CI->getValue();
6593 if (CVal.getBitWidth() - CVal.countl_zero() > MulWidth)
6594 return nullptr;
6595 } else {
6596 // In this case we could have the operand of the binary operation
6597 // being defined in another block, and performing the replacement
6598 // could break the dominance relation.
6599 return nullptr;
6600 }
6601 } else {
6602 // Other uses prohibit this transformation.
6603 return nullptr;
6604 }
6605 }
6606
6607 // Recognize patterns
6608 switch (I.getPredicate()) {
6609 case ICmpInst::ICMP_UGT: {
6610 // Recognize pattern:
6611 // mulval = mul(zext A, zext B)
6612 // cmp ugt mulval, max
6613 APInt MaxVal = APInt::getMaxValue(numBits: MulWidth);
6614 MaxVal = MaxVal.zext(width: OtherVal->getBitWidth());
6615 if (MaxVal.eq(RHS: *OtherVal))
6616 break; // Recognized
6617 return nullptr;
6618 }
6619
6620 case ICmpInst::ICMP_ULT: {
6621 // Recognize pattern:
6622 // mulval = mul(zext A, zext B)
6623 // cmp ule mulval, max + 1
6624 APInt MaxVal = APInt::getOneBitSet(numBits: OtherVal->getBitWidth(), BitNo: MulWidth);
6625 if (MaxVal.eq(RHS: *OtherVal))
6626 break; // Recognized
6627 return nullptr;
6628 }
6629
6630 default:
6631 return nullptr;
6632 }
6633
6634 InstCombiner::BuilderTy &Builder = IC.Builder;
6635 Builder.SetInsertPoint(MulInstr);
6636
6637 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
6638 Value *MulA = A, *MulB = B;
6639 if (WidthA < MulWidth)
6640 MulA = Builder.CreateZExt(V: A, DestTy: MulType);
6641 if (WidthB < MulWidth)
6642 MulB = Builder.CreateZExt(V: B, DestTy: MulType);
6643 CallInst *Call =
6644 Builder.CreateIntrinsic(ID: Intrinsic::umul_with_overflow, Types: MulType,
6645 Args: {MulA, MulB}, /*FMFSource=*/nullptr, Name: "umul");
6646 IC.addToWorklist(I: MulInstr);
6647
6648 // If there are uses of mul result other than the comparison, we know that
6649 // they are truncation or binary AND. Change them to use result of
6650 // mul.with.overflow and adjust properly mask/size.
6651 if (MulVal->hasNUsesOrMore(N: 2)) {
6652 Value *Mul = Builder.CreateExtractValue(Agg: Call, Idxs: 0, Name: "umul.value");
6653 for (User *U : make_early_inc_range(Range: MulVal->users())) {
6654 if (U == &I)
6655 continue;
6656 if (TruncInst *TI = dyn_cast<TruncInst>(Val: U)) {
6657 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
6658 IC.replaceInstUsesWith(I&: *TI, V: Mul);
6659 else
6660 TI->setOperand(i_nocapture: 0, Val_nocapture: Mul);
6661 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: U)) {
6662 assert(BO->getOpcode() == Instruction::And);
6663 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
6664 ConstantInt *CI = cast<ConstantInt>(Val: BO->getOperand(i_nocapture: 1));
6665 APInt ShortMask = CI->getValue().trunc(width: MulWidth);
6666 Value *ShortAnd = Builder.CreateAnd(LHS: Mul, RHS: ShortMask);
6667 Value *Zext = Builder.CreateZExt(V: ShortAnd, DestTy: BO->getType());
6668 IC.replaceInstUsesWith(I&: *BO, V: Zext);
6669 } else {
6670 llvm_unreachable("Unexpected Binary operation");
6671 }
6672 IC.addToWorklist(I: cast<Instruction>(Val: U));
6673 }
6674 }
6675
6676 // The original icmp gets replaced with the overflow value, maybe inverted
6677 // depending on predicate.
6678 if (I.getPredicate() == ICmpInst::ICMP_ULT) {
6679 Value *Res = Builder.CreateExtractValue(Agg: Call, Idxs: 1);
6680 return BinaryOperator::CreateNot(Op: Res);
6681 }
6682
6683 return ExtractValueInst::Create(Agg: Call, Idxs: 1);
6684}
6685
6686/// When performing a comparison against a constant, it is possible that not all
6687/// the bits in the LHS are demanded. This helper method computes the mask that
6688/// IS demanded.
6689static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) {
6690 const APInt *RHS;
6691 if (!match(V: I.getOperand(i_nocapture: 1), P: m_APInt(Res&: RHS)))
6692 return APInt::getAllOnes(numBits: BitWidth);
6693
6694 // If this is a normal comparison, it demands all bits. If it is a sign bit
6695 // comparison, it only demands the sign bit.
6696 bool UnusedBit;
6697 if (isSignBitCheck(Pred: I.getPredicate(), RHS: *RHS, TrueIfSigned&: UnusedBit))
6698 return APInt::getSignMask(BitWidth);
6699
6700 switch (I.getPredicate()) {
6701 // For a UGT comparison, we don't care about any bits that
6702 // correspond to the trailing ones of the comparand. The value of these
6703 // bits doesn't impact the outcome of the comparison, because any value
6704 // greater than the RHS must differ in a bit higher than these due to carry.
6705 case ICmpInst::ICMP_UGT:
6706 return APInt::getBitsSetFrom(numBits: BitWidth, loBit: RHS->countr_one());
6707
6708 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
6709 // Any value less than the RHS must differ in a higher bit because of carries.
6710 case ICmpInst::ICMP_ULT:
6711 return APInt::getBitsSetFrom(numBits: BitWidth, loBit: RHS->countr_zero());
6712
6713 default:
6714 return APInt::getAllOnes(numBits: BitWidth);
6715 }
6716}
6717
6718/// Check that one use is in the same block as the definition and all
6719/// other uses are in blocks dominated by a given block.
6720///
6721/// \param DI Definition
6722/// \param UI Use
6723/// \param DB Block that must dominate all uses of \p DI outside
6724/// the parent block
6725/// \return true when \p UI is the only use of \p DI in the parent block
6726/// and all other uses of \p DI are in blocks dominated by \p DB.
6727///
6728bool InstCombinerImpl::dominatesAllUses(const Instruction *DI,
6729 const Instruction *UI,
6730 const BasicBlock *DB) const {
6731 assert(DI && UI && "Instruction not defined\n");
6732 // Ignore incomplete definitions.
6733 if (!DI->getParent())
6734 return false;
6735 // DI and UI must be in the same block.
6736 if (DI->getParent() != UI->getParent())
6737 return false;
6738 // Protect from self-referencing blocks.
6739 if (DI->getParent() == DB)
6740 return false;
6741 for (const User *U : DI->users()) {
6742 auto *Usr = cast<Instruction>(Val: U);
6743 if (Usr != UI && !DT.dominates(A: DB, B: Usr->getParent()))
6744 return false;
6745 }
6746 return true;
6747}
6748
6749/// Return true when the instruction sequence within a block is select-cmp-br.
6750static bool isChainSelectCmpBranch(const SelectInst *SI) {
6751 const BasicBlock *BB = SI->getParent();
6752 if (!BB)
6753 return false;
6754 auto *BI = dyn_cast_or_null<BranchInst>(Val: BB->getTerminator());
6755 if (!BI || BI->getNumSuccessors() != 2)
6756 return false;
6757 auto *IC = dyn_cast<ICmpInst>(Val: BI->getCondition());
6758 if (!IC || (IC->getOperand(i_nocapture: 0) != SI && IC->getOperand(i_nocapture: 1) != SI))
6759 return false;
6760 return true;
6761}
6762
6763/// True when a select result is replaced by one of its operands
6764/// in select-icmp sequence. This will eventually result in the elimination
6765/// of the select.
6766///
6767/// \param SI Select instruction
6768/// \param Icmp Compare instruction
6769/// \param SIOpd Operand that replaces the select
6770///
6771/// Notes:
6772/// - The replacement is global and requires dominator information
6773/// - The caller is responsible for the actual replacement
6774///
6775/// Example:
6776///
6777/// entry:
6778/// %4 = select i1 %3, %C* %0, %C* null
6779/// %5 = icmp eq %C* %4, null
6780/// br i1 %5, label %9, label %7
6781/// ...
6782/// ; <label>:7 ; preds = %entry
6783/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
6784/// ...
6785///
6786/// can be transformed to
6787///
6788/// %5 = icmp eq %C* %0, null
6789/// %6 = select i1 %3, i1 %5, i1 true
6790/// br i1 %6, label %9, label %7
6791/// ...
6792/// ; <label>:7 ; preds = %entry
6793/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
6794///
6795/// Similar when the first operand of the select is a constant or/and
6796/// the compare is for not equal rather than equal.
6797///
6798/// NOTE: The function is only called when the select and compare constants
6799/// are equal, the optimization can work only for EQ predicates. This is not a
6800/// major restriction since a NE compare should be 'normalized' to an equal
6801/// compare, which usually happens in the combiner and test case
6802/// select-cmp-br.ll checks for it.
6803bool InstCombinerImpl::replacedSelectWithOperand(SelectInst *SI,
6804 const ICmpInst *Icmp,
6805 const unsigned SIOpd) {
6806 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
6807 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
6808 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(Idx: 1);
6809 // The check for the single predecessor is not the best that can be
6810 // done. But it protects efficiently against cases like when SI's
6811 // home block has two successors, Succ and Succ1, and Succ1 predecessor
6812 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
6813 // replaced can be reached on either path. So the uniqueness check
6814 // guarantees that the path all uses of SI (outside SI's parent) are on
6815 // is disjoint from all other paths out of SI. But that information
6816 // is more expensive to compute, and the trade-off here is in favor
6817 // of compile-time. It should also be noticed that we check for a single
6818 // predecessor and not only uniqueness. This to handle the situation when
6819 // Succ and Succ1 points to the same basic block.
6820 if (Succ->getSinglePredecessor() && dominatesAllUses(DI: SI, UI: Icmp, DB: Succ)) {
6821 NumSel++;
6822 SI->replaceUsesOutsideBlock(V: SI->getOperand(i_nocapture: SIOpd), BB: SI->getParent());
6823 return true;
6824 }
6825 }
6826 return false;
6827}
6828
6829/// Try to fold the comparison based on range information we can get by checking
6830/// whether bits are known to be zero or one in the inputs.
6831Instruction *InstCombinerImpl::foldICmpUsingKnownBits(ICmpInst &I) {
6832 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
6833 Type *Ty = Op0->getType();
6834 ICmpInst::Predicate Pred = I.getPredicate();
6835
6836 // Get scalar or pointer size.
6837 unsigned BitWidth = Ty->isIntOrIntVectorTy()
6838 ? Ty->getScalarSizeInBits()
6839 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
6840
6841 if (!BitWidth)
6842 return nullptr;
6843
6844 KnownBits Op0Known(BitWidth);
6845 KnownBits Op1Known(BitWidth);
6846
6847 {
6848 // Don't use dominating conditions when folding icmp using known bits. This
6849 // may convert signed into unsigned predicates in ways that other passes
6850 // (especially IndVarSimplify) may not be able to reliably undo.
6851 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(I: &I);
6852 if (SimplifyDemandedBits(I: &I, Op: 0, DemandedMask: getDemandedBitsLHSMask(I, BitWidth),
6853 Known&: Op0Known, Q))
6854 return &I;
6855
6856 if (SimplifyDemandedBits(I: &I, Op: 1, DemandedMask: APInt::getAllOnes(numBits: BitWidth), Known&: Op1Known, Q))
6857 return &I;
6858 }
6859
6860 if (!isa<Constant>(Val: Op0) && Op0Known.isConstant())
6861 return new ICmpInst(
6862 Pred, ConstantExpr::getIntegerValue(Ty, V: Op0Known.getConstant()), Op1);
6863 if (!isa<Constant>(Val: Op1) && Op1Known.isConstant())
6864 return new ICmpInst(
6865 Pred, Op0, ConstantExpr::getIntegerValue(Ty, V: Op1Known.getConstant()));
6866
6867 if (std::optional<bool> Res = ICmpInst::compare(LHS: Op0Known, RHS: Op1Known, Pred))
6868 return replaceInstUsesWith(I, V: ConstantInt::getBool(Ty: I.getType(), V: *Res));
6869
6870 // Given the known and unknown bits, compute a range that the LHS could be
6871 // in. Compute the Min, Max and RHS values based on the known bits. For the
6872 // EQ and NE we use unsigned values.
6873 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6874 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6875 if (I.isSigned()) {
6876 Op0Min = Op0Known.getSignedMinValue();
6877 Op0Max = Op0Known.getSignedMaxValue();
6878 Op1Min = Op1Known.getSignedMinValue();
6879 Op1Max = Op1Known.getSignedMaxValue();
6880 } else {
6881 Op0Min = Op0Known.getMinValue();
6882 Op0Max = Op0Known.getMaxValue();
6883 Op1Min = Op1Known.getMinValue();
6884 Op1Max = Op1Known.getMaxValue();
6885 }
6886
6887 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
6888 // min/max canonical compare with some other compare. That could lead to
6889 // conflict with select canonicalization and infinite looping.
6890 // FIXME: This constraint may go away if min/max intrinsics are canonical.
6891 auto isMinMaxCmp = [&](Instruction &Cmp) {
6892 if (!Cmp.hasOneUse())
6893 return false;
6894 Value *A, *B;
6895 SelectPatternFlavor SPF = matchSelectPattern(V: Cmp.user_back(), LHS&: A, RHS&: B).Flavor;
6896 if (!SelectPatternResult::isMinOrMax(SPF))
6897 return false;
6898 return match(V: Op0, P: m_MaxOrMin(L: m_Value(), R: m_Value())) ||
6899 match(V: Op1, P: m_MaxOrMin(L: m_Value(), R: m_Value()));
6900 };
6901 if (!isMinMaxCmp(I)) {
6902 switch (Pred) {
6903 default:
6904 break;
6905 case ICmpInst::ICMP_ULT: {
6906 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6907 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6908 const APInt *CmpC;
6909 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
6910 // A <u C -> A == C-1 if min(A)+1 == C
6911 if (*CmpC == Op0Min + 1)
6912 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6913 ConstantInt::get(Ty: Op1->getType(), V: *CmpC - 1));
6914 // X <u C --> X == 0, if the number of zero bits in the bottom of X
6915 // exceeds the log2 of C.
6916 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
6917 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6918 Constant::getNullValue(Ty: Op1->getType()));
6919 }
6920 break;
6921 }
6922 case ICmpInst::ICMP_UGT: {
6923 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6924 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6925 const APInt *CmpC;
6926 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
6927 // A >u C -> A == C+1 if max(a)-1 == C
6928 if (*CmpC == Op0Max - 1)
6929 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6930 ConstantInt::get(Ty: Op1->getType(), V: *CmpC + 1));
6931 // X >u C --> X != 0, if the number of zero bits in the bottom of X
6932 // exceeds the log2 of C.
6933 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
6934 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
6935 Constant::getNullValue(Ty: Op1->getType()));
6936 }
6937 break;
6938 }
6939 case ICmpInst::ICMP_SLT: {
6940 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6941 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6942 const APInt *CmpC;
6943 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
6944 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
6945 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6946 ConstantInt::get(Ty: Op1->getType(), V: *CmpC - 1));
6947 }
6948 break;
6949 }
6950 case ICmpInst::ICMP_SGT: {
6951 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6952 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6953 const APInt *CmpC;
6954 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
6955 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
6956 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6957 ConstantInt::get(Ty: Op1->getType(), V: *CmpC + 1));
6958 }
6959 break;
6960 }
6961 }
6962 }
6963
6964 // Based on the range information we know about the LHS, see if we can
6965 // simplify this comparison. For example, (x&4) < 8 is always true.
6966 switch (Pred) {
6967 default:
6968 break;
6969 case ICmpInst::ICMP_EQ:
6970 case ICmpInst::ICMP_NE: {
6971 // If all bits are known zero except for one, then we know at most one bit
6972 // is set. If the comparison is against zero, then this is a check to see if
6973 // *that* bit is set.
6974 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
6975 if (Op1Known.isZero()) {
6976 // If the LHS is an AND with the same constant, look through it.
6977 Value *LHS = nullptr;
6978 const APInt *LHSC;
6979 if (!match(V: Op0, P: m_And(L: m_Value(V&: LHS), R: m_APInt(Res&: LHSC))) ||
6980 *LHSC != Op0KnownZeroInverted)
6981 LHS = Op0;
6982
6983 Value *X;
6984 const APInt *C1;
6985 if (match(V: LHS, P: m_Shl(L: m_Power2(V&: C1), R: m_Value(V&: X)))) {
6986 Type *XTy = X->getType();
6987 unsigned Log2C1 = C1->countr_zero();
6988 APInt C2 = Op0KnownZeroInverted;
6989 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
6990 if (C2Pow2.isPowerOf2()) {
6991 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
6992 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
6993 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
6994 unsigned Log2C2 = C2Pow2.countr_zero();
6995 auto *CmpC = ConstantInt::get(Ty: XTy, V: Log2C2 - Log2C1);
6996 auto NewPred =
6997 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
6998 return new ICmpInst(NewPred, X, CmpC);
6999 }
7000 }
7001 }
7002
7003 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
7004 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
7005 (Op0Known & Op1Known) == Op0Known)
7006 return new ICmpInst(CmpInst::getInversePredicate(pred: Pred), Op0,
7007 ConstantInt::getNullValue(Ty: Op1->getType()));
7008 break;
7009 }
7010 case ICmpInst::ICMP_SGE:
7011 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
7012 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7013 break;
7014 case ICmpInst::ICMP_SLE:
7015 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
7016 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7017 break;
7018 case ICmpInst::ICMP_UGE:
7019 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
7020 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7021 break;
7022 case ICmpInst::ICMP_ULE:
7023 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
7024 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7025 break;
7026 }
7027
7028 // Turn a signed comparison into an unsigned one if both operands are known to
7029 // have the same sign. Set samesign if possible (except for equality
7030 // predicates).
7031 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
7032 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
7033 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
7034 I.setPredicate(I.getUnsignedPredicate());
7035 I.setSameSign();
7036 return &I;
7037 }
7038
7039 return nullptr;
7040}
7041
7042/// If one operand of an icmp is effectively a bool (value range of {0,1}),
7043/// then try to reduce patterns based on that limit.
7044Instruction *InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst &I) {
7045 Value *X, *Y;
7046 CmpPredicate Pred;
7047
7048 // X must be 0 and bool must be true for "ULT":
7049 // X <u (zext i1 Y) --> (X == 0) & Y
7050 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))))) &&
7051 Y->getType()->isIntOrIntVectorTy(BitWidth: 1) && Pred == ICmpInst::ICMP_ULT)
7052 return BinaryOperator::CreateAnd(V1: Builder.CreateIsNull(Arg: X), V2: Y);
7053
7054 // X must be 0 or bool must be true for "ULE":
7055 // X <=u (sext i1 Y) --> (X == 0) | Y
7056 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))))) &&
7057 Y->getType()->isIntOrIntVectorTy(BitWidth: 1) && Pred == ICmpInst::ICMP_ULE)
7058 return BinaryOperator::CreateOr(V1: Builder.CreateIsNull(Arg: X), V2: Y);
7059
7060 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
7061 CmpPredicate Pred1, Pred2;
7062 const APInt *C;
7063 Instruction *ExtI;
7064 if (match(V: &I, P: m_c_ICmp(Pred&: Pred1, L: m_Value(V&: X),
7065 R: m_CombineAnd(L: m_Instruction(I&: ExtI),
7066 R: m_ZExtOrSExt(Op: m_ICmp(Pred&: Pred2, L: m_Deferred(V: X),
7067 R: m_APInt(Res&: C)))))) &&
7068 ICmpInst::isEquality(P: Pred1) && ICmpInst::isEquality(P: Pred2)) {
7069 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
7070 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(i: 0)->hasOneUse();
7071 auto CreateRangeCheck = [&] {
7072 Value *CmpV1 =
7073 Builder.CreateICmp(P: Pred1, LHS: X, RHS: Constant::getNullValue(Ty: X->getType()));
7074 Value *CmpV2 = Builder.CreateICmp(
7075 P: Pred1, LHS: X, RHS: ConstantInt::getSigned(Ty: X->getType(), V: IsSExt ? -1 : 1));
7076 return BinaryOperator::Create(
7077 Op: Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
7078 S1: CmpV1, S2: CmpV2);
7079 };
7080 if (C->isZero()) {
7081 if (Pred2 == ICmpInst::ICMP_EQ) {
7082 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
7083 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
7084 return replaceInstUsesWith(
7085 I, V: ConstantInt::getBool(Ty: I.getType(), V: Pred1 == ICmpInst::ICMP_NE));
7086 } else if (!IsSExt || HasOneUse) {
7087 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
7088 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
7089 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
7090 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X != -1
7091 return CreateRangeCheck();
7092 }
7093 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
7094 if (Pred2 == ICmpInst::ICMP_NE) {
7095 // icmp eq X, (zext (icmp ne X, 1)) --> false
7096 // icmp ne X, (zext (icmp ne X, 1)) --> true
7097 // icmp eq X, (sext (icmp ne X, -1)) --> false
7098 // icmp ne X, (sext (icmp ne X, -1)) --> true
7099 return replaceInstUsesWith(
7100 I, V: ConstantInt::getBool(Ty: I.getType(), V: Pred1 == ICmpInst::ICMP_NE));
7101 } else if (!IsSExt || HasOneUse) {
7102 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
7103 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
7104 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
7105 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
7106 return CreateRangeCheck();
7107 }
7108 } else {
7109 // when C != 0 && C != 1:
7110 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
7111 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
7112 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
7113 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
7114 // when C != 0 && C != -1:
7115 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
7116 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
7117 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
7118 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
7119 return ICmpInst::Create(
7120 Op: Instruction::ICmp, Pred: Pred1, S1: X,
7121 S2: ConstantInt::getSigned(Ty: X->getType(), V: Pred2 == ICmpInst::ICMP_NE
7122 ? (IsSExt ? -1 : 1)
7123 : 0));
7124 }
7125 }
7126
7127 return nullptr;
7128}
7129
7130/// If we have an icmp le or icmp ge instruction with a constant operand, turn
7131/// it into the appropriate icmp lt or icmp gt instruction. This transform
7132/// allows them to be folded in visitICmpInst.
7133static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
7134 ICmpInst::Predicate Pred = I.getPredicate();
7135 if (ICmpInst::isEquality(P: Pred) || !ICmpInst::isIntPredicate(P: Pred) ||
7136 InstCombiner::isCanonicalPredicate(Pred))
7137 return nullptr;
7138
7139 Value *Op0 = I.getOperand(i_nocapture: 0);
7140 Value *Op1 = I.getOperand(i_nocapture: 1);
7141 auto *Op1C = dyn_cast<Constant>(Val: Op1);
7142 if (!Op1C)
7143 return nullptr;
7144
7145 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, C: Op1C);
7146 if (!FlippedStrictness)
7147 return nullptr;
7148
7149 return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7150}
7151
7152/// If we have a comparison with a non-canonical predicate, if we can update
7153/// all the users, invert the predicate and adjust all the users.
7154CmpInst *InstCombinerImpl::canonicalizeICmpPredicate(CmpInst &I) {
7155 // Is the predicate already canonical?
7156 CmpInst::Predicate Pred = I.getPredicate();
7157 if (InstCombiner::isCanonicalPredicate(Pred))
7158 return nullptr;
7159
7160 // Can all users be adjusted to predicate inversion?
7161 if (!InstCombiner::canFreelyInvertAllUsersOf(V: &I, /*IgnoredUser=*/nullptr))
7162 return nullptr;
7163
7164 // Ok, we can canonicalize comparison!
7165 // Let's first invert the comparison's predicate.
7166 I.setPredicate(CmpInst::getInversePredicate(pred: Pred));
7167 I.setName(I.getName() + ".not");
7168
7169 // And, adapt users.
7170 freelyInvertAllUsersOf(V: &I);
7171
7172 return &I;
7173}
7174
7175/// Integer compare with boolean values can always be turned into bitwise ops.
7176static Instruction *canonicalizeICmpBool(ICmpInst &I,
7177 InstCombiner::BuilderTy &Builder) {
7178 Value *A = I.getOperand(i_nocapture: 0), *B = I.getOperand(i_nocapture: 1);
7179 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
7180
7181 // A boolean compared to true/false can be simplified to Op0/true/false in
7182 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
7183 // Cases not handled by InstSimplify are always 'not' of Op0.
7184 if (match(V: B, P: m_Zero())) {
7185 switch (I.getPredicate()) {
7186 case CmpInst::ICMP_EQ: // A == 0 -> !A
7187 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
7188 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7189 return BinaryOperator::CreateNot(Op: A);
7190 default:
7191 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7192 }
7193 } else if (match(V: B, P: m_One())) {
7194 switch (I.getPredicate()) {
7195 case CmpInst::ICMP_NE: // A != 1 -> !A
7196 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7197 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7198 return BinaryOperator::CreateNot(Op: A);
7199 default:
7200 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7201 }
7202 }
7203
7204 switch (I.getPredicate()) {
7205 default:
7206 llvm_unreachable("Invalid icmp instruction!");
7207 case ICmpInst::ICMP_EQ:
7208 // icmp eq i1 A, B -> ~(A ^ B)
7209 return BinaryOperator::CreateNot(Op: Builder.CreateXor(LHS: A, RHS: B));
7210
7211 case ICmpInst::ICMP_NE:
7212 // icmp ne i1 A, B -> A ^ B
7213 return BinaryOperator::CreateXor(V1: A, V2: B);
7214
7215 case ICmpInst::ICMP_UGT:
7216 // icmp ugt -> icmp ult
7217 std::swap(a&: A, b&: B);
7218 [[fallthrough]];
7219 case ICmpInst::ICMP_ULT:
7220 // icmp ult i1 A, B -> ~A & B
7221 return BinaryOperator::CreateAnd(V1: Builder.CreateNot(V: A), V2: B);
7222
7223 case ICmpInst::ICMP_SGT:
7224 // icmp sgt -> icmp slt
7225 std::swap(a&: A, b&: B);
7226 [[fallthrough]];
7227 case ICmpInst::ICMP_SLT:
7228 // icmp slt i1 A, B -> A & ~B
7229 return BinaryOperator::CreateAnd(V1: Builder.CreateNot(V: B), V2: A);
7230
7231 case ICmpInst::ICMP_UGE:
7232 // icmp uge -> icmp ule
7233 std::swap(a&: A, b&: B);
7234 [[fallthrough]];
7235 case ICmpInst::ICMP_ULE:
7236 // icmp ule i1 A, B -> ~A | B
7237 return BinaryOperator::CreateOr(V1: Builder.CreateNot(V: A), V2: B);
7238
7239 case ICmpInst::ICMP_SGE:
7240 // icmp sge -> icmp sle
7241 std::swap(a&: A, b&: B);
7242 [[fallthrough]];
7243 case ICmpInst::ICMP_SLE:
7244 // icmp sle i1 A, B -> A | ~B
7245 return BinaryOperator::CreateOr(V1: Builder.CreateNot(V: B), V2: A);
7246 }
7247}
7248
7249// Transform pattern like:
7250// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7251// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7252// Into:
7253// (X l>> Y) != 0
7254// (X l>> Y) == 0
7255static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp,
7256 InstCombiner::BuilderTy &Builder) {
7257 CmpPredicate Pred, NewPred;
7258 Value *X, *Y;
7259 if (match(V: &Cmp,
7260 P: m_c_ICmp(Pred, L: m_OneUse(SubPattern: m_Shl(L: m_One(), R: m_Value(V&: Y))), R: m_Value(V&: X)))) {
7261 switch (Pred) {
7262 case ICmpInst::ICMP_ULE:
7263 NewPred = ICmpInst::ICMP_NE;
7264 break;
7265 case ICmpInst::ICMP_UGT:
7266 NewPred = ICmpInst::ICMP_EQ;
7267 break;
7268 default:
7269 return nullptr;
7270 }
7271 } else if (match(V: &Cmp, P: m_c_ICmp(Pred,
7272 L: m_OneUse(SubPattern: m_CombineOr(
7273 L: m_Not(V: m_Shl(L: m_AllOnes(), R: m_Value(V&: Y))),
7274 R: m_Add(L: m_Shl(L: m_One(), R: m_Value(V&: Y)),
7275 R: m_AllOnes()))),
7276 R: m_Value(V&: X)))) {
7277 // The variant with 'add' is not canonical, (the variant with 'not' is)
7278 // we only get it because it has extra uses, and can't be canonicalized,
7279
7280 switch (Pred) {
7281 case ICmpInst::ICMP_ULT:
7282 NewPred = ICmpInst::ICMP_NE;
7283 break;
7284 case ICmpInst::ICMP_UGE:
7285 NewPred = ICmpInst::ICMP_EQ;
7286 break;
7287 default:
7288 return nullptr;
7289 }
7290 } else
7291 return nullptr;
7292
7293 Value *NewX = Builder.CreateLShr(LHS: X, RHS: Y, Name: X->getName() + ".highbits");
7294 Constant *Zero = Constant::getNullValue(Ty: NewX->getType());
7295 return CmpInst::Create(Op: Instruction::ICmp, Pred: NewPred, S1: NewX, S2: Zero);
7296}
7297
7298static Instruction *foldVectorCmp(CmpInst &Cmp,
7299 InstCombiner::BuilderTy &Builder) {
7300 const CmpInst::Predicate Pred = Cmp.getPredicate();
7301 Value *LHS = Cmp.getOperand(i_nocapture: 0), *RHS = Cmp.getOperand(i_nocapture: 1);
7302 Value *V1, *V2;
7303
7304 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7305 Value *V = Builder.CreateCmp(Pred, LHS: X, RHS: Y, Name: Cmp.getName());
7306 if (auto *I = dyn_cast<Instruction>(Val: V))
7307 I->copyIRFlags(V: &Cmp);
7308 Module *M = Cmp.getModule();
7309 Function *F = Intrinsic::getOrInsertDeclaration(
7310 M, id: Intrinsic::vector_reverse, Tys: V->getType());
7311 return CallInst::Create(Func: F, Args: V);
7312 };
7313
7314 if (match(V: LHS, P: m_VecReverse(Op0: m_Value(V&: V1)))) {
7315 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7316 if (match(V: RHS, P: m_VecReverse(Op0: m_Value(V&: V2))) &&
7317 (LHS->hasOneUse() || RHS->hasOneUse()))
7318 return createCmpReverse(Pred, V1, V2);
7319
7320 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7321 if (LHS->hasOneUse() && isSplatValue(V: RHS))
7322 return createCmpReverse(Pred, V1, RHS);
7323 }
7324 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7325 else if (isSplatValue(V: LHS) && match(V: RHS, P: m_OneUse(SubPattern: m_VecReverse(Op0: m_Value(V&: V2)))))
7326 return createCmpReverse(Pred, LHS, V2);
7327
7328 ArrayRef<int> M;
7329 if (!match(V: LHS, P: m_Shuffle(v1: m_Value(V&: V1), v2: m_Undef(), mask: m_Mask(M))))
7330 return nullptr;
7331
7332 // If both arguments of the cmp are shuffles that use the same mask and
7333 // shuffle within a single vector, move the shuffle after the cmp:
7334 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7335 Type *V1Ty = V1->getType();
7336 if (match(V: RHS, P: m_Shuffle(v1: m_Value(V&: V2), v2: m_Undef(), mask: m_SpecificMask(M))) &&
7337 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7338 Value *NewCmp = Builder.CreateCmp(Pred, LHS: V1, RHS: V2);
7339 return new ShuffleVectorInst(NewCmp, M);
7340 }
7341
7342 // Try to canonicalize compare with splatted operand and splat constant.
7343 // TODO: We could generalize this for more than splats. See/use the code in
7344 // InstCombiner::foldVectorBinop().
7345 Constant *C;
7346 if (!LHS->hasOneUse() || !match(V: RHS, P: m_Constant(C)))
7347 return nullptr;
7348
7349 // Length-changing splats are ok, so adjust the constants as needed:
7350 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7351 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7352 int MaskSplatIndex;
7353 if (ScalarC && match(Mask: M, P: m_SplatOrPoisonMask(MaskSplatIndex))) {
7354 // We allow poison in matching, but this transform removes it for safety.
7355 // Demanded elements analysis should be able to recover some/all of that.
7356 C = ConstantVector::getSplat(EC: cast<VectorType>(Val: V1Ty)->getElementCount(),
7357 Elt: ScalarC);
7358 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7359 Value *NewCmp = Builder.CreateCmp(Pred, LHS: V1, RHS: C);
7360 return new ShuffleVectorInst(NewCmp, NewM);
7361 }
7362
7363 return nullptr;
7364}
7365
7366// extract(uadd.with.overflow(A, B), 0) ult A
7367// -> extract(uadd.with.overflow(A, B), 1)
7368static Instruction *foldICmpOfUAddOv(ICmpInst &I) {
7369 CmpInst::Predicate Pred = I.getPredicate();
7370 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
7371
7372 Value *UAddOv;
7373 Value *A, *B;
7374 auto UAddOvResultPat = m_ExtractValue<0>(
7375 V: m_Intrinsic<Intrinsic::uadd_with_overflow>(Op0: m_Value(V&: A), Op1: m_Value(V&: B)));
7376 if (match(V: Op0, P: UAddOvResultPat) &&
7377 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7378 (Pred == ICmpInst::ICMP_EQ && match(V: Op1, P: m_ZeroInt()) &&
7379 (match(V: A, P: m_One()) || match(V: B, P: m_One()))) ||
7380 (Pred == ICmpInst::ICMP_NE && match(V: Op1, P: m_AllOnes()) &&
7381 (match(V: A, P: m_AllOnes()) || match(V: B, P: m_AllOnes())))))
7382 // extract(uadd.with.overflow(A, B), 0) < A
7383 // extract(uadd.with.overflow(A, 1), 0) == 0
7384 // extract(uadd.with.overflow(A, -1), 0) != -1
7385 UAddOv = cast<ExtractValueInst>(Val: Op0)->getAggregateOperand();
7386 else if (match(V: Op1, P: UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7387 (Op0 == A || Op0 == B))
7388 // A > extract(uadd.with.overflow(A, B), 0)
7389 UAddOv = cast<ExtractValueInst>(Val: Op1)->getAggregateOperand();
7390 else
7391 return nullptr;
7392
7393 return ExtractValueInst::Create(Agg: UAddOv, Idxs: 1);
7394}
7395
7396static Instruction *foldICmpInvariantGroup(ICmpInst &I) {
7397 if (!I.getOperand(i_nocapture: 0)->getType()->isPointerTy() ||
7398 NullPointerIsDefined(
7399 F: I.getParent()->getParent(),
7400 AS: I.getOperand(i_nocapture: 0)->getType()->getPointerAddressSpace())) {
7401 return nullptr;
7402 }
7403 Instruction *Op;
7404 if (match(V: I.getOperand(i_nocapture: 0), P: m_Instruction(I&: Op)) &&
7405 match(V: I.getOperand(i_nocapture: 1), P: m_Zero()) &&
7406 Op->isLaunderOrStripInvariantGroup()) {
7407 return ICmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(),
7408 S1: Op->getOperand(i: 0), S2: I.getOperand(i_nocapture: 1));
7409 }
7410 return nullptr;
7411}
7412
7413/// This function folds patterns produced by lowering of reduce idioms, such as
7414/// llvm.vector.reduce.and which are lowered into instruction chains. This code
7415/// attempts to generate fewer number of scalar comparisons instead of vector
7416/// comparisons when possible.
7417static Instruction *foldReductionIdiom(ICmpInst &I,
7418 InstCombiner::BuilderTy &Builder,
7419 const DataLayout &DL) {
7420 if (I.getType()->isVectorTy())
7421 return nullptr;
7422 CmpPredicate OuterPred, InnerPred;
7423 Value *LHS, *RHS;
7424
7425 // Match lowering of @llvm.vector.reduce.and. Turn
7426 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7427 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7428 /// %res = icmp <pred> i8 %scalar_ne, 0
7429 ///
7430 /// into
7431 ///
7432 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7433 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7434 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7435 ///
7436 /// for <pred> in {ne, eq}.
7437 if (!match(V: &I, P: m_ICmp(Pred&: OuterPred,
7438 L: m_OneUse(SubPattern: m_BitCast(Op: m_OneUse(
7439 SubPattern: m_ICmp(Pred&: InnerPred, L: m_Value(V&: LHS), R: m_Value(V&: RHS))))),
7440 R: m_Zero())))
7441 return nullptr;
7442 auto *LHSTy = dyn_cast<FixedVectorType>(Val: LHS->getType());
7443 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7444 return nullptr;
7445 unsigned NumBits =
7446 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7447 // TODO: Relax this to "not wider than max legal integer type"?
7448 if (!DL.isLegalInteger(Width: NumBits))
7449 return nullptr;
7450
7451 if (ICmpInst::isEquality(P: OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7452 auto *ScalarTy = Builder.getIntNTy(N: NumBits);
7453 LHS = Builder.CreateBitCast(V: LHS, DestTy: ScalarTy, Name: LHS->getName() + ".scalar");
7454 RHS = Builder.CreateBitCast(V: RHS, DestTy: ScalarTy, Name: RHS->getName() + ".scalar");
7455 return ICmpInst::Create(Op: Instruction::ICmp, Pred: OuterPred, S1: LHS, S2: RHS,
7456 Name: I.getName());
7457 }
7458
7459 return nullptr;
7460}
7461
7462// This helper will be called with icmp operands in both orders.
7463Instruction *InstCombinerImpl::foldICmpCommutative(CmpPredicate Pred,
7464 Value *Op0, Value *Op1,
7465 ICmpInst &CxtI) {
7466 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7467 if (auto *GEP = dyn_cast<GEPOperator>(Val: Op0))
7468 if (Instruction *NI = foldGEPICmp(GEPLHS: GEP, RHS: Op1, Cond: Pred, I&: CxtI))
7469 return NI;
7470
7471 if (auto *SI = dyn_cast<SelectInst>(Val: Op0))
7472 if (Instruction *NI = foldSelectICmp(Pred, SI, RHS: Op1, I: CxtI))
7473 return NI;
7474
7475 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Val: Op0))
7476 if (Instruction *Res = foldICmpWithMinMax(I&: CxtI, MinMax, Z: Op1, Pred))
7477 return Res;
7478
7479 {
7480 Value *X;
7481 const APInt *C;
7482 // icmp X+Cst, X
7483 if (match(V: Op0, P: m_Add(L: m_Value(V&: X), R: m_APInt(Res&: C))) && Op1 == X)
7484 return foldICmpAddOpConst(X, C: *C, Pred);
7485 }
7486
7487 // abs(X) >= X --> true
7488 // abs(X) u<= X --> true
7489 // abs(X) < X --> false
7490 // abs(X) u> X --> false
7491 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7492 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7493 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7494 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7495 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7496 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7497 {
7498 Value *X;
7499 Constant *C;
7500 if (match(V: Op0, P: m_Intrinsic<Intrinsic::abs>(Op0: m_Value(V&: X), Op1: m_Constant(C))) &&
7501 match(V: Op1, P: m_Specific(V: X))) {
7502 Value *NullValue = Constant::getNullValue(Ty: X->getType());
7503 Value *AllOnesValue = Constant::getAllOnesValue(Ty: X->getType());
7504 const APInt SMin =
7505 APInt::getSignedMinValue(numBits: X->getType()->getScalarSizeInBits());
7506 bool IsIntMinPosion = C->isAllOnesValue();
7507 switch (Pred) {
7508 case CmpInst::ICMP_ULE:
7509 case CmpInst::ICMP_SGE:
7510 return replaceInstUsesWith(I&: CxtI, V: ConstantInt::getTrue(Ty: CxtI.getType()));
7511 case CmpInst::ICMP_UGT:
7512 case CmpInst::ICMP_SLT:
7513 return replaceInstUsesWith(I&: CxtI, V: ConstantInt::getFalse(Ty: CxtI.getType()));
7514 case CmpInst::ICMP_UGE:
7515 case CmpInst::ICMP_SLE:
7516 case CmpInst::ICMP_EQ: {
7517 return replaceInstUsesWith(
7518 I&: CxtI, V: IsIntMinPosion
7519 ? Builder.CreateICmpSGT(LHS: X, RHS: AllOnesValue)
7520 : Builder.CreateICmpULT(
7521 LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: SMin + 1)));
7522 }
7523 case CmpInst::ICMP_ULT:
7524 case CmpInst::ICMP_SGT:
7525 case CmpInst::ICMP_NE: {
7526 return replaceInstUsesWith(
7527 I&: CxtI, V: IsIntMinPosion
7528 ? Builder.CreateICmpSLT(LHS: X, RHS: NullValue)
7529 : Builder.CreateICmpUGT(
7530 LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: SMin)));
7531 }
7532 default:
7533 llvm_unreachable("Invalid predicate!");
7534 }
7535 }
7536 }
7537
7538 const SimplifyQuery Q = SQ.getWithInstruction(I: &CxtI);
7539 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, IC&: *this))
7540 return replaceInstUsesWith(I&: CxtI, V);
7541
7542 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
7543 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(RHS: 1); };
7544 {
7545 if (match(V: Op0, P: m_UDiv(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckUGT1)))) {
7546 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7547 Constant::getNullValue(Ty: Op1->getType()));
7548 }
7549
7550 if (!ICmpInst::isUnsigned(predicate: Pred) &&
7551 match(V: Op0, P: m_SDiv(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckUGT1)))) {
7552 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7553 Constant::getNullValue(Ty: Op1->getType()));
7554 }
7555 }
7556
7557 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
7558 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
7559 {
7560 if (match(V: Op0, P: m_LShr(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckNE0)))) {
7561 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7562 Constant::getNullValue(Ty: Op1->getType()));
7563 }
7564
7565 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
7566 match(V: Op0, P: m_AShr(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckNE0)))) {
7567 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7568 Constant::getNullValue(Ty: Op1->getType()));
7569 }
7570 }
7571
7572 return nullptr;
7573}
7574
7575Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {
7576 bool Changed = false;
7577 const SimplifyQuery Q = SQ.getWithInstruction(I: &I);
7578 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
7579 unsigned Op0Cplxity = getComplexity(V: Op0);
7580 unsigned Op1Cplxity = getComplexity(V: Op1);
7581
7582 /// Orders the operands of the compare so that they are listed from most
7583 /// complex to least complex. This puts constants before unary operators,
7584 /// before binary operators.
7585 if (Op0Cplxity < Op1Cplxity) {
7586 I.swapOperands();
7587 std::swap(a&: Op0, b&: Op1);
7588 Changed = true;
7589 }
7590
7591 if (Value *V = simplifyICmpInst(Pred: I.getCmpPredicate(), LHS: Op0, RHS: Op1, Q))
7592 return replaceInstUsesWith(I, V);
7593
7594 // Comparing -val or val with non-zero is the same as just comparing val
7595 // ie, abs(val) != 0 -> val != 0
7596 if (I.getPredicate() == ICmpInst::ICMP_NE && match(V: Op1, P: m_Zero())) {
7597 Value *Cond, *SelectTrue, *SelectFalse;
7598 if (match(V: Op0, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: SelectTrue),
7599 R: m_Value(V&: SelectFalse)))) {
7600 if (Value *V = dyn_castNegVal(V: SelectTrue)) {
7601 if (V == SelectFalse)
7602 return CmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(), S1: V, S2: Op1);
7603 } else if (Value *V = dyn_castNegVal(V: SelectFalse)) {
7604 if (V == SelectTrue)
7605 return CmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(), S1: V, S2: Op1);
7606 }
7607 }
7608 }
7609
7610 if (Instruction *Res = foldICmpTruncWithTruncOrExt(Cmp&: I, Q))
7611 return Res;
7612
7613 if (Op0->getType()->isIntOrIntVectorTy(BitWidth: 1))
7614 if (Instruction *Res = canonicalizeICmpBool(I, Builder))
7615 return Res;
7616
7617 if (Instruction *Res = canonicalizeCmpWithConstant(I))
7618 return Res;
7619
7620 if (Instruction *Res = canonicalizeICmpPredicate(I))
7621 return Res;
7622
7623 if (Instruction *Res = foldICmpWithConstant(Cmp&: I))
7624 return Res;
7625
7626 if (Instruction *Res = foldICmpWithDominatingICmp(Cmp&: I))
7627 return Res;
7628
7629 if (Instruction *Res = foldICmpUsingBoolRange(I))
7630 return Res;
7631
7632 if (Instruction *Res = foldICmpUsingKnownBits(I))
7633 return Res;
7634
7635 // Test if the ICmpInst instruction is used exclusively by a select as
7636 // part of a minimum or maximum operation. If so, refrain from doing
7637 // any other folding. This helps out other analyses which understand
7638 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
7639 // and CodeGen. And in this case, at least one of the comparison
7640 // operands has at least one user besides the compare (the select),
7641 // which would often largely negate the benefit of folding anyway.
7642 //
7643 // Do the same for the other patterns recognized by matchSelectPattern.
7644 if (I.hasOneUse())
7645 if (SelectInst *SI = dyn_cast<SelectInst>(Val: I.user_back())) {
7646 Value *A, *B;
7647 SelectPatternResult SPR = matchSelectPattern(V: SI, LHS&: A, RHS&: B);
7648 if (SPR.Flavor != SPF_UNKNOWN)
7649 return nullptr;
7650 }
7651
7652 // Do this after checking for min/max to prevent infinite looping.
7653 if (Instruction *Res = foldICmpWithZero(Cmp&: I))
7654 return Res;
7655
7656 // FIXME: We only do this after checking for min/max to prevent infinite
7657 // looping caused by a reverse canonicalization of these patterns for min/max.
7658 // FIXME: The organization of folds is a mess. These would naturally go into
7659 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
7660 // down here after the min/max restriction.
7661 ICmpInst::Predicate Pred = I.getPredicate();
7662 const APInt *C;
7663 if (match(V: Op1, P: m_APInt(Res&: C))) {
7664 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
7665 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
7666 Constant *Zero = Constant::getNullValue(Ty: Op0->getType());
7667 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
7668 }
7669
7670 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
7671 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
7672 Constant *AllOnes = Constant::getAllOnesValue(Ty: Op0->getType());
7673 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
7674 }
7675 }
7676
7677 // The folds in here may rely on wrapping flags and special constants, so
7678 // they can break up min/max idioms in some cases but not seemingly similar
7679 // patterns.
7680 // FIXME: It may be possible to enhance select folding to make this
7681 // unnecessary. It may also be moot if we canonicalize to min/max
7682 // intrinsics.
7683 if (Instruction *Res = foldICmpBinOp(I, SQ: Q))
7684 return Res;
7685
7686 if (Instruction *Res = foldICmpInstWithConstant(Cmp&: I))
7687 return Res;
7688
7689 // Try to match comparison as a sign bit test. Intentionally do this after
7690 // foldICmpInstWithConstant() to potentially let other folds to happen first.
7691 if (Instruction *New = foldSignBitTest(I))
7692 return New;
7693
7694 if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
7695 return Res;
7696
7697 if (Instruction *Res = foldICmpCommutative(Pred: I.getCmpPredicate(), Op0, Op1, CxtI&: I))
7698 return Res;
7699 if (Instruction *Res =
7700 foldICmpCommutative(Pred: I.getSwappedCmpPredicate(), Op0: Op1, Op1: Op0, CxtI&: I))
7701 return Res;
7702
7703 if (I.isCommutative()) {
7704 if (auto Pair = matchSymmetricPair(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1))) {
7705 replaceOperand(I, OpNum: 0, V: Pair->first);
7706 replaceOperand(I, OpNum: 1, V: Pair->second);
7707 return &I;
7708 }
7709 }
7710
7711 // In case of a comparison with two select instructions having the same
7712 // condition, check whether one of the resulting branches can be simplified.
7713 // If so, just compare the other branch and select the appropriate result.
7714 // For example:
7715 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
7716 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
7717 // %cmp2 = icmp slt i32 %tmp2, %tmp1
7718 // The icmp will result false for the false value of selects and the result
7719 // will depend upon the comparison of true values of selects if %cmp is
7720 // true. Thus, transform this into:
7721 // %cmp = icmp slt i32 %y, %z
7722 // %sel = select i1 %cond, i1 %cmp, i1 false
7723 // This handles similar cases to transform.
7724 {
7725 Value *Cond, *A, *B, *C, *D;
7726 if (match(V: Op0, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: A), R: m_Value(V&: B))) &&
7727 match(V: Op1, P: m_Select(C: m_Specific(V: Cond), L: m_Value(V&: C), R: m_Value(V&: D))) &&
7728 (Op0->hasOneUse() || Op1->hasOneUse())) {
7729 // Check whether comparison of TrueValues can be simplified
7730 if (Value *Res = simplifyICmpInst(Pred, LHS: A, RHS: C, Q: SQ)) {
7731 Value *NewICMP = Builder.CreateICmp(P: Pred, LHS: B, RHS: D);
7732 return SelectInst::Create(C: Cond, S1: Res, S2: NewICMP);
7733 }
7734 // Check whether comparison of FalseValues can be simplified
7735 if (Value *Res = simplifyICmpInst(Pred, LHS: B, RHS: D, Q: SQ)) {
7736 Value *NewICMP = Builder.CreateICmp(P: Pred, LHS: A, RHS: C);
7737 return SelectInst::Create(C: Cond, S1: NewICMP, S2: Res);
7738 }
7739 }
7740 }
7741
7742 // icmp slt (sub nsw x, y), (add nsw x, y) --> icmp sgt y, 0
7743 // icmp ult (sub nuw x, y), (add nuw x, y) --> icmp ugt y, 0
7744 // icmp eq (sub nsw/nuw x, y), (add nsw/nuw x, y) --> icmp eq y, 0
7745 {
7746 Value *A, *B;
7747 CmpPredicate CmpPred;
7748 if (match(V: &I, P: m_c_ICmp(Pred&: CmpPred, L: m_Sub(L: m_Value(V&: A), R: m_Value(V&: B)),
7749 R: m_c_Add(L: m_Deferred(V: A), R: m_Deferred(V: B))))) {
7750 auto *I0 = cast<OverflowingBinaryOperator>(Val: Op0);
7751 auto *I1 = cast<OverflowingBinaryOperator>(Val: Op1);
7752 bool I0NUW = I0->hasNoUnsignedWrap();
7753 bool I1NUW = I1->hasNoUnsignedWrap();
7754 bool I0NSW = I0->hasNoSignedWrap();
7755 bool I1NSW = I1->hasNoSignedWrap();
7756 if ((ICmpInst::isUnsigned(predicate: Pred) && I0NUW && I1NUW) ||
7757 (ICmpInst::isSigned(predicate: Pred) && I0NSW && I1NSW) ||
7758 (ICmpInst::isEquality(P: Pred) &&
7759 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
7760 return new ICmpInst(CmpPredicate::getSwapped(P: CmpPred), B,
7761 ConstantInt::get(Ty: Op0->getType(), V: 0));
7762 }
7763 }
7764 }
7765
7766 // Try to optimize equality comparisons against alloca-based pointers.
7767 if (Op0->getType()->isPointerTy() && I.isEquality()) {
7768 assert(Op1->getType()->isPointerTy() &&
7769 "Comparing pointer with non-pointer?");
7770 if (auto *Alloca = dyn_cast<AllocaInst>(Val: getUnderlyingObject(V: Op0)))
7771 if (foldAllocaCmp(Alloca))
7772 return nullptr;
7773 if (auto *Alloca = dyn_cast<AllocaInst>(Val: getUnderlyingObject(V: Op1)))
7774 if (foldAllocaCmp(Alloca))
7775 return nullptr;
7776 }
7777
7778 if (Instruction *Res = foldICmpBitCast(Cmp&: I))
7779 return Res;
7780
7781 // TODO: Hoist this above the min/max bailout.
7782 if (Instruction *R = foldICmpWithCastOp(ICmp&: I))
7783 return R;
7784
7785 {
7786 Value *X, *Y;
7787 // Transform (X & ~Y) == 0 --> (X & Y) != 0
7788 // and (X & ~Y) != 0 --> (X & Y) == 0
7789 // if A is a power of 2.
7790 if (match(V: Op0, P: m_And(L: m_Value(V&: X), R: m_Not(V: m_Value(V&: Y)))) &&
7791 match(V: Op1, P: m_Zero()) && isKnownToBeAPowerOfTwo(V: X, OrZero: false, CxtI: &I) &&
7792 I.isEquality())
7793 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(LHS: X, RHS: Y),
7794 Op1);
7795
7796 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
7797 if (Op0->getType()->isIntOrIntVectorTy()) {
7798 bool ConsumesOp0, ConsumesOp1;
7799 if (isFreeToInvert(V: Op0, WillInvertAllUses: Op0->hasOneUse(), DoesConsume&: ConsumesOp0) &&
7800 isFreeToInvert(V: Op1, WillInvertAllUses: Op1->hasOneUse(), DoesConsume&: ConsumesOp1) &&
7801 (ConsumesOp0 || ConsumesOp1)) {
7802 Value *InvOp0 = getFreelyInverted(V: Op0, WillInvertAllUses: Op0->hasOneUse(), Builder: &Builder);
7803 Value *InvOp1 = getFreelyInverted(V: Op1, WillInvertAllUses: Op1->hasOneUse(), Builder: &Builder);
7804 assert(InvOp0 && InvOp1 &&
7805 "Mismatch between isFreeToInvert and getFreelyInverted");
7806 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
7807 }
7808 }
7809
7810 Instruction *AddI = nullptr;
7811 if (match(V: &I, P: m_UAddWithOverflow(L: m_Value(V&: X), R: m_Value(V&: Y),
7812 S: m_Instruction(I&: AddI))) &&
7813 isa<IntegerType>(Val: X->getType())) {
7814 Value *Result;
7815 Constant *Overflow;
7816 // m_UAddWithOverflow can match patterns that do not include an explicit
7817 // "add" instruction, so check the opcode of the matched op.
7818 if (AddI->getOpcode() == Instruction::Add &&
7819 OptimizeOverflowCheck(BinaryOp: Instruction::Add, /*Signed*/ IsSigned: false, LHS: X, RHS: Y, OrigI&: *AddI,
7820 Result, Overflow)) {
7821 replaceInstUsesWith(I&: *AddI, V: Result);
7822 eraseInstFromFunction(I&: *AddI);
7823 return replaceInstUsesWith(I, V: Overflow);
7824 }
7825 }
7826
7827 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
7828 if (match(V: Op0, P: m_NUWMul(L: m_ZExt(Op: m_Value(V&: X)), R: m_ZExt(Op: m_Value(V&: Y)))) &&
7829 match(V: Op1, P: m_APInt(Res&: C))) {
7830 if (Instruction *R = processUMulZExtIdiom(I, MulVal: Op0, OtherVal: C, IC&: *this))
7831 return R;
7832 }
7833
7834 // Signbit test folds
7835 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
7836 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
7837 Instruction *ExtI;
7838 if ((I.isUnsigned() || I.isEquality()) &&
7839 match(V: Op1,
7840 P: m_CombineAnd(L: m_Instruction(I&: ExtI), R: m_ZExtOrSExt(Op: m_Value(V&: Y)))) &&
7841 Y->getType()->getScalarSizeInBits() == 1 &&
7842 (Op0->hasOneUse() || Op1->hasOneUse())) {
7843 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
7844 Instruction *ShiftI;
7845 if (match(V: Op0, P: m_CombineAnd(L: m_Instruction(I&: ShiftI),
7846 R: m_Shr(L: m_Value(V&: X), R: m_SpecificIntAllowPoison(
7847 V: OpWidth - 1))))) {
7848 unsigned ExtOpc = ExtI->getOpcode();
7849 unsigned ShiftOpc = ShiftI->getOpcode();
7850 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
7851 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
7852 Value *SLTZero =
7853 Builder.CreateICmpSLT(LHS: X, RHS: Constant::getNullValue(Ty: X->getType()));
7854 Value *Cmp = Builder.CreateICmp(P: Pred, LHS: SLTZero, RHS: Y, Name: I.getName());
7855 return replaceInstUsesWith(I, V: Cmp);
7856 }
7857 }
7858 }
7859 }
7860
7861 if (Instruction *Res = foldICmpEquality(I))
7862 return Res;
7863
7864 if (Instruction *Res = foldICmpPow2Test(I, Builder))
7865 return Res;
7866
7867 if (Instruction *Res = foldICmpOfUAddOv(I))
7868 return Res;
7869
7870 // The 'cmpxchg' instruction returns an aggregate containing the old value and
7871 // an i1 which indicates whether or not we successfully did the swap.
7872 //
7873 // Replace comparisons between the old value and the expected value with the
7874 // indicator that 'cmpxchg' returns.
7875 //
7876 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
7877 // spuriously fail. In those cases, the old value may equal the expected
7878 // value but it is possible for the swap to not occur.
7879 if (I.getPredicate() == ICmpInst::ICMP_EQ)
7880 if (auto *EVI = dyn_cast<ExtractValueInst>(Val: Op0))
7881 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(Val: EVI->getAggregateOperand()))
7882 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
7883 !ACXI->isWeak())
7884 return ExtractValueInst::Create(Agg: ACXI, Idxs: 1);
7885
7886 if (Instruction *Res = foldICmpWithHighBitMask(Cmp&: I, Builder))
7887 return Res;
7888
7889 if (I.getType()->isVectorTy())
7890 if (Instruction *Res = foldVectorCmp(Cmp&: I, Builder))
7891 return Res;
7892
7893 if (Instruction *Res = foldICmpInvariantGroup(I))
7894 return Res;
7895
7896 if (Instruction *Res = foldReductionIdiom(I, Builder, DL))
7897 return Res;
7898
7899 {
7900 Value *A;
7901 const APInt *C1, *C2;
7902 ICmpInst::Predicate Pred = I.getPredicate();
7903 if (ICmpInst::isEquality(P: Pred)) {
7904 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
7905 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
7906 if (match(V: Op0, P: m_And(L: m_SExt(Op: m_Value(V&: A)), R: m_APInt(Res&: C1))) &&
7907 match(V: Op1, P: m_APInt(Res&: C2))) {
7908 Type *InputTy = A->getType();
7909 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
7910 // c2 must be non-negative at the bitwidth of a.
7911 if (C2->getActiveBits() < InputBitWidth) {
7912 APInt TruncC1 = C1->trunc(width: InputBitWidth);
7913 // Check if there are 1s in C1 high bits of size InputBitWidth.
7914 if (C1->uge(RHS: APInt::getOneBitSet(numBits: C1->getBitWidth(), BitNo: InputBitWidth)))
7915 TruncC1.setBit(InputBitWidth - 1);
7916 Value *AndInst = Builder.CreateAnd(LHS: A, RHS: TruncC1);
7917 return new ICmpInst(
7918 Pred, AndInst,
7919 ConstantInt::get(Ty: InputTy, V: C2->trunc(width: InputBitWidth)));
7920 }
7921 }
7922 }
7923 }
7924
7925 return Changed ? &I : nullptr;
7926}
7927
7928/// Fold fcmp ([us]itofp x, cst) if possible.
7929Instruction *InstCombinerImpl::foldFCmpIntToFPConst(FCmpInst &I,
7930 Instruction *LHSI,
7931 Constant *RHSC) {
7932 const APFloat *RHS;
7933 if (!match(V: RHSC, P: m_APFloat(Res&: RHS)))
7934 return nullptr;
7935
7936 // Get the width of the mantissa. We don't want to hack on conversions that
7937 // might lose information from the integer, e.g. "i64 -> float"
7938 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
7939 if (MantissaWidth == -1)
7940 return nullptr; // Unknown.
7941
7942 Type *IntTy = LHSI->getOperand(i: 0)->getType();
7943 unsigned IntWidth = IntTy->getScalarSizeInBits();
7944 bool LHSUnsigned = isa<UIToFPInst>(Val: LHSI);
7945
7946 if (I.isEquality()) {
7947 FCmpInst::Predicate P = I.getPredicate();
7948 bool IsExact = false;
7949 APSInt RHSCvt(IntWidth, LHSUnsigned);
7950 RHS->convertToInteger(Result&: RHSCvt, RM: APFloat::rmNearestTiesToEven, IsExact: &IsExact);
7951
7952 // If the floating point constant isn't an integer value, we know if we will
7953 // ever compare equal / not equal to it.
7954 if (!IsExact) {
7955 // TODO: Can never be -0.0 and other non-representable values
7956 APFloat RHSRoundInt(*RHS);
7957 RHSRoundInt.roundToIntegral(RM: APFloat::rmNearestTiesToEven);
7958 if (*RHS != RHSRoundInt) {
7959 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
7960 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
7961
7962 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
7963 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
7964 }
7965 }
7966
7967 // TODO: If the constant is exactly representable, is it always OK to do
7968 // equality compares as integer?
7969 }
7970
7971 // Check to see that the input is converted from an integer type that is small
7972 // enough that preserves all bits. TODO: check here for "known" sign bits.
7973 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
7974
7975 // Following test does NOT adjust IntWidth downwards for signed inputs,
7976 // because the most negative value still requires all the mantissa bits
7977 // to distinguish it from one less than that value.
7978 if ((int)IntWidth > MantissaWidth) {
7979 // Conversion would lose accuracy. Check if loss can impact comparison.
7980 int Exp = ilogb(Arg: *RHS);
7981 if (Exp == APFloat::IEK_Inf) {
7982 int MaxExponent = ilogb(Arg: APFloat::getLargest(Sem: RHS->getSemantics()));
7983 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
7984 // Conversion could create infinity.
7985 return nullptr;
7986 } else {
7987 // Note that if RHS is zero or NaN, then Exp is negative
7988 // and first condition is trivially false.
7989 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
7990 // Conversion could affect comparison.
7991 return nullptr;
7992 }
7993 }
7994
7995 // Otherwise, we can potentially simplify the comparison. We know that it
7996 // will always come through as an integer value and we know the constant is
7997 // not a NAN (it would have been previously simplified).
7998 assert(!RHS->isNaN() && "NaN comparison not already folded!");
7999
8000 ICmpInst::Predicate Pred;
8001 switch (I.getPredicate()) {
8002 default:
8003 llvm_unreachable("Unexpected predicate!");
8004 case FCmpInst::FCMP_UEQ:
8005 case FCmpInst::FCMP_OEQ:
8006 Pred = ICmpInst::ICMP_EQ;
8007 break;
8008 case FCmpInst::FCMP_UGT:
8009 case FCmpInst::FCMP_OGT:
8010 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
8011 break;
8012 case FCmpInst::FCMP_UGE:
8013 case FCmpInst::FCMP_OGE:
8014 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
8015 break;
8016 case FCmpInst::FCMP_ULT:
8017 case FCmpInst::FCMP_OLT:
8018 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
8019 break;
8020 case FCmpInst::FCMP_ULE:
8021 case FCmpInst::FCMP_OLE:
8022 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
8023 break;
8024 case FCmpInst::FCMP_UNE:
8025 case FCmpInst::FCMP_ONE:
8026 Pred = ICmpInst::ICMP_NE;
8027 break;
8028 case FCmpInst::FCMP_ORD:
8029 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8030 case FCmpInst::FCMP_UNO:
8031 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8032 }
8033
8034 // Now we know that the APFloat is a normal number, zero or inf.
8035
8036 // See if the FP constant is too large for the integer. For example,
8037 // comparing an i8 to 300.0.
8038 if (!LHSUnsigned) {
8039 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
8040 // and large values.
8041 APFloat SMax(RHS->getSemantics());
8042 SMax.convertFromAPInt(Input: APInt::getSignedMaxValue(numBits: IntWidth), IsSigned: true,
8043 RM: APFloat::rmNearestTiesToEven);
8044 if (SMax < *RHS) { // smax < 13123.0
8045 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
8046 Pred == ICmpInst::ICMP_SLE)
8047 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8048 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8049 }
8050 } else {
8051 // If the RHS value is > UnsignedMax, fold the comparison. This handles
8052 // +INF and large values.
8053 APFloat UMax(RHS->getSemantics());
8054 UMax.convertFromAPInt(Input: APInt::getMaxValue(numBits: IntWidth), IsSigned: false,
8055 RM: APFloat::rmNearestTiesToEven);
8056 if (UMax < *RHS) { // umax < 13123.0
8057 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
8058 Pred == ICmpInst::ICMP_ULE)
8059 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8060 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8061 }
8062 }
8063
8064 if (!LHSUnsigned) {
8065 // See if the RHS value is < SignedMin.
8066 APFloat SMin(RHS->getSemantics());
8067 SMin.convertFromAPInt(Input: APInt::getSignedMinValue(numBits: IntWidth), IsSigned: true,
8068 RM: APFloat::rmNearestTiesToEven);
8069 if (SMin > *RHS) { // smin > 12312.0
8070 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
8071 Pred == ICmpInst::ICMP_SGE)
8072 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8073 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8074 }
8075 } else {
8076 // See if the RHS value is < UnsignedMin.
8077 APFloat UMin(RHS->getSemantics());
8078 UMin.convertFromAPInt(Input: APInt::getMinValue(numBits: IntWidth), IsSigned: false,
8079 RM: APFloat::rmNearestTiesToEven);
8080 if (UMin > *RHS) { // umin > 12312.0
8081 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
8082 Pred == ICmpInst::ICMP_UGE)
8083 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8084 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8085 }
8086 }
8087
8088 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
8089 // [0, UMAX], but it may still be fractional. Check whether this is the case
8090 // using the IsExact flag.
8091 // Don't do this for zero, because -0.0 is not fractional.
8092 APSInt RHSInt(IntWidth, LHSUnsigned);
8093 bool IsExact;
8094 RHS->convertToInteger(Result&: RHSInt, RM: APFloat::rmTowardZero, IsExact: &IsExact);
8095 if (!RHS->isZero()) {
8096 if (!IsExact) {
8097 // If we had a comparison against a fractional value, we have to adjust
8098 // the compare predicate and sometimes the value. RHSC is rounded towards
8099 // zero at this point.
8100 switch (Pred) {
8101 default:
8102 llvm_unreachable("Unexpected integer comparison!");
8103 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
8104 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8105 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
8106 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8107 case ICmpInst::ICMP_ULE:
8108 // (float)int <= 4.4 --> int <= 4
8109 // (float)int <= -4.4 --> false
8110 if (RHS->isNegative())
8111 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8112 break;
8113 case ICmpInst::ICMP_SLE:
8114 // (float)int <= 4.4 --> int <= 4
8115 // (float)int <= -4.4 --> int < -4
8116 if (RHS->isNegative())
8117 Pred = ICmpInst::ICMP_SLT;
8118 break;
8119 case ICmpInst::ICMP_ULT:
8120 // (float)int < -4.4 --> false
8121 // (float)int < 4.4 --> int <= 4
8122 if (RHS->isNegative())
8123 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8124 Pred = ICmpInst::ICMP_ULE;
8125 break;
8126 case ICmpInst::ICMP_SLT:
8127 // (float)int < -4.4 --> int < -4
8128 // (float)int < 4.4 --> int <= 4
8129 if (!RHS->isNegative())
8130 Pred = ICmpInst::ICMP_SLE;
8131 break;
8132 case ICmpInst::ICMP_UGT:
8133 // (float)int > 4.4 --> int > 4
8134 // (float)int > -4.4 --> true
8135 if (RHS->isNegative())
8136 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8137 break;
8138 case ICmpInst::ICMP_SGT:
8139 // (float)int > 4.4 --> int > 4
8140 // (float)int > -4.4 --> int >= -4
8141 if (RHS->isNegative())
8142 Pred = ICmpInst::ICMP_SGE;
8143 break;
8144 case ICmpInst::ICMP_UGE:
8145 // (float)int >= -4.4 --> true
8146 // (float)int >= 4.4 --> int > 4
8147 if (RHS->isNegative())
8148 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8149 Pred = ICmpInst::ICMP_UGT;
8150 break;
8151 case ICmpInst::ICMP_SGE:
8152 // (float)int >= -4.4 --> int >= -4
8153 // (float)int >= 4.4 --> int > 4
8154 if (!RHS->isNegative())
8155 Pred = ICmpInst::ICMP_SGT;
8156 break;
8157 }
8158 }
8159 }
8160
8161 // Lower this FP comparison into an appropriate integer version of the
8162 // comparison.
8163 return new ICmpInst(Pred, LHSI->getOperand(i: 0),
8164 ConstantInt::get(Ty: LHSI->getOperand(i: 0)->getType(), V: RHSInt));
8165}
8166
8167/// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
8168static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI,
8169 Constant *RHSC) {
8170 // When C is not 0.0 and infinities are not allowed:
8171 // (C / X) < 0.0 is a sign-bit test of X
8172 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
8173 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
8174 //
8175 // Proof:
8176 // Multiply (C / X) < 0.0 by X * X / C.
8177 // - X is non zero, if it is the flag 'ninf' is violated.
8178 // - C defines the sign of X * X * C. Thus it also defines whether to swap
8179 // the predicate. C is also non zero by definition.
8180 //
8181 // Thus X * X / C is non zero and the transformation is valid. [qed]
8182
8183 FCmpInst::Predicate Pred = I.getPredicate();
8184
8185 // Check that predicates are valid.
8186 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
8187 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
8188 return nullptr;
8189
8190 // Check that RHS operand is zero.
8191 if (!match(V: RHSC, P: m_AnyZeroFP()))
8192 return nullptr;
8193
8194 // Check fastmath flags ('ninf').
8195 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
8196 return nullptr;
8197
8198 // Check the properties of the dividend. It must not be zero to avoid a
8199 // division by zero (see Proof).
8200 const APFloat *C;
8201 if (!match(V: LHSI->getOperand(i: 0), P: m_APFloat(Res&: C)))
8202 return nullptr;
8203
8204 if (C->isZero())
8205 return nullptr;
8206
8207 // Get swapped predicate if necessary.
8208 if (C->isNegative())
8209 Pred = I.getSwappedPredicate();
8210
8211 return new FCmpInst(Pred, LHSI->getOperand(i: 1), RHSC, "", &I);
8212}
8213
8214/// Optimize fabs(X) compared with zero.
8215static Instruction *foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
8216 Value *X;
8217 if (!match(V: I.getOperand(i_nocapture: 0), P: m_FAbs(Op0: m_Value(V&: X))))
8218 return nullptr;
8219
8220 const APFloat *C;
8221 if (!match(V: I.getOperand(i_nocapture: 1), P: m_APFloat(Res&: C)))
8222 return nullptr;
8223
8224 if (!C->isPosZero()) {
8225 if (!C->isSmallestNormalized())
8226 return nullptr;
8227
8228 const Function *F = I.getFunction();
8229 DenormalMode Mode = F->getDenormalMode(FPType: C->getSemantics());
8230 if (Mode.Input == DenormalMode::PreserveSign ||
8231 Mode.Input == DenormalMode::PositiveZero) {
8232
8233 auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8234 Constant *Zero = ConstantFP::getZero(Ty: X->getType());
8235 return new FCmpInst(P, X, Zero, "", I);
8236 };
8237
8238 switch (I.getPredicate()) {
8239 case FCmpInst::FCMP_OLT:
8240 // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
8241 return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
8242 case FCmpInst::FCMP_UGE:
8243 // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
8244 return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
8245 case FCmpInst::FCMP_OGE:
8246 // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
8247 return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
8248 case FCmpInst::FCMP_ULT:
8249 // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
8250 return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
8251 default:
8252 break;
8253 }
8254 }
8255
8256 return nullptr;
8257 }
8258
8259 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8260 I->setPredicate(P);
8261 return IC.replaceOperand(I&: *I, OpNum: 0, V: X);
8262 };
8263
8264 switch (I.getPredicate()) {
8265 case FCmpInst::FCMP_UGE:
8266 case FCmpInst::FCMP_OLT:
8267 // fabs(X) >= 0.0 --> true
8268 // fabs(X) < 0.0 --> false
8269 llvm_unreachable("fcmp should have simplified");
8270
8271 case FCmpInst::FCMP_OGT:
8272 // fabs(X) > 0.0 --> X != 0.0
8273 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
8274
8275 case FCmpInst::FCMP_UGT:
8276 // fabs(X) u> 0.0 --> X u!= 0.0
8277 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
8278
8279 case FCmpInst::FCMP_OLE:
8280 // fabs(X) <= 0.0 --> X == 0.0
8281 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
8282
8283 case FCmpInst::FCMP_ULE:
8284 // fabs(X) u<= 0.0 --> X u== 0.0
8285 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
8286
8287 case FCmpInst::FCMP_OGE:
8288 // fabs(X) >= 0.0 --> !isnan(X)
8289 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8290 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
8291
8292 case FCmpInst::FCMP_ULT:
8293 // fabs(X) u< 0.0 --> isnan(X)
8294 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8295 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
8296
8297 case FCmpInst::FCMP_OEQ:
8298 case FCmpInst::FCMP_UEQ:
8299 case FCmpInst::FCMP_ONE:
8300 case FCmpInst::FCMP_UNE:
8301 case FCmpInst::FCMP_ORD:
8302 case FCmpInst::FCMP_UNO:
8303 // Look through the fabs() because it doesn't change anything but the sign.
8304 // fabs(X) == 0.0 --> X == 0.0,
8305 // fabs(X) != 0.0 --> X != 0.0
8306 // isnan(fabs(X)) --> isnan(X)
8307 // !isnan(fabs(X) --> !isnan(X)
8308 return replacePredAndOp0(&I, I.getPredicate(), X);
8309
8310 default:
8311 return nullptr;
8312 }
8313}
8314
8315/// Optimize sqrt(X) compared with zero.
8316static Instruction *foldSqrtWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
8317 Value *X;
8318 if (!match(V: I.getOperand(i_nocapture: 0), P: m_Sqrt(Op0: m_Value(V&: X))))
8319 return nullptr;
8320
8321 if (!match(V: I.getOperand(i_nocapture: 1), P: m_PosZeroFP()))
8322 return nullptr;
8323
8324 auto ReplacePredAndOp0 = [&](FCmpInst::Predicate P) {
8325 I.setPredicate(P);
8326 return IC.replaceOperand(I, OpNum: 0, V: X);
8327 };
8328
8329 // Clear ninf flag if sqrt doesn't have it.
8330 if (!cast<Instruction>(Val: I.getOperand(i_nocapture: 0))->hasNoInfs())
8331 I.setHasNoInfs(false);
8332
8333 switch (I.getPredicate()) {
8334 case FCmpInst::FCMP_OLT:
8335 case FCmpInst::FCMP_UGE:
8336 // sqrt(X) < 0.0 --> false
8337 // sqrt(X) u>= 0.0 --> true
8338 llvm_unreachable("fcmp should have simplified");
8339 case FCmpInst::FCMP_ULT:
8340 case FCmpInst::FCMP_ULE:
8341 case FCmpInst::FCMP_OGT:
8342 case FCmpInst::FCMP_OGE:
8343 case FCmpInst::FCMP_OEQ:
8344 case FCmpInst::FCMP_UNE:
8345 // sqrt(X) u< 0.0 --> X u< 0.0
8346 // sqrt(X) u<= 0.0 --> X u<= 0.0
8347 // sqrt(X) > 0.0 --> X > 0.0
8348 // sqrt(X) >= 0.0 --> X >= 0.0
8349 // sqrt(X) == 0.0 --> X == 0.0
8350 // sqrt(X) u!= 0.0 --> X u!= 0.0
8351 return IC.replaceOperand(I, OpNum: 0, V: X);
8352
8353 case FCmpInst::FCMP_OLE:
8354 // sqrt(X) <= 0.0 --> X == 0.0
8355 return ReplacePredAndOp0(FCmpInst::FCMP_OEQ);
8356 case FCmpInst::FCMP_UGT:
8357 // sqrt(X) u> 0.0 --> X u!= 0.0
8358 return ReplacePredAndOp0(FCmpInst::FCMP_UNE);
8359 case FCmpInst::FCMP_UEQ:
8360 // sqrt(X) u== 0.0 --> X u<= 0.0
8361 return ReplacePredAndOp0(FCmpInst::FCMP_ULE);
8362 case FCmpInst::FCMP_ONE:
8363 // sqrt(X) != 0.0 --> X > 0.0
8364 return ReplacePredAndOp0(FCmpInst::FCMP_OGT);
8365 case FCmpInst::FCMP_ORD:
8366 // !isnan(sqrt(X)) --> X >= 0.0
8367 return ReplacePredAndOp0(FCmpInst::FCMP_OGE);
8368 case FCmpInst::FCMP_UNO:
8369 // isnan(sqrt(X)) --> X u< 0.0
8370 return ReplacePredAndOp0(FCmpInst::FCMP_ULT);
8371 default:
8372 llvm_unreachable("Unexpected predicate!");
8373 }
8374}
8375
8376static Instruction *foldFCmpFNegCommonOp(FCmpInst &I) {
8377 CmpInst::Predicate Pred = I.getPredicate();
8378 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
8379
8380 // Canonicalize fneg as Op1.
8381 if (match(V: Op0, P: m_FNeg(X: m_Value())) && !match(V: Op1, P: m_FNeg(X: m_Value()))) {
8382 std::swap(a&: Op0, b&: Op1);
8383 Pred = I.getSwappedPredicate();
8384 }
8385
8386 if (!match(V: Op1, P: m_FNeg(X: m_Specific(V: Op0))))
8387 return nullptr;
8388
8389 // Replace the negated operand with 0.0:
8390 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
8391 Constant *Zero = ConstantFP::getZero(Ty: Op0->getType());
8392 return new FCmpInst(Pred, Op0, Zero, "", &I);
8393}
8394
8395static Instruction *foldFCmpFSubIntoFCmp(FCmpInst &I, Instruction *LHSI,
8396 Constant *RHSC, InstCombinerImpl &CI) {
8397 const CmpInst::Predicate Pred = I.getPredicate();
8398 Value *X = LHSI->getOperand(i: 0);
8399 Value *Y = LHSI->getOperand(i: 1);
8400 switch (Pred) {
8401 default:
8402 break;
8403 case FCmpInst::FCMP_UGT:
8404 case FCmpInst::FCMP_ULT:
8405 case FCmpInst::FCMP_UNE:
8406 case FCmpInst::FCMP_OEQ:
8407 case FCmpInst::FCMP_OGE:
8408 case FCmpInst::FCMP_OLE:
8409 // The optimization is not valid if X and Y are infinities of the same
8410 // sign, i.e. the inf - inf = nan case. If the fsub has the ninf or nnan
8411 // flag then we can assume we do not have that case. Otherwise we might be
8412 // able to prove that either X or Y is not infinity.
8413 if (!LHSI->hasNoNaNs() && !LHSI->hasNoInfs() &&
8414 !isKnownNeverInfinity(V: Y,
8415 SQ: CI.getSimplifyQuery().getWithInstruction(I: &I)) &&
8416 !isKnownNeverInfinity(V: X, SQ: CI.getSimplifyQuery().getWithInstruction(I: &I)))
8417 break;
8418
8419 [[fallthrough]];
8420 case FCmpInst::FCMP_OGT:
8421 case FCmpInst::FCMP_OLT:
8422 case FCmpInst::FCMP_ONE:
8423 case FCmpInst::FCMP_UEQ:
8424 case FCmpInst::FCMP_UGE:
8425 case FCmpInst::FCMP_ULE:
8426 // fcmp pred (x - y), 0 --> fcmp pred x, y
8427 if (match(V: RHSC, P: m_AnyZeroFP()) &&
8428 I.getFunction()->getDenormalMode(
8429 FPType: LHSI->getType()->getScalarType()->getFltSemantics()) ==
8430 DenormalMode::getIEEE()) {
8431 CI.replaceOperand(I, OpNum: 0, V: X);
8432 CI.replaceOperand(I, OpNum: 1, V: Y);
8433 return &I;
8434 }
8435 break;
8436 }
8437
8438 return nullptr;
8439}
8440
8441static Instruction *foldFCmpWithFloorAndCeil(FCmpInst &I,
8442 InstCombinerImpl &IC) {
8443 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
8444 Type *OpType = LHS->getType();
8445 CmpInst::Predicate Pred = I.getPredicate();
8446
8447 bool FloorX = match(V: LHS, P: m_Intrinsic<Intrinsic::floor>(Op0: m_Specific(V: RHS)));
8448 bool CeilX = match(V: LHS, P: m_Intrinsic<Intrinsic::ceil>(Op0: m_Specific(V: RHS)));
8449
8450 if (!FloorX && !CeilX) {
8451 if ((FloorX = match(V: RHS, P: m_Intrinsic<Intrinsic::floor>(Op0: m_Specific(V: LHS)))) ||
8452 (CeilX = match(V: RHS, P: m_Intrinsic<Intrinsic::ceil>(Op0: m_Specific(V: LHS))))) {
8453 std::swap(a&: LHS, b&: RHS);
8454 Pred = I.getSwappedPredicate();
8455 }
8456 }
8457
8458 switch (Pred) {
8459 case FCmpInst::FCMP_OLE:
8460 // fcmp ole floor(x), x => fcmp ord x, 0
8461 if (FloorX)
8462 return new FCmpInst(FCmpInst::FCMP_ORD, RHS, ConstantFP::getZero(Ty: OpType),
8463 "", &I);
8464 break;
8465 case FCmpInst::FCMP_OGT:
8466 // fcmp ogt floor(x), x => false
8467 if (FloorX)
8468 return IC.replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8469 break;
8470 case FCmpInst::FCMP_OGE:
8471 // fcmp oge ceil(x), x => fcmp ord x, 0
8472 if (CeilX)
8473 return new FCmpInst(FCmpInst::FCMP_ORD, RHS, ConstantFP::getZero(Ty: OpType),
8474 "", &I);
8475 break;
8476 case FCmpInst::FCMP_OLT:
8477 // fcmp olt ceil(x), x => false
8478 if (CeilX)
8479 return IC.replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8480 break;
8481 case FCmpInst::FCMP_ULE:
8482 // fcmp ule floor(x), x => true
8483 if (FloorX)
8484 return IC.replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8485 break;
8486 case FCmpInst::FCMP_UGT:
8487 // fcmp ugt floor(x), x => fcmp uno x, 0
8488 if (FloorX)
8489 return new FCmpInst(FCmpInst::FCMP_UNO, RHS, ConstantFP::getZero(Ty: OpType),
8490 "", &I);
8491 break;
8492 case FCmpInst::FCMP_UGE:
8493 // fcmp uge ceil(x), x => true
8494 if (CeilX)
8495 return IC.replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8496 break;
8497 case FCmpInst::FCMP_ULT:
8498 // fcmp ult ceil(x), x => fcmp uno x, 0
8499 if (CeilX)
8500 return new FCmpInst(FCmpInst::FCMP_UNO, RHS, ConstantFP::getZero(Ty: OpType),
8501 "", &I);
8502 break;
8503 default:
8504 break;
8505 }
8506
8507 return nullptr;
8508}
8509
8510Instruction *InstCombinerImpl::visitFCmpInst(FCmpInst &I) {
8511 bool Changed = false;
8512
8513 /// Orders the operands of the compare so that they are listed from most
8514 /// complex to least complex. This puts constants before unary operators,
8515 /// before binary operators.
8516 if (getComplexity(V: I.getOperand(i_nocapture: 0)) < getComplexity(V: I.getOperand(i_nocapture: 1))) {
8517 I.swapOperands();
8518 Changed = true;
8519 }
8520
8521 const CmpInst::Predicate Pred = I.getPredicate();
8522 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
8523 if (Value *V = simplifyFCmpInst(Predicate: Pred, LHS: Op0, RHS: Op1, FMF: I.getFastMathFlags(),
8524 Q: SQ.getWithInstruction(I: &I)))
8525 return replaceInstUsesWith(I, V);
8526
8527 // Simplify 'fcmp pred X, X'
8528 Type *OpType = Op0->getType();
8529 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
8530 if (Op0 == Op1) {
8531 switch (Pred) {
8532 default:
8533 break;
8534 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
8535 case FCmpInst::FCMP_ULT: // True if unordered or less than
8536 case FCmpInst::FCMP_UGT: // True if unordered or greater than
8537 case FCmpInst::FCMP_UNE: // True if unordered or not equal
8538 // Canonicalize these to be 'fcmp uno %X, 0.0'.
8539 I.setPredicate(FCmpInst::FCMP_UNO);
8540 I.setOperand(i_nocapture: 1, Val_nocapture: Constant::getNullValue(Ty: OpType));
8541 return &I;
8542
8543 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
8544 case FCmpInst::FCMP_OEQ: // True if ordered and equal
8545 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
8546 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
8547 // Canonicalize these to be 'fcmp ord %X, 0.0'.
8548 I.setPredicate(FCmpInst::FCMP_ORD);
8549 I.setOperand(i_nocapture: 1, Val_nocapture: Constant::getNullValue(Ty: OpType));
8550 return &I;
8551 }
8552 }
8553
8554 if (I.isCommutative()) {
8555 if (auto Pair = matchSymmetricPair(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1))) {
8556 replaceOperand(I, OpNum: 0, V: Pair->first);
8557 replaceOperand(I, OpNum: 1, V: Pair->second);
8558 return &I;
8559 }
8560 }
8561
8562 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
8563 // then canonicalize the operand to 0.0.
8564 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
8565 if (!match(V: Op0, P: m_PosZeroFP()) &&
8566 isKnownNeverNaN(V: Op0, SQ: getSimplifyQuery().getWithInstruction(I: &I)))
8567 return replaceOperand(I, OpNum: 0, V: ConstantFP::getZero(Ty: OpType));
8568
8569 if (!match(V: Op1, P: m_PosZeroFP()) &&
8570 isKnownNeverNaN(V: Op1, SQ: getSimplifyQuery().getWithInstruction(I: &I)))
8571 return replaceOperand(I, OpNum: 1, V: ConstantFP::getZero(Ty: OpType));
8572 }
8573
8574 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
8575 Value *X, *Y;
8576 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: X))) && match(V: Op1, P: m_FNeg(X: m_Value(V&: Y))))
8577 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
8578
8579 if (Instruction *R = foldFCmpFNegCommonOp(I))
8580 return R;
8581
8582 // Test if the FCmpInst instruction is used exclusively by a select as
8583 // part of a minimum or maximum operation. If so, refrain from doing
8584 // any other folding. This helps out other analyses which understand
8585 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
8586 // and CodeGen. And in this case, at least one of the comparison
8587 // operands has at least one user besides the compare (the select),
8588 // which would often largely negate the benefit of folding anyway.
8589 if (I.hasOneUse())
8590 if (SelectInst *SI = dyn_cast<SelectInst>(Val: I.user_back())) {
8591 Value *A, *B;
8592 SelectPatternResult SPR = matchSelectPattern(V: SI, LHS&: A, RHS&: B);
8593 if (SPR.Flavor != SPF_UNKNOWN)
8594 return nullptr;
8595 }
8596
8597 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
8598 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
8599 if (match(V: Op1, P: m_AnyZeroFP()) && !match(V: Op1, P: m_PosZeroFP()))
8600 return replaceOperand(I, OpNum: 1, V: ConstantFP::getZero(Ty: OpType));
8601
8602 // Canonicalize:
8603 // fcmp olt X, +inf -> fcmp one X, +inf
8604 // fcmp ole X, +inf -> fcmp ord X, 0
8605 // fcmp ogt X, +inf -> false
8606 // fcmp oge X, +inf -> fcmp oeq X, +inf
8607 // fcmp ult X, +inf -> fcmp une X, +inf
8608 // fcmp ule X, +inf -> true
8609 // fcmp ugt X, +inf -> fcmp uno X, 0
8610 // fcmp uge X, +inf -> fcmp ueq X, +inf
8611 // fcmp olt X, -inf -> false
8612 // fcmp ole X, -inf -> fcmp oeq X, -inf
8613 // fcmp ogt X, -inf -> fcmp one X, -inf
8614 // fcmp oge X, -inf -> fcmp ord X, 0
8615 // fcmp ult X, -inf -> fcmp uno X, 0
8616 // fcmp ule X, -inf -> fcmp ueq X, -inf
8617 // fcmp ugt X, -inf -> fcmp une X, -inf
8618 // fcmp uge X, -inf -> true
8619 const APFloat *C;
8620 if (match(V: Op1, P: m_APFloat(Res&: C)) && C->isInfinity()) {
8621 switch (C->isNegative() ? FCmpInst::getSwappedPredicate(pred: Pred) : Pred) {
8622 default:
8623 break;
8624 case FCmpInst::FCMP_ORD:
8625 case FCmpInst::FCMP_UNO:
8626 case FCmpInst::FCMP_TRUE:
8627 case FCmpInst::FCMP_FALSE:
8628 case FCmpInst::FCMP_OGT:
8629 case FCmpInst::FCMP_ULE:
8630 llvm_unreachable("Should be simplified by InstSimplify");
8631 case FCmpInst::FCMP_OLT:
8632 return new FCmpInst(FCmpInst::FCMP_ONE, Op0, Op1, "", &I);
8633 case FCmpInst::FCMP_OLE:
8634 return new FCmpInst(FCmpInst::FCMP_ORD, Op0, ConstantFP::getZero(Ty: OpType),
8635 "", &I);
8636 case FCmpInst::FCMP_OGE:
8637 return new FCmpInst(FCmpInst::FCMP_OEQ, Op0, Op1, "", &I);
8638 case FCmpInst::FCMP_ULT:
8639 return new FCmpInst(FCmpInst::FCMP_UNE, Op0, Op1, "", &I);
8640 case FCmpInst::FCMP_UGT:
8641 return new FCmpInst(FCmpInst::FCMP_UNO, Op0, ConstantFP::getZero(Ty: OpType),
8642 "", &I);
8643 case FCmpInst::FCMP_UGE:
8644 return new FCmpInst(FCmpInst::FCMP_UEQ, Op0, Op1, "", &I);
8645 }
8646 }
8647
8648 // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
8649 // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
8650 if (match(V: Op1, P: m_PosZeroFP()) &&
8651 match(V: Op0, P: m_OneUse(SubPattern: m_ElementWiseBitCast(Op: m_Value(V&: X))))) {
8652 ICmpInst::Predicate IntPred = ICmpInst::BAD_ICMP_PREDICATE;
8653 if (Pred == FCmpInst::FCMP_OEQ)
8654 IntPred = ICmpInst::ICMP_EQ;
8655 else if (Pred == FCmpInst::FCMP_UNE)
8656 IntPred = ICmpInst::ICMP_NE;
8657
8658 if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
8659 Type *IntTy = X->getType();
8660 const APInt &SignMask = ~APInt::getSignMask(BitWidth: IntTy->getScalarSizeInBits());
8661 Value *MaskX = Builder.CreateAnd(LHS: X, RHS: ConstantInt::get(Ty: IntTy, V: SignMask));
8662 return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(Ty: IntTy));
8663 }
8664 }
8665
8666 // Handle fcmp with instruction LHS and constant RHS.
8667 Instruction *LHSI;
8668 Constant *RHSC;
8669 if (match(V: Op0, P: m_Instruction(I&: LHSI)) && match(V: Op1, P: m_Constant(C&: RHSC))) {
8670 switch (LHSI->getOpcode()) {
8671 case Instruction::Select:
8672 // fcmp eq (cond ? x : -x), 0 --> fcmp eq x, 0
8673 if (FCmpInst::isEquality(Pred) && match(V: RHSC, P: m_AnyZeroFP()) &&
8674 match(V: LHSI, P: m_c_Select(L: m_FNeg(X: m_Value(V&: X)), R: m_Deferred(V: X))))
8675 return replaceOperand(I, OpNum: 0, V: X);
8676 if (Instruction *NV = FoldOpIntoSelect(Op&: I, SI: cast<SelectInst>(Val: LHSI)))
8677 return NV;
8678 break;
8679 case Instruction::FSub:
8680 if (LHSI->hasOneUse())
8681 if (Instruction *NV = foldFCmpFSubIntoFCmp(I, LHSI, RHSC, CI&: *this))
8682 return NV;
8683 break;
8684 case Instruction::PHI:
8685 if (Instruction *NV = foldOpIntoPhi(I, PN: cast<PHINode>(Val: LHSI)))
8686 return NV;
8687 break;
8688 case Instruction::SIToFP:
8689 case Instruction::UIToFP:
8690 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
8691 return NV;
8692 break;
8693 case Instruction::FDiv:
8694 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
8695 return NV;
8696 break;
8697 case Instruction::Load:
8698 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: LHSI->getOperand(i: 0)))
8699 if (auto *GV = dyn_cast<GlobalVariable>(Val: GEP->getOperand(i_nocapture: 0)))
8700 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(
8701 LI: cast<LoadInst>(Val: LHSI), GEP, GV, ICI&: I))
8702 return Res;
8703 break;
8704 }
8705 }
8706
8707 if (Instruction *R = foldFabsWithFcmpZero(I, IC&: *this))
8708 return R;
8709
8710 if (Instruction *R = foldSqrtWithFcmpZero(I, IC&: *this))
8711 return R;
8712
8713 if (Instruction *R = foldFCmpWithFloorAndCeil(I, IC&: *this))
8714 return R;
8715
8716 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: X)))) {
8717 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
8718 Constant *C;
8719 if (match(V: Op1, P: m_Constant(C)))
8720 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL))
8721 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
8722 }
8723
8724 // fcmp (fadd X, 0.0), Y --> fcmp X, Y
8725 if (match(V: Op0, P: m_FAdd(L: m_Value(V&: X), R: m_AnyZeroFP())))
8726 return new FCmpInst(Pred, X, Op1, "", &I);
8727
8728 // fcmp X, (fadd Y, 0.0) --> fcmp X, Y
8729 if (match(V: Op1, P: m_FAdd(L: m_Value(V&: Y), R: m_AnyZeroFP())))
8730 return new FCmpInst(Pred, Op0, Y, "", &I);
8731
8732 if (match(V: Op0, P: m_FPExt(Op: m_Value(V&: X)))) {
8733 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
8734 if (match(V: Op1, P: m_FPExt(Op: m_Value(V&: Y))) && X->getType() == Y->getType())
8735 return new FCmpInst(Pred, X, Y, "", &I);
8736
8737 const APFloat *C;
8738 if (match(V: Op1, P: m_APFloat(Res&: C))) {
8739 const fltSemantics &FPSem =
8740 X->getType()->getScalarType()->getFltSemantics();
8741 bool Lossy;
8742 APFloat TruncC = *C;
8743 TruncC.convert(ToSemantics: FPSem, RM: APFloat::rmNearestTiesToEven, losesInfo: &Lossy);
8744
8745 if (Lossy) {
8746 // X can't possibly equal the higher-precision constant, so reduce any
8747 // equality comparison.
8748 // TODO: Other predicates can be handled via getFCmpCode().
8749 switch (Pred) {
8750 case FCmpInst::FCMP_OEQ:
8751 // X is ordered and equal to an impossible constant --> false
8752 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8753 case FCmpInst::FCMP_ONE:
8754 // X is ordered and not equal to an impossible constant --> ordered
8755 return new FCmpInst(FCmpInst::FCMP_ORD, X,
8756 ConstantFP::getZero(Ty: X->getType()));
8757 case FCmpInst::FCMP_UEQ:
8758 // X is unordered or equal to an impossible constant --> unordered
8759 return new FCmpInst(FCmpInst::FCMP_UNO, X,
8760 ConstantFP::getZero(Ty: X->getType()));
8761 case FCmpInst::FCMP_UNE:
8762 // X is unordered or not equal to an impossible constant --> true
8763 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8764 default:
8765 break;
8766 }
8767 }
8768
8769 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
8770 // Avoid lossy conversions and denormals.
8771 // Zero is a special case that's OK to convert.
8772 APFloat Fabs = TruncC;
8773 Fabs.clearSign();
8774 if (!Lossy &&
8775 (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(Sem: FPSem)))) {
8776 Constant *NewC = ConstantFP::get(Ty: X->getType(), V: TruncC);
8777 return new FCmpInst(Pred, X, NewC, "", &I);
8778 }
8779 }
8780 }
8781
8782 // Convert a sign-bit test of an FP value into a cast and integer compare.
8783 // TODO: Simplify if the copysign constant is 0.0 or NaN.
8784 // TODO: Handle non-zero compare constants.
8785 // TODO: Handle other predicates.
8786 if (match(V: Op0, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::copysign>(Op0: m_APFloat(Res&: C),
8787 Op1: m_Value(V&: X)))) &&
8788 match(V: Op1, P: m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
8789 Type *IntType = Builder.getIntNTy(N: X->getType()->getScalarSizeInBits());
8790 if (auto *VecTy = dyn_cast<VectorType>(Val: OpType))
8791 IntType = VectorType::get(ElementType: IntType, EC: VecTy->getElementCount());
8792
8793 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
8794 if (Pred == FCmpInst::FCMP_OLT) {
8795 Value *IntX = Builder.CreateBitCast(V: X, DestTy: IntType);
8796 return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
8797 ConstantInt::getNullValue(Ty: IntType));
8798 }
8799 }
8800
8801 {
8802 Value *CanonLHS = nullptr, *CanonRHS = nullptr;
8803 match(V: Op0, P: m_Intrinsic<Intrinsic::canonicalize>(Op0: m_Value(V&: CanonLHS)));
8804 match(V: Op1, P: m_Intrinsic<Intrinsic::canonicalize>(Op0: m_Value(V&: CanonRHS)));
8805
8806 // (canonicalize(x) == x) => (x == x)
8807 if (CanonLHS == Op1)
8808 return new FCmpInst(Pred, Op1, Op1, "", &I);
8809
8810 // (x == canonicalize(x)) => (x == x)
8811 if (CanonRHS == Op0)
8812 return new FCmpInst(Pred, Op0, Op0, "", &I);
8813
8814 // (canonicalize(x) == canonicalize(y)) => (x == y)
8815 if (CanonLHS && CanonRHS)
8816 return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
8817 }
8818
8819 if (I.getType()->isVectorTy())
8820 if (Instruction *Res = foldVectorCmp(Cmp&: I, Builder))
8821 return Res;
8822
8823 return Changed ? &I : nullptr;
8824}
8825