LLVM 17.0.0git
InstCombineCompares.cpp
Go to the documentation of this file.
1//===- InstCombineCompares.cpp --------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visitICmp and visitFCmp functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/SetVector.h"
16#include "llvm/ADT/Statistic.h"
22#include "llvm/IR/DataLayout.h"
28
29using namespace llvm;
30using namespace PatternMatch;
31
32#define DEBUG_TYPE "instcombine"
33
34// How many times is a select replaced by one of its operands?
35STATISTIC(NumSel, "Number of select opts");
36
37
38/// Compute Result = In1+In2, returning true if the result overflowed for this
39/// type.
40static bool addWithOverflow(APInt &Result, const APInt &In1,
41 const APInt &In2, bool IsSigned = false) {
42 bool Overflow;
43 if (IsSigned)
44 Result = In1.sadd_ov(In2, Overflow);
45 else
46 Result = In1.uadd_ov(In2, Overflow);
47
48 return Overflow;
49}
50
51/// Compute Result = In1-In2, returning true if the result overflowed for this
52/// type.
53static bool subWithOverflow(APInt &Result, const APInt &In1,
54 const APInt &In2, bool IsSigned = false) {
55 bool Overflow;
56 if (IsSigned)
57 Result = In1.ssub_ov(In2, Overflow);
58 else
59 Result = In1.usub_ov(In2, Overflow);
60
61 return Overflow;
62}
63
64/// Given an icmp instruction, return true if any use of this comparison is a
65/// branch on sign bit comparison.
66static bool hasBranchUse(ICmpInst &I) {
67 for (auto *U : I.users())
68 if (isa<BranchInst>(U))
69 return true;
70 return false;
71}
72
73/// Returns true if the exploded icmp can be expressed as a signed comparison
74/// to zero and updates the predicate accordingly.
75/// The signedness of the comparison is preserved.
76/// TODO: Refactor with decomposeBitTestICmp()?
77static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
78 if (!ICmpInst::isSigned(Pred))
79 return false;
80
81 if (C.isZero())
82 return ICmpInst::isRelational(Pred);
83
84 if (C.isOne()) {
85 if (Pred == ICmpInst::ICMP_SLT) {
86 Pred = ICmpInst::ICMP_SLE;
87 return true;
88 }
89 } else if (C.isAllOnes()) {
90 if (Pred == ICmpInst::ICMP_SGT) {
91 Pred = ICmpInst::ICMP_SGE;
92 return true;
93 }
94 }
95
96 return false;
97}
98
99/// This is called when we see this pattern:
100/// cmp pred (load (gep GV, ...)), cmpcst
101/// where GV is a global variable with a constant initializer. Try to simplify
102/// this into some simple computation that does not need the load. For example
103/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
104///
105/// If AndCst is non-null, then the loaded value is masked with that constant
106/// before doing the comparison. This handles cases like "A[i]&4 == 0".
109 ConstantInt *AndCst) {
110 if (LI->isVolatile() || LI->getType() != GEP->getResultElementType() ||
111 GV->getValueType() != GEP->getSourceElementType() ||
112 !GV->isConstant() || !GV->hasDefinitiveInitializer())
113 return nullptr;
114
116 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
117 return nullptr;
118
119 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
120 // Don't blow up on huge arrays.
121 if (ArrayElementCount > MaxArraySizeForCombine)
122 return nullptr;
123
124 // There are many forms of this optimization we can handle, for now, just do
125 // the simple index into a single-dimensional array.
126 //
127 // Require: GEP GV, 0, i {{, constant indices}}
128 if (GEP->getNumOperands() < 3 ||
129 !isa<ConstantInt>(GEP->getOperand(1)) ||
130 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
131 isa<Constant>(GEP->getOperand(2)))
132 return nullptr;
133
134 // Check that indices after the variable are constants and in-range for the
135 // type they index. Collect the indices. This is typically for arrays of
136 // structs.
137 SmallVector<unsigned, 4> LaterIndices;
138
139 Type *EltTy = Init->getType()->getArrayElementType();
140 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
141 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
142 if (!Idx) return nullptr; // Variable index.
143
144 uint64_t IdxVal = Idx->getZExtValue();
145 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
146
147 if (StructType *STy = dyn_cast<StructType>(EltTy))
148 EltTy = STy->getElementType(IdxVal);
149 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
150 if (IdxVal >= ATy->getNumElements()) return nullptr;
151 EltTy = ATy->getElementType();
152 } else {
153 return nullptr; // Unknown type.
154 }
155
156 LaterIndices.push_back(IdxVal);
157 }
158
159 enum { Overdefined = -3, Undefined = -2 };
160
161 // Variables for our state machines.
162
163 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
164 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
165 // and 87 is the second (and last) index. FirstTrueElement is -2 when
166 // undefined, otherwise set to the first true element. SecondTrueElement is
167 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
168 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
169
170 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
171 // form "i != 47 & i != 87". Same state transitions as for true elements.
172 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
173
174 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
175 /// define a state machine that triggers for ranges of values that the index
176 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
177 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
178 /// index in the range (inclusive). We use -2 for undefined here because we
179 /// use relative comparisons and don't want 0-1 to match -1.
180 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
181
182 // MagicBitvector - This is a magic bitvector where we set a bit if the
183 // comparison is true for element 'i'. If there are 64 elements or less in
184 // the array, this will fully represent all the comparison results.
185 uint64_t MagicBitvector = 0;
186
187 // Scan the array and see if one of our patterns matches.
188 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
189 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
190 Constant *Elt = Init->getAggregateElement(i);
191 if (!Elt) return nullptr;
192
193 // If this is indexing an array of structures, get the structure element.
194 if (!LaterIndices.empty()) {
195 Elt = ConstantFoldExtractValueInstruction(Elt, LaterIndices);
196 if (!Elt)
197 return nullptr;
198 }
199
200 // If the element is masked, handle it.
201 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
202
203 // Find out if the comparison would be true or false for the i'th element.
205 CompareRHS, DL, &TLI);
206 // If the result is undef for this element, ignore it.
207 if (isa<UndefValue>(C)) {
208 // Extend range state machines to cover this element in case there is an
209 // undef in the middle of the range.
210 if (TrueRangeEnd == (int)i-1)
211 TrueRangeEnd = i;
212 if (FalseRangeEnd == (int)i-1)
213 FalseRangeEnd = i;
214 continue;
215 }
216
217 // If we can't compute the result for any of the elements, we have to give
218 // up evaluating the entire conditional.
219 if (!isa<ConstantInt>(C)) return nullptr;
220
221 // Otherwise, we know if the comparison is true or false for this element,
222 // update our state machines.
223 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
224
225 // State machine for single/double/range index comparison.
226 if (IsTrueForElt) {
227 // Update the TrueElement state machine.
228 if (FirstTrueElement == Undefined)
229 FirstTrueElement = TrueRangeEnd = i; // First true element.
230 else {
231 // Update double-compare state machine.
232 if (SecondTrueElement == Undefined)
233 SecondTrueElement = i;
234 else
235 SecondTrueElement = Overdefined;
236
237 // Update range state machine.
238 if (TrueRangeEnd == (int)i-1)
239 TrueRangeEnd = i;
240 else
241 TrueRangeEnd = Overdefined;
242 }
243 } else {
244 // Update the FalseElement state machine.
245 if (FirstFalseElement == Undefined)
246 FirstFalseElement = FalseRangeEnd = i; // First false element.
247 else {
248 // Update double-compare state machine.
249 if (SecondFalseElement == Undefined)
250 SecondFalseElement = i;
251 else
252 SecondFalseElement = Overdefined;
253
254 // Update range state machine.
255 if (FalseRangeEnd == (int)i-1)
256 FalseRangeEnd = i;
257 else
258 FalseRangeEnd = Overdefined;
259 }
260 }
261
262 // If this element is in range, update our magic bitvector.
263 if (i < 64 && IsTrueForElt)
264 MagicBitvector |= 1ULL << i;
265
266 // If all of our states become overdefined, bail out early. Since the
267 // predicate is expensive, only check it every 8 elements. This is only
268 // really useful for really huge arrays.
269 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
270 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
271 FalseRangeEnd == Overdefined)
272 return nullptr;
273 }
274
275 // Now that we've scanned the entire array, emit our new comparison(s). We
276 // order the state machines in complexity of the generated code.
277 Value *Idx = GEP->getOperand(2);
278
279 // If the index is larger than the pointer size of the target, truncate the
280 // index down like the GEP would do implicitly. We don't have to do this for
281 // an inbounds GEP because the index can't be out of range.
282 if (!GEP->isInBounds()) {
283 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
284 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
285 if (Idx->getType()->getPrimitiveSizeInBits().getFixedValue() > PtrSize)
286 Idx = Builder.CreateTrunc(Idx, IntPtrTy);
287 }
288
289 // If inbounds keyword is not present, Idx * ElementSize can overflow.
290 // Let's assume that ElementSize is 2 and the wanted value is at offset 0.
291 // Then, there are two possible values for Idx to match offset 0:
292 // 0x00..00, 0x80..00.
293 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
294 // comparison is false if Idx was 0x80..00.
295 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
296 unsigned ElementSize =
297 DL.getTypeAllocSize(Init->getType()->getArrayElementType());
298 auto MaskIdx = [&](Value *Idx) {
299 if (!GEP->isInBounds() && llvm::countr_zero(ElementSize) != 0) {
300 Value *Mask = ConstantInt::get(Idx->getType(), -1);
301 Mask = Builder.CreateLShr(Mask, llvm::countr_zero(ElementSize));
302 Idx = Builder.CreateAnd(Idx, Mask);
303 }
304 return Idx;
305 };
306
307 // If the comparison is only true for one or two elements, emit direct
308 // comparisons.
309 if (SecondTrueElement != Overdefined) {
310 Idx = MaskIdx(Idx);
311 // None true -> false.
312 if (FirstTrueElement == Undefined)
313 return replaceInstUsesWith(ICI, Builder.getFalse());
314
315 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
316
317 // True for one element -> 'i == 47'.
318 if (SecondTrueElement == Undefined)
319 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
320
321 // True for two elements -> 'i == 47 | i == 72'.
322 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
323 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
324 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
325 return BinaryOperator::CreateOr(C1, C2);
326 }
327
328 // If the comparison is only false for one or two elements, emit direct
329 // comparisons.
330 if (SecondFalseElement != Overdefined) {
331 Idx = MaskIdx(Idx);
332 // None false -> true.
333 if (FirstFalseElement == Undefined)
334 return replaceInstUsesWith(ICI, Builder.getTrue());
335
336 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
337
338 // False for one element -> 'i != 47'.
339 if (SecondFalseElement == Undefined)
340 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
341
342 // False for two elements -> 'i != 47 & i != 72'.
343 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
344 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
345 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
346 return BinaryOperator::CreateAnd(C1, C2);
347 }
348
349 // If the comparison can be replaced with a range comparison for the elements
350 // where it is true, emit the range check.
351 if (TrueRangeEnd != Overdefined) {
352 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
353 Idx = MaskIdx(Idx);
354
355 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
356 if (FirstTrueElement) {
357 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
358 Idx = Builder.CreateAdd(Idx, Offs);
359 }
360
361 Value *End = ConstantInt::get(Idx->getType(),
362 TrueRangeEnd-FirstTrueElement+1);
363 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
364 }
365
366 // False range check.
367 if (FalseRangeEnd != Overdefined) {
368 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
369 Idx = MaskIdx(Idx);
370 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
371 if (FirstFalseElement) {
372 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
373 Idx = Builder.CreateAdd(Idx, Offs);
374 }
375
376 Value *End = ConstantInt::get(Idx->getType(),
377 FalseRangeEnd-FirstFalseElement);
378 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
379 }
380
381 // If a magic bitvector captures the entire comparison state
382 // of this load, replace it with computation that does:
383 // ((magic_cst >> i) & 1) != 0
384 {
385 Type *Ty = nullptr;
386
387 // Look for an appropriate type:
388 // - The type of Idx if the magic fits
389 // - The smallest fitting legal type
390 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
391 Ty = Idx->getType();
392 else
393 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
394
395 if (Ty) {
396 Idx = MaskIdx(Idx);
397 Value *V = Builder.CreateIntCast(Idx, Ty, false);
398 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
399 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
400 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
401 }
402 }
403
404 return nullptr;
405}
406
407/// Returns true if we can rewrite Start as a GEP with pointer Base
408/// and some integer offset. The nodes that need to be re-written
409/// for this transformation will be added to Explored.
410static bool canRewriteGEPAsOffset(Type *ElemTy, Value *Start, Value *Base,
411 const DataLayout &DL,
412 SetVector<Value *> &Explored) {
413 SmallVector<Value *, 16> WorkList(1, Start);
414 Explored.insert(Base);
415
416 // The following traversal gives us an order which can be used
417 // when doing the final transformation. Since in the final
418 // transformation we create the PHI replacement instructions first,
419 // we don't have to get them in any particular order.
420 //
421 // However, for other instructions we will have to traverse the
422 // operands of an instruction first, which means that we have to
423 // do a post-order traversal.
424 while (!WorkList.empty()) {
426
427 while (!WorkList.empty()) {
428 if (Explored.size() >= 100)
429 return false;
430
431 Value *V = WorkList.back();
432
433 if (Explored.contains(V)) {
434 WorkList.pop_back();
435 continue;
436 }
437
438 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
439 !isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
440 // We've found some value that we can't explore which is different from
441 // the base. Therefore we can't do this transformation.
442 return false;
443
444 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
445 auto *CI = cast<CastInst>(V);
446 if (!CI->isNoopCast(DL))
447 return false;
448
449 if (!Explored.contains(CI->getOperand(0)))
450 WorkList.push_back(CI->getOperand(0));
451 }
452
453 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
454 // We're limiting the GEP to having one index. This will preserve
455 // the original pointer type. We could handle more cases in the
456 // future.
457 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
458 GEP->getSourceElementType() != ElemTy)
459 return false;
460
461 if (!Explored.contains(GEP->getOperand(0)))
462 WorkList.push_back(GEP->getOperand(0));
463 }
464
465 if (WorkList.back() == V) {
466 WorkList.pop_back();
467 // We've finished visiting this node, mark it as such.
468 Explored.insert(V);
469 }
470
471 if (auto *PN = dyn_cast<PHINode>(V)) {
472 // We cannot transform PHIs on unsplittable basic blocks.
473 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
474 return false;
475 Explored.insert(PN);
476 PHIs.insert(PN);
477 }
478 }
479
480 // Explore the PHI nodes further.
481 for (auto *PN : PHIs)
482 for (Value *Op : PN->incoming_values())
483 if (!Explored.contains(Op))
484 WorkList.push_back(Op);
485 }
486
487 // Make sure that we can do this. Since we can't insert GEPs in a basic
488 // block before a PHI node, we can't easily do this transformation if
489 // we have PHI node users of transformed instructions.
490 for (Value *Val : Explored) {
491 for (Value *Use : Val->uses()) {
492
493 auto *PHI = dyn_cast<PHINode>(Use);
494 auto *Inst = dyn_cast<Instruction>(Val);
495
496 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
497 !Explored.contains(PHI))
498 continue;
499
500 if (PHI->getParent() == Inst->getParent())
501 return false;
502 }
503 }
504 return true;
505}
506
507// Sets the appropriate insert point on Builder where we can add
508// a replacement Instruction for V (if that is possible).
509static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
510 bool Before = true) {
511 if (auto *PHI = dyn_cast<PHINode>(V)) {
512 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
513 return;
514 }
515 if (auto *I = dyn_cast<Instruction>(V)) {
516 if (!Before)
517 I = &*std::next(I->getIterator());
518 Builder.SetInsertPoint(I);
519 return;
520 }
521 if (auto *A = dyn_cast<Argument>(V)) {
522 // Set the insertion point in the entry block.
523 BasicBlock &Entry = A->getParent()->getEntryBlock();
524 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
525 return;
526 }
527 // Otherwise, this is a constant and we don't need to set a new
528 // insertion point.
529 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
530}
531
532/// Returns a re-written value of Start as an indexed GEP using Base as a
533/// pointer.
534static Value *rewriteGEPAsOffset(Type *ElemTy, Value *Start, Value *Base,
535 const DataLayout &DL,
536 SetVector<Value *> &Explored) {
537 // Perform all the substitutions. This is a bit tricky because we can
538 // have cycles in our use-def chains.
539 // 1. Create the PHI nodes without any incoming values.
540 // 2. Create all the other values.
541 // 3. Add the edges for the PHI nodes.
542 // 4. Emit GEPs to get the original pointers.
543 // 5. Remove the original instructions.
544 Type *IndexType = IntegerType::get(
545 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
546
548 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
549
550 // Create the new PHI nodes, without adding any incoming values.
551 for (Value *Val : Explored) {
552 if (Val == Base)
553 continue;
554 // Create empty phi nodes. This avoids cyclic dependencies when creating
555 // the remaining instructions.
556 if (auto *PHI = dyn_cast<PHINode>(Val))
557 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
558 PHI->getName() + ".idx", PHI);
559 }
560 IRBuilder<> Builder(Base->getContext());
561
562 // Create all the other instructions.
563 for (Value *Val : Explored) {
564
565 if (NewInsts.find(Val) != NewInsts.end())
566 continue;
567
568 if (auto *CI = dyn_cast<CastInst>(Val)) {
569 // Don't get rid of the intermediate variable here; the store can grow
570 // the map which will invalidate the reference to the input value.
571 Value *V = NewInsts[CI->getOperand(0)];
572 NewInsts[CI] = V;
573 continue;
574 }
575 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
576 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
577 : GEP->getOperand(1);
579 // Indices might need to be sign extended. GEPs will magically do
580 // this, but we need to do it ourselves here.
581 if (Index->getType()->getScalarSizeInBits() !=
582 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
583 Index = Builder.CreateSExtOrTrunc(
584 Index, NewInsts[GEP->getOperand(0)]->getType(),
585 GEP->getOperand(0)->getName() + ".sext");
586 }
587
588 auto *Op = NewInsts[GEP->getOperand(0)];
589 if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero())
590 NewInsts[GEP] = Index;
591 else
592 NewInsts[GEP] = Builder.CreateNSWAdd(
593 Op, Index, GEP->getOperand(0)->getName() + ".add");
594 continue;
595 }
596 if (isa<PHINode>(Val))
597 continue;
598
599 llvm_unreachable("Unexpected instruction type");
600 }
601
602 // Add the incoming values to the PHI nodes.
603 for (Value *Val : Explored) {
604 if (Val == Base)
605 continue;
606 // All the instructions have been created, we can now add edges to the
607 // phi nodes.
608 if (auto *PHI = dyn_cast<PHINode>(Val)) {
609 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
610 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
611 Value *NewIncoming = PHI->getIncomingValue(I);
612
613 if (NewInsts.find(NewIncoming) != NewInsts.end())
614 NewIncoming = NewInsts[NewIncoming];
615
616 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
617 }
618 }
619 }
620
621 PointerType *PtrTy =
622 ElemTy->getPointerTo(Start->getType()->getPointerAddressSpace());
623 for (Value *Val : Explored) {
624 if (Val == Base)
625 continue;
626
627 // Depending on the type, for external users we have to emit
628 // a GEP or a GEP + ptrtoint.
629 setInsertionPoint(Builder, Val, false);
630
631 // Cast base to the expected type.
632 Value *NewVal = Builder.CreateBitOrPointerCast(
633 Base, PtrTy, Start->getName() + "to.ptr");
634 NewVal = Builder.CreateInBoundsGEP(ElemTy, NewVal, ArrayRef(NewInsts[Val]),
635 Val->getName() + ".ptr");
636 NewVal = Builder.CreateBitOrPointerCast(
637 NewVal, Val->getType(), Val->getName() + ".conv");
638 Val->replaceAllUsesWith(NewVal);
639 }
640
641 return NewInsts[Start];
642}
643
644/// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
645/// the input Value as a constant indexed GEP. Returns a pair containing
646/// the GEPs Pointer and Index.
647static std::pair<Value *, Value *>
649 Type *IndexType = IntegerType::get(V->getContext(),
650 DL.getIndexTypeSizeInBits(V->getType()));
651
653 while (true) {
654 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
655 // We accept only inbouds GEPs here to exclude the possibility of
656 // overflow.
657 if (!GEP->isInBounds())
658 break;
659 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
660 GEP->getSourceElementType() == ElemTy) {
661 V = GEP->getOperand(0);
662 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
664 Index, ConstantExpr::getSExtOrTrunc(GEPIndex, IndexType));
665 continue;
666 }
667 break;
668 }
669 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
670 if (!CI->isNoopCast(DL))
671 break;
672 V = CI->getOperand(0);
673 continue;
674 }
675 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
676 if (!CI->isNoopCast(DL))
677 break;
678 V = CI->getOperand(0);
679 continue;
680 }
681 break;
682 }
683 return {V, Index};
684}
685
686/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
687/// We can look through PHIs, GEPs and casts in order to determine a common base
688/// between GEPLHS and RHS.
691 const DataLayout &DL) {
692 // FIXME: Support vector of pointers.
693 if (GEPLHS->getType()->isVectorTy())
694 return nullptr;
695
696 if (!GEPLHS->hasAllConstantIndices())
697 return nullptr;
698
699 Type *ElemTy = GEPLHS->getSourceElementType();
700 Value *PtrBase, *Index;
701 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(ElemTy, GEPLHS, DL);
702
703 // The set of nodes that will take part in this transformation.
704 SetVector<Value *> Nodes;
705
706 if (!canRewriteGEPAsOffset(ElemTy, RHS, PtrBase, DL, Nodes))
707 return nullptr;
708
709 // We know we can re-write this as
710 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
711 // Since we've only looked through inbouds GEPs we know that we
712 // can't have overflow on either side. We can therefore re-write
713 // this as:
714 // OFFSET1 cmp OFFSET2
715 Value *NewRHS = rewriteGEPAsOffset(ElemTy, RHS, PtrBase, DL, Nodes);
716
717 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
718 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
719 // offset. Since Index is the offset of LHS to the base pointer, we will now
720 // compare the offsets instead of comparing the pointers.
721 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
722}
723
724/// Fold comparisons between a GEP instruction and something else. At this point
725/// we know that the GEP is on the LHS of the comparison.
728 Instruction &I) {
729 // Don't transform signed compares of GEPs into index compares. Even if the
730 // GEP is inbounds, the final add of the base pointer can have signed overflow
731 // and would change the result of the icmp.
732 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
733 // the maximum signed value for the pointer type.
735 return nullptr;
736
737 // Look through bitcasts and addrspacecasts. We do not however want to remove
738 // 0 GEPs.
739 if (!isa<GetElementPtrInst>(RHS))
741
742 Value *PtrBase = GEPLHS->getOperand(0);
743 if (PtrBase == RHS && GEPLHS->isInBounds()) {
744 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
745 Value *Offset = EmitGEPOffset(GEPLHS);
747 Constant::getNullValue(Offset->getType()));
748 }
749
750 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
751 isa<Constant>(RHS) && cast<Constant>(RHS)->isNullValue() &&
752 !NullPointerIsDefined(I.getFunction(),
754 // For most address spaces, an allocation can't be placed at null, but null
755 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
756 // the only valid inbounds address derived from null, is null itself.
757 // Thus, we have four cases to consider:
758 // 1) Base == nullptr, Offset == 0 -> inbounds, null
759 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
760 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
761 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
762 //
763 // (Note if we're indexing a type of size 0, that simply collapses into one
764 // of the buckets above.)
765 //
766 // In general, we're allowed to make values less poison (i.e. remove
767 // sources of full UB), so in this case, we just select between the two
768 // non-poison cases (1 and 4 above).
769 //
770 // For vectors, we apply the same reasoning on a per-lane basis.
771 auto *Base = GEPLHS->getPointerOperand();
772 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
773 auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
775 }
776 return new ICmpInst(Cond, Base,
778 cast<Constant>(RHS), Base->getType()));
779 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
780 // If the base pointers are different, but the indices are the same, just
781 // compare the base pointer.
782 if (PtrBase != GEPRHS->getOperand(0)) {
783 bool IndicesTheSame =
784 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
785 GEPLHS->getPointerOperand()->getType() ==
786 GEPRHS->getPointerOperand()->getType() &&
787 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
788 if (IndicesTheSame)
789 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
790 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
791 IndicesTheSame = false;
792 break;
793 }
794
795 // If all indices are the same, just compare the base pointers.
796 Type *BaseType = GEPLHS->getOperand(0)->getType();
797 if (IndicesTheSame && CmpInst::makeCmpResultType(BaseType) == I.getType())
798 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
799
800 // If we're comparing GEPs with two base pointers that only differ in type
801 // and both GEPs have only constant indices or just one use, then fold
802 // the compare with the adjusted indices.
803 // FIXME: Support vector of pointers.
804 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
805 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
806 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
807 PtrBase->stripPointerCasts() ==
808 GEPRHS->getOperand(0)->stripPointerCasts() &&
809 !GEPLHS->getType()->isVectorTy()) {
810 Value *LOffset = EmitGEPOffset(GEPLHS);
811 Value *ROffset = EmitGEPOffset(GEPRHS);
812
813 // If we looked through an addrspacecast between different sized address
814 // spaces, the LHS and RHS pointers are different sized
815 // integers. Truncate to the smaller one.
816 Type *LHSIndexTy = LOffset->getType();
817 Type *RHSIndexTy = ROffset->getType();
818 if (LHSIndexTy != RHSIndexTy) {
819 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
820 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
821 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
822 } else
823 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
824 }
825
827 LOffset, ROffset);
828 return replaceInstUsesWith(I, Cmp);
829 }
830
831 // Otherwise, the base pointers are different and the indices are
832 // different. Try convert this to an indexed compare by looking through
833 // PHIs/casts.
834 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
835 }
836
837 // If one of the GEPs has all zero indices, recurse.
838 // FIXME: Handle vector of pointers.
839 if (!GEPLHS->getType()->isVectorTy() && GEPLHS->hasAllZeroIndices())
840 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
842
843 // If the other GEP has all zero indices, recurse.
844 // FIXME: Handle vector of pointers.
845 if (!GEPRHS->getType()->isVectorTy() && GEPRHS->hasAllZeroIndices())
846 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
847
848 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
849 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
850 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
851 // If the GEPs only differ by one index, compare it.
852 unsigned NumDifferences = 0; // Keep track of # differences.
853 unsigned DiffOperand = 0; // The operand that differs.
854 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
855 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
856 Type *LHSType = GEPLHS->getOperand(i)->getType();
857 Type *RHSType = GEPRHS->getOperand(i)->getType();
858 // FIXME: Better support for vector of pointers.
859 if (LHSType->getPrimitiveSizeInBits() !=
860 RHSType->getPrimitiveSizeInBits() ||
861 (GEPLHS->getType()->isVectorTy() &&
862 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
863 // Irreconcilable differences.
864 NumDifferences = 2;
865 break;
866 }
867
868 if (NumDifferences++) break;
869 DiffOperand = i;
870 }
871
872 if (NumDifferences == 0) // SAME GEP?
873 return replaceInstUsesWith(I, // No comparison is needed here.
875
876 else if (NumDifferences == 1 && GEPsInBounds) {
877 Value *LHSV = GEPLHS->getOperand(DiffOperand);
878 Value *RHSV = GEPRHS->getOperand(DiffOperand);
879 // Make sure we do a signed comparison here.
880 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
881 }
882 }
883
884 // Only lower this if the icmp is the only user of the GEP or if we expect
885 // the result to fold to a constant!
886 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
887 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
888 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
889 Value *L = EmitGEPOffset(GEPLHS);
890 Value *R = EmitGEPOffset(GEPRHS);
891 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
892 }
893 }
894
895 // Try convert this to an indexed compare by looking through PHIs/casts as a
896 // last resort.
897 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
898}
899
901 const AllocaInst *Alloca) {
902 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
903
904 // It would be tempting to fold away comparisons between allocas and any
905 // pointer not based on that alloca (e.g. an argument). However, even
906 // though such pointers cannot alias, they can still compare equal.
907 //
908 // But LLVM doesn't specify where allocas get their memory, so if the alloca
909 // doesn't escape we can argue that it's impossible to guess its value, and we
910 // can therefore act as if any such guesses are wrong.
911 //
912 // The code below checks that the alloca doesn't escape, and that it's only
913 // used in a comparison once (the current instruction). The
914 // single-comparison-use condition ensures that we're trivially folding all
915 // comparisons against the alloca consistently, and avoids the risk of
916 // erroneously folding a comparison of the pointer with itself.
917
918 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
919
921 for (const Use &U : Alloca->uses()) {
922 if (Worklist.size() >= MaxIter)
923 return nullptr;
924 Worklist.push_back(&U);
925 }
926
927 unsigned NumCmps = 0;
928 while (!Worklist.empty()) {
929 assert(Worklist.size() <= MaxIter);
930 const Use *U = Worklist.pop_back_val();
931 const Value *V = U->getUser();
932 --MaxIter;
933
934 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
935 isa<SelectInst>(V)) {
936 // Track the uses.
937 } else if (isa<LoadInst>(V)) {
938 // Loading from the pointer doesn't escape it.
939 continue;
940 } else if (const auto *SI = dyn_cast<StoreInst>(V)) {
941 // Storing *to* the pointer is fine, but storing the pointer escapes it.
942 if (SI->getValueOperand() == U->get())
943 return nullptr;
944 continue;
945 } else if (isa<ICmpInst>(V)) {
946 if (NumCmps++)
947 return nullptr; // Found more than one cmp.
948 continue;
949 } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
950 switch (Intrin->getIntrinsicID()) {
951 // These intrinsics don't escape or compare the pointer. Memset is safe
952 // because we don't allow ptrtoint. Memcpy and memmove are safe because
953 // we don't allow stores, so src cannot point to V.
954 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
955 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
956 continue;
957 default:
958 return nullptr;
959 }
960 } else {
961 return nullptr;
962 }
963 for (const Use &U : V->uses()) {
964 if (Worklist.size() >= MaxIter)
965 return nullptr;
966 Worklist.push_back(&U);
967 }
968 }
969
970 auto *Res = ConstantInt::get(ICI.getType(),
972 return replaceInstUsesWith(ICI, Res);
973}
974
975/// Fold "icmp pred (X+C), X".
977 ICmpInst::Predicate Pred) {
978 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
979 // so the values can never be equal. Similarly for all other "or equals"
980 // operators.
981 assert(!!C && "C should not be zero!");
982
983 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
984 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
985 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
986 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
987 Constant *R = ConstantInt::get(X->getType(),
988 APInt::getMaxValue(C.getBitWidth()) - C);
989 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
990 }
991
992 // (X+1) >u X --> X <u (0-1) --> X != 255
993 // (X+2) >u X --> X <u (0-2) --> X <u 254
994 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
995 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
996 return new ICmpInst(ICmpInst::ICMP_ULT, X,
997 ConstantInt::get(X->getType(), -C));
998
999 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
1000
1001 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1002 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1003 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1004 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1005 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1006 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
1007 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1008 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1009 ConstantInt::get(X->getType(), SMax - C));
1010
1011 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1012 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1013 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1014 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1015 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1016 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
1017
1018 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
1019 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1020 ConstantInt::get(X->getType(), SMax - (C - 1)));
1021}
1022
1023/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
1024/// (icmp eq/ne A, Log2(AP2/AP1)) ->
1025/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
1027 const APInt &AP1,
1028 const APInt &AP2) {
1029 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1030
1031 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1032 if (I.getPredicate() == I.ICMP_NE)
1033 Pred = CmpInst::getInversePredicate(Pred);
1034 return new ICmpInst(Pred, LHS, RHS);
1035 };
1036
1037 // Don't bother doing any work for cases which InstSimplify handles.
1038 if (AP2.isZero())
1039 return nullptr;
1040
1041 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
1042 if (IsAShr) {
1043 if (AP2.isAllOnes())
1044 return nullptr;
1045 if (AP2.isNegative() != AP1.isNegative())
1046 return nullptr;
1047 if (AP2.sgt(AP1))
1048 return nullptr;
1049 }
1050
1051 if (!AP1)
1052 // 'A' must be large enough to shift out the highest set bit.
1053 return getICmp(I.ICMP_UGT, A,
1054 ConstantInt::get(A->getType(), AP2.logBase2()));
1055
1056 if (AP1 == AP2)
1057 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1058
1059 int Shift;
1060 if (IsAShr && AP1.isNegative())
1061 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
1062 else
1063 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
1064
1065 if (Shift > 0) {
1066 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1067 // There are multiple solutions if we are comparing against -1 and the LHS
1068 // of the ashr is not a power of two.
1069 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1070 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1071 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1072 } else if (AP1 == AP2.lshr(Shift)) {
1073 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1074 }
1075 }
1076
1077 // Shifting const2 will never be equal to const1.
1078 // FIXME: This should always be handled by InstSimplify?
1079 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1080 return replaceInstUsesWith(I, TorF);
1081}
1082
1083/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1084/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1086 const APInt &AP1,
1087 const APInt &AP2) {
1088 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1089
1090 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1091 if (I.getPredicate() == I.ICMP_NE)
1092 Pred = CmpInst::getInversePredicate(Pred);
1093 return new ICmpInst(Pred, LHS, RHS);
1094 };
1095
1096 // Don't bother doing any work for cases which InstSimplify handles.
1097 if (AP2.isZero())
1098 return nullptr;
1099
1100 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1101
1102 if (!AP1 && AP2TrailingZeros != 0)
1103 return getICmp(
1104 I.ICMP_UGE, A,
1105 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1106
1107 if (AP1 == AP2)
1108 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1109
1110 // Get the distance between the lowest bits that are set.
1111 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1112
1113 if (Shift > 0 && AP2.shl(Shift) == AP1)
1114 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1115
1116 // Shifting const2 will never be equal to const1.
1117 // FIXME: This should always be handled by InstSimplify?
1118 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1119 return replaceInstUsesWith(I, TorF);
1120}
1121
1122/// The caller has matched a pattern of the form:
1123/// I = icmp ugt (add (add A, B), CI2), CI1
1124/// If this is of the form:
1125/// sum = a + b
1126/// if (sum+128 >u 255)
1127/// Then replace it with llvm.sadd.with.overflow.i8.
1128///
1130 ConstantInt *CI2, ConstantInt *CI1,
1131 InstCombinerImpl &IC) {
1132 // The transformation we're trying to do here is to transform this into an
1133 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1134 // with a narrower add, and discard the add-with-constant that is part of the
1135 // range check (if we can't eliminate it, this isn't profitable).
1136
1137 // In order to eliminate the add-with-constant, the compare can be its only
1138 // use.
1139 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1140 if (!AddWithCst->hasOneUse())
1141 return nullptr;
1142
1143 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1144 if (!CI2->getValue().isPowerOf2())
1145 return nullptr;
1146 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1147 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1148 return nullptr;
1149
1150 // The width of the new add formed is 1 more than the bias.
1151 ++NewWidth;
1152
1153 // Check to see that CI1 is an all-ones value with NewWidth bits.
1154 if (CI1->getBitWidth() == NewWidth ||
1155 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1156 return nullptr;
1157
1158 // This is only really a signed overflow check if the inputs have been
1159 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1160 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1161 if (IC.ComputeMaxSignificantBits(A, 0, &I) > NewWidth ||
1162 IC.ComputeMaxSignificantBits(B, 0, &I) > NewWidth)
1163 return nullptr;
1164
1165 // In order to replace the original add with a narrower
1166 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1167 // and truncates that discard the high bits of the add. Verify that this is
1168 // the case.
1169 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1170 for (User *U : OrigAdd->users()) {
1171 if (U == AddWithCst)
1172 continue;
1173
1174 // Only accept truncates for now. We would really like a nice recursive
1175 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1176 // chain to see which bits of a value are actually demanded. If the
1177 // original add had another add which was then immediately truncated, we
1178 // could still do the transformation.
1179 TruncInst *TI = dyn_cast<TruncInst>(U);
1180 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1181 return nullptr;
1182 }
1183
1184 // If the pattern matches, truncate the inputs to the narrower type and
1185 // use the sadd_with_overflow intrinsic to efficiently compute both the
1186 // result and the overflow bit.
1187 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1189 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1190
1192
1193 // Put the new code above the original add, in case there are any uses of the
1194 // add between the add and the compare.
1195 Builder.SetInsertPoint(OrigAdd);
1196
1197 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1198 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1199 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1200 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1201 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1202
1203 // The inner add was the result of the narrow add, zero extended to the
1204 // wider type. Replace it with the result computed by the intrinsic.
1205 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1206 IC.eraseInstFromFunction(*OrigAdd);
1207
1208 // The original icmp gets replaced with the overflow value.
1209 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1210}
1211
1212/// If we have:
1213/// icmp eq/ne (urem/srem %x, %y), 0
1214/// iff %y is a power-of-two, we can replace this with a bit test:
1215/// icmp eq/ne (and %x, (add %y, -1)), 0
1217 // This fold is only valid for equality predicates.
1218 if (!I.isEquality())
1219 return nullptr;
1221 Value *X, *Y, *Zero;
1222 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1223 m_CombineAnd(m_Zero(), m_Value(Zero)))))
1224 return nullptr;
1225 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, 0, &I))
1226 return nullptr;
1227 // This may increase instruction count, we don't enforce that Y is a constant.
1228 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1229 Value *Masked = Builder.CreateAnd(X, Mask);
1230 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1231}
1232
1233/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1234/// by one-less-than-bitwidth into a sign test on the original value.
1236 Instruction *Val;
1238 if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1239 return nullptr;
1240
1241 Value *X;
1242 Type *XTy;
1243
1244 Constant *C;
1245 if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1246 XTy = X->getType();
1247 unsigned XBitWidth = XTy->getScalarSizeInBits();
1249 APInt(XBitWidth, XBitWidth - 1))))
1250 return nullptr;
1251 } else if (isa<BinaryOperator>(Val) &&
1253 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1254 /*AnalyzeForSignBitExtraction=*/true))) {
1255 XTy = X->getType();
1256 } else
1257 return nullptr;
1258
1259 return ICmpInst::Create(Instruction::ICmp,
1263}
1264
1265// Handle icmp pred X, 0
1267 CmpInst::Predicate Pred = Cmp.getPredicate();
1268 if (!match(Cmp.getOperand(1), m_Zero()))
1269 return nullptr;
1270
1271 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1272 if (Pred == ICmpInst::ICMP_SGT) {
1273 Value *A, *B;
1274 if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1275 if (isKnownPositive(A, DL, 0, &AC, &Cmp, &DT))
1276 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1277 if (isKnownPositive(B, DL, 0, &AC, &Cmp, &DT))
1278 return new ICmpInst(Pred, A, Cmp.getOperand(1));
1279 }
1280 }
1281
1283 return New;
1284
1285 // Given:
1286 // icmp eq/ne (urem %x, %y), 0
1287 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1288 // icmp eq/ne %x, 0
1289 Value *X, *Y;
1290 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1291 ICmpInst::isEquality(Pred)) {
1292 KnownBits XKnown = computeKnownBits(X, 0, &Cmp);
1293 KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);
1294 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1295 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1296 }
1297
1298 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1299 // odd/non-zero/there is no overflow.
1300 if (match(Cmp.getOperand(0), m_Mul(m_Value(X), m_Value(Y))) &&
1301 ICmpInst::isEquality(Pred)) {
1302
1303 KnownBits XKnown = computeKnownBits(X, 0, &Cmp);
1304 // if X % 2 != 0
1305 // (icmp eq/ne Y)
1306 if (XKnown.countMaxTrailingZeros() == 0)
1307 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1308
1309 KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);
1310 // if Y % 2 != 0
1311 // (icmp eq/ne X)
1312 if (YKnown.countMaxTrailingZeros() == 0)
1313 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1314
1315 auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1316 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1317 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
1318 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1319 // but to avoid unnecessary work, first just if this is an obvious case.
1320
1321 // if X non-zero and NoOverflow(X * Y)
1322 // (icmp eq/ne Y)
1323 if (!XKnown.One.isZero() || isKnownNonZero(X, DL, 0, Q.AC, Q.CxtI, Q.DT))
1324 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1325
1326 // if Y non-zero and NoOverflow(X * Y)
1327 // (icmp eq/ne X)
1328 if (!YKnown.One.isZero() || isKnownNonZero(Y, DL, 0, Q.AC, Q.CxtI, Q.DT))
1329 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1330 }
1331 // Note, we are skipping cases:
1332 // if Y % 2 != 0 AND X % 2 != 0
1333 // (false/true)
1334 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1335 // (false/true)
1336 // Those can be simplified later as we would have already replaced the (icmp
1337 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1338 // will fold to a constant elsewhere.
1339 }
1340 return nullptr;
1341}
1342
1343/// Fold icmp Pred X, C.
1344/// TODO: This code structure does not make sense. The saturating add fold
1345/// should be moved to some other helper and extended as noted below (it is also
1346/// possible that code has been made unnecessary - do we canonicalize IR to
1347/// overflow/saturating intrinsics or not?).
1349 // Match the following pattern, which is a common idiom when writing
1350 // overflow-safe integer arithmetic functions. The source performs an addition
1351 // in wider type and explicitly checks for overflow using comparisons against
1352 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1353 //
1354 // TODO: This could probably be generalized to handle other overflow-safe
1355 // operations if we worked out the formulas to compute the appropriate magic
1356 // constants.
1357 //
1358 // sum = a + b
1359 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1360 CmpInst::Predicate Pred = Cmp.getPredicate();
1361 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1362 Value *A, *B;
1363 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1364 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1365 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1366 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1367 return Res;
1368
1369 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1370 Constant *C = dyn_cast<Constant>(Op1);
1371 if (!C)
1372 return nullptr;
1373
1374 if (auto *Phi = dyn_cast<PHINode>(Op0))
1375 if (all_of(Phi->operands(), [](Value *V) { return isa<Constant>(V); })) {
1376 Type *Ty = Cmp.getType();
1378 PHINode *NewPhi =
1379 Builder.CreatePHI(Ty, Phi->getNumOperands());
1380 for (BasicBlock *Predecessor : predecessors(Phi->getParent())) {
1381 auto *Input =
1382 cast<Constant>(Phi->getIncomingValueForBlock(Predecessor));
1383 auto *BoolInput = ConstantExpr::getCompare(Pred, Input, C);
1384 NewPhi->addIncoming(BoolInput, Predecessor);
1385 }
1386 NewPhi->takeName(&Cmp);
1387 return replaceInstUsesWith(Cmp, NewPhi);
1388 }
1389
1390 return nullptr;
1391}
1392
1393/// Canonicalize icmp instructions based on dominating conditions.
1395 // This is a cheap/incomplete check for dominance - just match a single
1396 // predecessor with a conditional branch.
1397 BasicBlock *CmpBB = Cmp.getParent();
1398 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1399 if (!DomBB)
1400 return nullptr;
1401
1402 Value *DomCond;
1403 BasicBlock *TrueBB, *FalseBB;
1404 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1405 return nullptr;
1406
1407 assert((TrueBB == CmpBB || FalseBB == CmpBB) &&
1408 "Predecessor block does not point to successor?");
1409
1410 // The branch should get simplified. Don't bother simplifying this condition.
1411 if (TrueBB == FalseBB)
1412 return nullptr;
1413
1414 // Try to simplify this compare to T/F based on the dominating condition.
1415 std::optional<bool> Imp =
1416 isImpliedCondition(DomCond, &Cmp, DL, TrueBB == CmpBB);
1417 if (Imp)
1418 return replaceInstUsesWith(Cmp, ConstantInt::get(Cmp.getType(), *Imp));
1419
1420 CmpInst::Predicate Pred = Cmp.getPredicate();
1421 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1422 ICmpInst::Predicate DomPred;
1423 const APInt *C, *DomC;
1424 if (match(DomCond, m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))) &&
1425 match(Y, m_APInt(C))) {
1426 // We have 2 compares of a variable with constants. Calculate the constant
1427 // ranges of those compares to see if we can transform the 2nd compare:
1428 // DomBB:
1429 // DomCond = icmp DomPred X, DomC
1430 // br DomCond, CmpBB, FalseBB
1431 // CmpBB:
1432 // Cmp = icmp Pred X, C
1434 ConstantRange DominatingCR =
1435 (CmpBB == TrueBB) ? ConstantRange::makeExactICmpRegion(DomPred, *DomC)
1437 CmpInst::getInversePredicate(DomPred), *DomC);
1438 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1439 ConstantRange Difference = DominatingCR.difference(CR);
1440 if (Intersection.isEmptySet())
1441 return replaceInstUsesWith(Cmp, Builder.getFalse());
1442 if (Difference.isEmptySet())
1443 return replaceInstUsesWith(Cmp, Builder.getTrue());
1444
1445 // Canonicalizing a sign bit comparison that gets used in a branch,
1446 // pessimizes codegen by generating branch on zero instruction instead
1447 // of a test and branch. So we avoid canonicalizing in such situations
1448 // because test and branch instruction has better branch displacement
1449 // than compare and branch instruction.
1450 bool UnusedBit;
1451 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1452 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1453 return nullptr;
1454
1455 // Avoid an infinite loop with min/max canonicalization.
1456 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1457 if (Cmp.hasOneUse() &&
1458 match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1459 return nullptr;
1460
1461 if (const APInt *EqC = Intersection.getSingleElement())
1462 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1463 if (const APInt *NeC = Difference.getSingleElement())
1464 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1465 }
1466
1467 return nullptr;
1468}
1469
1470/// Fold icmp (trunc X), C.
1472 TruncInst *Trunc,
1473 const APInt &C) {
1474 ICmpInst::Predicate Pred = Cmp.getPredicate();
1475 Value *X = Trunc->getOperand(0);
1476 if (C.isOne() && C.getBitWidth() > 1) {
1477 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1478 Value *V = nullptr;
1479 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1480 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1481 ConstantInt::get(V->getType(), 1));
1482 }
1483
1484 Type *SrcTy = X->getType();
1485 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1486 SrcBits = SrcTy->getScalarSizeInBits();
1487
1488 // TODO: Handle any shifted constant by subtracting trailing zeros.
1489 // TODO: Handle non-equality predicates.
1490 Value *Y;
1491 if (Cmp.isEquality() && match(X, m_Shl(m_One(), m_Value(Y)))) {
1492 // (trunc (1 << Y) to iN) == 0 --> Y u>= N
1493 // (trunc (1 << Y) to iN) != 0 --> Y u< N
1494 if (C.isZero()) {
1495 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1496 return new ICmpInst(NewPred, Y, ConstantInt::get(SrcTy, DstBits));
1497 }
1498 // (trunc (1 << Y) to iN) == 2**C --> Y == C
1499 // (trunc (1 << Y) to iN) != 2**C --> Y != C
1500 if (C.isPowerOf2())
1501 return new ICmpInst(Pred, Y, ConstantInt::get(SrcTy, C.logBase2()));
1502 }
1503
1504 if (Cmp.isEquality() && Trunc->hasOneUse()) {
1505 // Canonicalize to a mask and wider compare if the wide type is suitable:
1506 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1507 if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1508 Constant *Mask =
1509 ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1510 Value *And = Builder.CreateAnd(X, Mask);
1511 Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1512 return new ICmpInst(Pred, And, WideC);
1513 }
1514
1515 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1516 // of the high bits truncated out of x are known.
1517 KnownBits Known = computeKnownBits(X, 0, &Cmp);
1518
1519 // If all the high bits are known, we can do this xform.
1520 if ((Known.Zero | Known.One).countLeadingOnes() >= SrcBits - DstBits) {
1521 // Pull in the high bits from known-ones set.
1522 APInt NewRHS = C.zext(SrcBits);
1523 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1524 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1525 }
1526 }
1527
1528 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1529 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1530 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1531 Value *ShOp;
1532 const APInt *ShAmtC;
1533 bool TrueIfSigned;
1534 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1535 match(X, m_Shr(m_Value(ShOp), m_APInt(ShAmtC))) &&
1536 DstBits == SrcBits - ShAmtC->getZExtValue()) {
1537 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1539 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1541 }
1542
1543 return nullptr;
1544}
1545
1546/// Fold icmp (xor X, Y), C.
1549 const APInt &C) {
1550 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1551 return I;
1552
1553 Value *X = Xor->getOperand(0);
1554 Value *Y = Xor->getOperand(1);
1555 const APInt *XorC;
1556 if (!match(Y, m_APInt(XorC)))
1557 return nullptr;
1558
1559 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1560 // fold the xor.
1561 ICmpInst::Predicate Pred = Cmp.getPredicate();
1562 bool TrueIfSigned = false;
1563 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1564
1565 // If the sign bit of the XorCst is not set, there is no change to
1566 // the operation, just stop using the Xor.
1567 if (!XorC->isNegative())
1568 return replaceOperand(Cmp, 0, X);
1569
1570 // Emit the opposite comparison.
1571 if (TrueIfSigned)
1572 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1573 ConstantInt::getAllOnesValue(X->getType()));
1574 else
1575 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1576 ConstantInt::getNullValue(X->getType()));
1577 }
1578
1579 if (Xor->hasOneUse()) {
1580 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1581 if (!Cmp.isEquality() && XorC->isSignMask()) {
1582 Pred = Cmp.getFlippedSignednessPredicate();
1583 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1584 }
1585
1586 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1587 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1588 Pred = Cmp.getFlippedSignednessPredicate();
1589 Pred = Cmp.getSwappedPredicate(Pred);
1590 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1591 }
1592 }
1593
1594 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1595 if (Pred == ICmpInst::ICMP_UGT) {
1596 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1597 if (*XorC == ~C && (C + 1).isPowerOf2())
1598 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1599 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1600 if (*XorC == C && (C + 1).isPowerOf2())
1601 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1602 }
1603 if (Pred == ICmpInst::ICMP_ULT) {
1604 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1605 if (*XorC == -C && C.isPowerOf2())
1606 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1607 ConstantInt::get(X->getType(), ~C));
1608 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1609 if (*XorC == C && (-C).isPowerOf2())
1610 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1611 ConstantInt::get(X->getType(), ~C));
1612 }
1613 return nullptr;
1614}
1615
1616/// For power-of-2 C:
1617/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1618/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1621 const APInt &C) {
1622 CmpInst::Predicate Pred = Cmp.getPredicate();
1623 APInt PowerOf2;
1624 if (Pred == ICmpInst::ICMP_ULT)
1625 PowerOf2 = C;
1626 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1627 PowerOf2 = C + 1;
1628 else
1629 return nullptr;
1630 if (!PowerOf2.isPowerOf2())
1631 return nullptr;
1632 Value *X;
1633 const APInt *ShiftC;
1635 m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1636 return nullptr;
1637 uint64_t Shift = ShiftC->getLimitedValue();
1638 Type *XType = X->getType();
1639 if (Shift == 0 || PowerOf2.isMinSignedValue())
1640 return nullptr;
1641 Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1642 APInt Bound =
1643 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1644 return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1645}
1646
1647/// Fold icmp (and (sh X, Y), C2), C1.
1650 const APInt &C1,
1651 const APInt &C2) {
1652 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1653 if (!Shift || !Shift->isShift())
1654 return nullptr;
1655
1656 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1657 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1658 // code produced by the clang front-end, for bitfield access.
1659 // This seemingly simple opportunity to fold away a shift turns out to be
1660 // rather complicated. See PR17827 for details.
1661 unsigned ShiftOpcode = Shift->getOpcode();
1662 bool IsShl = ShiftOpcode == Instruction::Shl;
1663 const APInt *C3;
1664 if (match(Shift->getOperand(1), m_APInt(C3))) {
1665 APInt NewAndCst, NewCmpCst;
1666 bool AnyCmpCstBitsShiftedOut;
1667 if (ShiftOpcode == Instruction::Shl) {
1668 // For a left shift, we can fold if the comparison is not signed. We can
1669 // also fold a signed comparison if the mask value and comparison value
1670 // are not negative. These constraints may not be obvious, but we can
1671 // prove that they are correct using an SMT solver.
1672 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1673 return nullptr;
1674
1675 NewCmpCst = C1.lshr(*C3);
1676 NewAndCst = C2.lshr(*C3);
1677 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1678 } else if (ShiftOpcode == Instruction::LShr) {
1679 // For a logical right shift, we can fold if the comparison is not signed.
1680 // We can also fold a signed comparison if the shifted mask value and the
1681 // shifted comparison value are not negative. These constraints may not be
1682 // obvious, but we can prove that they are correct using an SMT solver.
1683 NewCmpCst = C1.shl(*C3);
1684 NewAndCst = C2.shl(*C3);
1685 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1686 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1687 return nullptr;
1688 } else {
1689 // For an arithmetic shift, check that both constants don't use (in a
1690 // signed sense) the top bits being shifted out.
1691 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1692 NewCmpCst = C1.shl(*C3);
1693 NewAndCst = C2.shl(*C3);
1694 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1695 if (NewAndCst.ashr(*C3) != C2)
1696 return nullptr;
1697 }
1698
1699 if (AnyCmpCstBitsShiftedOut) {
1700 // If we shifted bits out, the fold is not going to work out. As a
1701 // special case, check to see if this means that the result is always
1702 // true or false now.
1703 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1704 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1705 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1706 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1707 } else {
1708 Value *NewAnd = Builder.CreateAnd(
1709 Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1710 return new ICmpInst(Cmp.getPredicate(),
1711 NewAnd, ConstantInt::get(And->getType(), NewCmpCst));
1712 }
1713 }
1714
1715 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1716 // preferable because it allows the C2 << Y expression to be hoisted out of a
1717 // loop if Y is invariant and X is not.
1718 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1719 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1720 // Compute C2 << Y.
1721 Value *NewShift =
1722 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1723 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1724
1725 // Compute X & (C2 << Y).
1726 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1727 return replaceOperand(Cmp, 0, NewAnd);
1728 }
1729
1730 return nullptr;
1731}
1732
1733/// Fold icmp (and X, C2), C1.
1736 const APInt &C1) {
1737 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1738
1739 // For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i1
1740 // TODO: We canonicalize to the longer form for scalars because we have
1741 // better analysis/folds for icmp, and codegen may be better with icmp.
1742 if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.isZero() &&
1743 match(And->getOperand(1), m_One()))
1744 return new TruncInst(And->getOperand(0), Cmp.getType());
1745
1746 const APInt *C2;
1747 Value *X;
1748 if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1749 return nullptr;
1750
1751 // Don't perform the following transforms if the AND has multiple uses
1752 if (!And->hasOneUse())
1753 return nullptr;
1754
1755 if (Cmp.isEquality() && C1.isZero()) {
1756 // Restrict this fold to single-use 'and' (PR10267).
1757 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1758 if (C2->isSignMask()) {
1759 Constant *Zero = Constant::getNullValue(X->getType());
1760 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1761 return new ICmpInst(NewPred, X, Zero);
1762 }
1763
1764 APInt NewC2 = *C2;
1765 KnownBits Know = computeKnownBits(And->getOperand(0), 0, And);
1766 // Set high zeros of C2 to allow matching negated power-of-2.
1767 NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
1768 Know.countMinLeadingZeros());
1769
1770 // Restrict this fold only for single-use 'and' (PR10267).
1771 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1772 if (NewC2.isNegatedPowerOf2()) {
1773 Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1774 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1775 return new ICmpInst(NewPred, X, NegBOC);
1776 }
1777 }
1778
1779 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1780 // the input width without changing the value produced, eliminate the cast:
1781 //
1782 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1783 //
1784 // We can do this transformation if the constants do not have their sign bits
1785 // set or if it is an equality comparison. Extending a relational comparison
1786 // when we're checking the sign bit would not work.
1787 Value *W;
1788 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1789 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1790 // TODO: Is this a good transform for vectors? Wider types may reduce
1791 // throughput. Should this transform be limited (even for scalars) by using
1792 // shouldChangeType()?
1793 if (!Cmp.getType()->isVectorTy()) {
1794 Type *WideType = W->getType();
1795 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1796 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1797 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1798 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1799 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1800 }
1801 }
1802
1803 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1804 return I;
1805
1806 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1807 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1808 //
1809 // iff pred isn't signed
1810 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1811 match(And->getOperand(1), m_One())) {
1812 Constant *One = cast<Constant>(And->getOperand(1));
1813 Value *Or = And->getOperand(0);
1814 Value *A, *B, *LShr;
1815 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1816 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1817 unsigned UsesRemoved = 0;
1818 if (And->hasOneUse())
1819 ++UsesRemoved;
1820 if (Or->hasOneUse())
1821 ++UsesRemoved;
1822 if (LShr->hasOneUse())
1823 ++UsesRemoved;
1824
1825 // Compute A & ((1 << B) | 1)
1826 Value *NewOr = nullptr;
1827 if (auto *C = dyn_cast<Constant>(B)) {
1828 if (UsesRemoved >= 1)
1829 NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1830 } else {
1831 if (UsesRemoved >= 3)
1832 NewOr = Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1833 /*HasNUW=*/true),
1834 One, Or->getName());
1835 }
1836 if (NewOr) {
1837 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1838 return replaceOperand(Cmp, 0, NewAnd);
1839 }
1840 }
1841 }
1842
1843 return nullptr;
1844}
1845
1846/// Fold icmp (and X, Y), C.
1849 const APInt &C) {
1850 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1851 return I;
1852
1853 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1854 bool TrueIfNeg;
1855 if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1856 // ((X - 1) & ~X) < 0 --> X == 0
1857 // ((X - 1) & ~X) >= 0 --> X != 0
1858 Value *X;
1859 if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1860 match(And->getOperand(1), m_Not(m_Specific(X)))) {
1861 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1862 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1863 }
1864 }
1865
1866 // TODO: These all require that Y is constant too, so refactor with the above.
1867
1868 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1869 Value *X = And->getOperand(0);
1870 Value *Y = And->getOperand(1);
1871 if (auto *C2 = dyn_cast<ConstantInt>(Y))
1872 if (auto *LI = dyn_cast<LoadInst>(X))
1873 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1874 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1875 if (Instruction *Res =
1876 foldCmpLoadFromIndexedGlobal(LI, GEP, GV, Cmp, C2))
1877 return Res;
1878
1879 if (!Cmp.isEquality())
1880 return nullptr;
1881
1882 // X & -C == -C -> X > u ~C
1883 // X & -C != -C -> X <= u ~C
1884 // iff C is a power of 2
1885 if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
1886 auto NewPred =
1888 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1889 }
1890
1891 // If we are testing the intersection of 2 select-of-nonzero-constants with no
1892 // common bits set, it's the same as checking if exactly one select condition
1893 // is set:
1894 // ((A ? TC : FC) & (B ? TC : FC)) == 0 --> xor A, B
1895 // ((A ? TC : FC) & (B ? TC : FC)) != 0 --> not(xor A, B)
1896 // TODO: Generalize for non-constant values.
1897 // TODO: Handle signed/unsigned predicates.
1898 // TODO: Handle other bitwise logic connectors.
1899 // TODO: Extend to handle a non-zero compare constant.
1900 if (C.isZero() && (Pred == CmpInst::ICMP_EQ || And->hasOneUse())) {
1901 assert(Cmp.isEquality() && "Not expecting non-equality predicates");
1902 Value *A, *B;
1903 const APInt *TC, *FC;
1904 if (match(X, m_Select(m_Value(A), m_APInt(TC), m_APInt(FC))) &&
1905 match(Y,
1906 m_Select(m_Value(B), m_SpecificInt(*TC), m_SpecificInt(*FC))) &&
1907 !TC->isZero() && !FC->isZero() && !TC->intersects(*FC)) {
1908 Value *R = Builder.CreateXor(A, B);
1909 if (Pred == CmpInst::ICMP_NE)
1910 R = Builder.CreateNot(R);
1911 return replaceInstUsesWith(Cmp, R);
1912 }
1913 }
1914
1915 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
1916 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
1917 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
1918 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
1920 X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
1921 Value *TruncY = Builder.CreateTrunc(Y, X->getType());
1922 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
1923 Value *And = Builder.CreateAnd(TruncY, X);
1925 }
1926 return BinaryOperator::CreateAnd(TruncY, X);
1927 }
1928
1929 return nullptr;
1930}
1931
1932/// Fold icmp (or X, Y), C.
1935 const APInt &C) {
1936 ICmpInst::Predicate Pred = Cmp.getPredicate();
1937 if (C.isOne()) {
1938 // icmp slt signum(V) 1 --> icmp slt V, 1
1939 Value *V = nullptr;
1940 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
1941 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1942 ConstantInt::get(V->getType(), 1));
1943 }
1944
1945 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
1946 const APInt *MaskC;
1947 if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
1948 if (*MaskC == C && (C + 1).isPowerOf2()) {
1949 // X | C == C --> X <=u C
1950 // X | C != C --> X >u C
1951 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
1953 return new ICmpInst(Pred, OrOp0, OrOp1);
1954 }
1955
1956 // More general: canonicalize 'equality with set bits mask' to
1957 // 'equality with clear bits mask'.
1958 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
1959 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
1960 if (Or->hasOneUse()) {
1961 Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
1962 Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
1963 return new ICmpInst(Pred, And, NewC);
1964 }
1965 }
1966
1967 // (X | (X-1)) s< 0 --> X s< 1
1968 // (X | (X-1)) s> -1 --> X s> 0
1969 Value *X;
1970 bool TrueIfSigned;
1971 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1973 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
1974 Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
1975 return new ICmpInst(NewPred, X, NewC);
1976 }
1977
1978 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
1979 return nullptr;
1980
1981 Value *P, *Q;
1983 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1984 // -> and (icmp eq P, null), (icmp eq Q, null).
1985 Value *CmpP =
1986 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
1987 Value *CmpQ =
1989 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1990 return BinaryOperator::Create(BOpc, CmpP, CmpQ);
1991 }
1992
1993 // Are we using xors to bitwise check for a pair of (in)equalities? Convert to
1994 // a shorter form that has more potential to be folded even further.
1995 Value *X1, *X2, *X3, *X4;
1996 if (match(OrOp0, m_OneUse(m_Xor(m_Value(X1), m_Value(X2)))) &&
1997 match(OrOp1, m_OneUse(m_Xor(m_Value(X3), m_Value(X4))))) {
1998 // ((X1 ^ X2) || (X3 ^ X4)) == 0 --> (X1 == X2) && (X3 == X4)
1999 // ((X1 ^ X2) || (X3 ^ X4)) != 0 --> (X1 != X2) || (X3 != X4)
2000 Value *Cmp12 = Builder.CreateICmp(Pred, X1, X2);
2001 Value *Cmp34 = Builder.CreateICmp(Pred, X3, X4);
2002 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2003 return BinaryOperator::Create(BOpc, Cmp12, Cmp34);
2004 }
2005
2006 return nullptr;
2007}
2008
2009/// Fold icmp (mul X, Y), C.
2012 const APInt &C) {
2013 ICmpInst::Predicate Pred = Cmp.getPredicate();
2014 Type *MulTy = Mul->getType();
2015 Value *X = Mul->getOperand(0);
2016
2017 // If there's no overflow:
2018 // X * X == 0 --> X == 0
2019 // X * X != 0 --> X != 0
2020 if (Cmp.isEquality() && C.isZero() && X == Mul->getOperand(1) &&
2021 (Mul->hasNoUnsignedWrap() || Mul->hasNoSignedWrap()))
2022 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2023
2024 const APInt *MulC;
2025 if (!match(Mul->getOperand(1), m_APInt(MulC)))
2026 return nullptr;
2027
2028 // If this is a test of the sign bit and the multiply is sign-preserving with
2029 // a constant operand, use the multiply LHS operand instead:
2030 // (X * +MulC) < 0 --> X < 0
2031 // (X * -MulC) < 0 --> X > 0
2032 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2033 if (MulC->isNegative())
2034 Pred = ICmpInst::getSwappedPredicate(Pred);
2035 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2036 }
2037
2038 if (MulC->isZero())
2039 return nullptr;
2040
2041 // If the multiply does not wrap or the constant is odd, try to divide the
2042 // compare constant by the multiplication factor.
2043 if (Cmp.isEquality()) {
2044 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2045 if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
2046 Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
2047 return new ICmpInst(Pred, X, NewC);
2048 }
2049
2050 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2051 // correct to transform if MulC * N == C including overflow. I.e with i8
2052 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2053 // miss that case.
2054 if (C.urem(*MulC).isZero()) {
2055 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2056 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2057 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2058 Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
2059 return new ICmpInst(Pred, X, NewC);
2060 }
2061 }
2062 }
2063
2064 if (!Mul->hasNoSignedWrap() && !Mul->hasNoUnsignedWrap())
2065 return nullptr;
2066
2067 // With a matching no-overflow guarantee, fold the constants:
2068 // (X * MulC) < C --> X < (C / MulC)
2069 // (X * MulC) > C --> X > (C / MulC)
2070 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2071 Constant *NewC = nullptr;
2072 if (Mul->hasNoSignedWrap()) {
2073 // MININT / -1 --> overflow.
2074 if (C.isMinSignedValue() && MulC->isAllOnes())
2075 return nullptr;
2076 if (MulC->isNegative())
2077 Pred = ICmpInst::getSwappedPredicate(Pred);
2078
2079 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE)
2080 NewC = ConstantInt::get(
2082 if (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT)
2083 NewC = ConstantInt::get(
2085 } else {
2086 assert(Mul->hasNoUnsignedWrap() && "Expected mul nuw");
2087 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)
2088 NewC = ConstantInt::get(
2090 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)
2091 NewC = ConstantInt::get(
2093 }
2094
2095 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2096}
2097
2098/// Fold icmp (shl 1, Y), C.
2100 const APInt &C) {
2101 Value *Y;
2102 if (!match(Shl, m_Shl(m_One(), m_Value(Y))))
2103 return nullptr;
2104
2105 Type *ShiftType = Shl->getType();
2106 unsigned TypeBits = C.getBitWidth();
2107 bool CIsPowerOf2 = C.isPowerOf2();
2108 ICmpInst::Predicate Pred = Cmp.getPredicate();
2109 if (Cmp.isUnsigned()) {
2110 // (1 << Y) pred C -> Y pred Log2(C)
2111 if (!CIsPowerOf2) {
2112 // (1 << Y) < 30 -> Y <= 4
2113 // (1 << Y) <= 30 -> Y <= 4
2114 // (1 << Y) >= 30 -> Y > 4
2115 // (1 << Y) > 30 -> Y > 4
2116 if (Pred == ICmpInst::ICMP_ULT)
2117 Pred = ICmpInst::ICMP_ULE;
2118 else if (Pred == ICmpInst::ICMP_UGE)
2119 Pred = ICmpInst::ICMP_UGT;
2120 }
2121
2122 unsigned CLog2 = C.logBase2();
2123 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2124 } else if (Cmp.isSigned()) {
2125 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2126 // (1 << Y) > 0 -> Y != 31
2127 // (1 << Y) > C -> Y != 31 if C is negative.
2128 if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
2129 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2130
2131 // (1 << Y) < 0 -> Y == 31
2132 // (1 << Y) < 1 -> Y == 31
2133 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2134 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2135 if (Pred == ICmpInst::ICMP_SLT && (C-1).sle(0))
2136 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2137 }
2138
2139 return nullptr;
2140}
2141
2142/// Fold icmp (shl X, Y), C.
2144 BinaryOperator *Shl,
2145 const APInt &C) {
2146 const APInt *ShiftVal;
2147 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2148 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2149
2150 const APInt *ShiftAmt;
2151 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2152 return foldICmpShlOne(Cmp, Shl, C);
2153
2154 // Check that the shift amount is in range. If not, don't perform undefined
2155 // shifts. When the shift is visited, it will be simplified.
2156 unsigned TypeBits = C.getBitWidth();
2157 if (ShiftAmt->uge(TypeBits))
2158 return nullptr;
2159
2160 ICmpInst::Predicate Pred = Cmp.getPredicate();
2161 Value *X = Shl->getOperand(0);
2162 Type *ShType = Shl->getType();
2163
2164 // NSW guarantees that we are only shifting out sign bits from the high bits,
2165 // so we can ASHR the compare constant without needing a mask and eliminate
2166 // the shift.
2167 if (Shl->hasNoSignedWrap()) {
2168 if (Pred == ICmpInst::ICMP_SGT) {
2169 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2170 APInt ShiftedC = C.ashr(*ShiftAmt);
2171 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2172 }
2173 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2174 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2175 APInt ShiftedC = C.ashr(*ShiftAmt);
2176 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2177 }
2178 if (Pred == ICmpInst::ICMP_SLT) {
2179 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2180 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2181 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2182 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2183 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2184 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2185 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2186 }
2187 // If this is a signed comparison to 0 and the shift is sign preserving,
2188 // use the shift LHS operand instead; isSignTest may change 'Pred', so only
2189 // do that if we're sure to not continue on in this function.
2190 if (isSignTest(Pred, C))
2191 return new ICmpInst(Pred, X, Constant::getNullValue(ShType));
2192 }
2193
2194 // NUW guarantees that we are only shifting out zero bits from the high bits,
2195 // so we can LSHR the compare constant without needing a mask and eliminate
2196 // the shift.
2197 if (Shl->hasNoUnsignedWrap()) {
2198 if (Pred == ICmpInst::ICMP_UGT) {
2199 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2200 APInt ShiftedC = C.lshr(*ShiftAmt);
2201 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2202 }
2203 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2204 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2205 APInt ShiftedC = C.lshr(*ShiftAmt);
2206 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2207 }
2208 if (Pred == ICmpInst::ICMP_ULT) {
2209 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2210 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2211 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2212 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2213 assert(C.ugt(0) && "ult 0 should have been eliminated");
2214 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2215 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2216 }
2217 }
2218
2219 if (Cmp.isEquality() && Shl->hasOneUse()) {
2220 // Strength-reduce the shift into an 'and'.
2221 Constant *Mask = ConstantInt::get(
2222 ShType,
2223 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2224 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2225 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2226 return new ICmpInst(Pred, And, LShrC);
2227 }
2228
2229 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2230 bool TrueIfSigned = false;
2231 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2232 // (X << 31) <s 0 --> (X & 1) != 0
2233 Constant *Mask = ConstantInt::get(
2234 ShType,
2235 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2236 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2237 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2238 And, Constant::getNullValue(ShType));
2239 }
2240
2241 // Simplify 'shl' inequality test into 'and' equality test.
2242 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2243 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2244 if ((C + 1).isPowerOf2() &&
2245 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2246 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2247 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2249 And, Constant::getNullValue(ShType));
2250 }
2251 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2252 if (C.isPowerOf2() &&
2253 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2254 Value *And =
2255 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2256 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2258 And, Constant::getNullValue(ShType));
2259 }
2260 }
2261
2262 // Transform (icmp pred iM (shl iM %v, N), C)
2263 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2264 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2265 // This enables us to get rid of the shift in favor of a trunc that may be
2266 // free on the target. It has the additional benefit of comparing to a
2267 // smaller constant that may be more target-friendly.
2268 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2269 if (Shl->hasOneUse() && Amt != 0 && C.countTrailingZeros() >= Amt &&
2270 DL.isLegalInteger(TypeBits - Amt)) {
2271 Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt);
2272 if (auto *ShVTy = dyn_cast<VectorType>(ShType))
2273 TruncTy = VectorType::get(TruncTy, ShVTy->getElementCount());
2274 Constant *NewC =
2275 ConstantInt::get(TruncTy, C.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2276 return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC);
2277 }
2278
2279 return nullptr;
2280}
2281
2282/// Fold icmp ({al}shr X, Y), C.
2284 BinaryOperator *Shr,
2285 const APInt &C) {
2286 // An exact shr only shifts out zero bits, so:
2287 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2288 Value *X = Shr->getOperand(0);
2289 CmpInst::Predicate Pred = Cmp.getPredicate();
2290 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2291 return new ICmpInst(Pred, X, Cmp.getOperand(1));
2292
2293 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2294 const APInt *ShiftValC;
2295 if (match(X, m_APInt(ShiftValC))) {
2296 if (Cmp.isEquality())
2297 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2298
2299 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2300 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2301 bool TrueIfSigned;
2302 if (!IsAShr && ShiftValC->isNegative() &&
2303 isSignBitCheck(Pred, C, TrueIfSigned))
2304 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2305 Shr->getOperand(1),
2306 ConstantInt::getNullValue(X->getType()));
2307
2308 // If the shifted constant is a power-of-2, test the shift amount directly:
2309 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2310 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2311 if (!IsAShr && ShiftValC->isPowerOf2() &&
2312 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2313 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2314 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2315 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2316
2317 unsigned CmpLZ =
2318 IsUGT ? C.countLeadingZeros() : (C - 1).countLeadingZeros();
2319 unsigned ShiftLZ = ShiftValC->countLeadingZeros();
2320 Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2321 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2322 return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2323 }
2324 }
2325
2326 const APInt *ShiftAmtC;
2327 if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2328 return nullptr;
2329
2330 // Check that the shift amount is in range. If not, don't perform undefined
2331 // shifts. When the shift is visited it will be simplified.
2332 unsigned TypeBits = C.getBitWidth();
2333 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2334 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2335 return nullptr;
2336
2337 bool IsExact = Shr->isExact();
2338 Type *ShrTy = Shr->getType();
2339 // TODO: If we could guarantee that InstSimplify would handle all of the
2340 // constant-value-based preconditions in the folds below, then we could assert
2341 // those conditions rather than checking them. This is difficult because of
2342 // undef/poison (PR34838).
2343 if (IsAShr) {
2344 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2345 // When ShAmtC can be shifted losslessly:
2346 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2347 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2348 APInt ShiftedC = C.shl(ShAmtVal);
2349 if (ShiftedC.ashr(ShAmtVal) == C)
2350 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2351 }
2352 if (Pred == CmpInst::ICMP_SGT) {
2353 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2354 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2355 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2356 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2357 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2358 }
2359 if (Pred == CmpInst::ICMP_UGT) {
2360 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2361 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2362 // clause accounts for that pattern.
2363 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2364 if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2365 (C + 1).shl(ShAmtVal).isMinSignedValue())
2366 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2367 }
2368
2369 // If the compare constant has significant bits above the lowest sign-bit,
2370 // then convert an unsigned cmp to a test of the sign-bit:
2371 // (ashr X, ShiftC) u> C --> X s< 0
2372 // (ashr X, ShiftC) u< C --> X s> -1
2373 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2374 if (Pred == CmpInst::ICMP_UGT) {
2375 return new ICmpInst(CmpInst::ICMP_SLT, X,
2377 }
2378 if (Pred == CmpInst::ICMP_ULT) {
2379 return new ICmpInst(CmpInst::ICMP_SGT, X,
2381 }
2382 }
2383 } else {
2384 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2385 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2386 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2387 APInt ShiftedC = C.shl(ShAmtVal);
2388 if (ShiftedC.lshr(ShAmtVal) == C)
2389 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2390 }
2391 if (Pred == CmpInst::ICMP_UGT) {
2392 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2393 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2394 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2395 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2396 }
2397 }
2398
2399 if (!Cmp.isEquality())
2400 return nullptr;
2401
2402 // Handle equality comparisons of shift-by-constant.
2403
2404 // If the comparison constant changes with the shift, the comparison cannot
2405 // succeed (bits of the comparison constant cannot match the shifted value).
2406 // This should be known by InstSimplify and already be folded to true/false.
2407 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2408 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2409 "Expected icmp+shr simplify did not occur.");
2410
2411 // If the bits shifted out are known zero, compare the unshifted value:
2412 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2413 if (Shr->isExact())
2414 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2415
2416 if (C.isZero()) {
2417 // == 0 is u< 1.
2418 if (Pred == CmpInst::ICMP_EQ)
2419 return new ICmpInst(CmpInst::ICMP_ULT, X,
2420 ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal)));
2421 else
2422 return new ICmpInst(CmpInst::ICMP_UGT, X,
2423 ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal) - 1));
2424 }
2425
2426 if (Shr->hasOneUse()) {
2427 // Canonicalize the shift into an 'and':
2428 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2429 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2430 Constant *Mask = ConstantInt::get(ShrTy, Val);
2431 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2432 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2433 }
2434
2435 return nullptr;
2436}
2437
2439 BinaryOperator *SRem,
2440 const APInt &C) {
2441 // Match an 'is positive' or 'is negative' comparison of remainder by a
2442 // constant power-of-2 value:
2443 // (X % pow2C) sgt/slt 0
2444 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2445 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2446 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2447 return nullptr;
2448
2449 // TODO: The one-use check is standard because we do not typically want to
2450 // create longer instruction sequences, but this might be a special-case
2451 // because srem is not good for analysis or codegen.
2452 if (!SRem->hasOneUse())
2453 return nullptr;
2454
2455 const APInt *DivisorC;
2456 if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2457 return nullptr;
2458
2459 // For cmp_sgt/cmp_slt only zero valued C is handled.
2460 // For cmp_eq/cmp_ne only positive valued C is handled.
2461 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2462 !C.isZero()) ||
2463 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2464 !C.isStrictlyPositive()))
2465 return nullptr;
2466
2467 // Mask off the sign bit and the modulo bits (low-bits).
2468 Type *Ty = SRem->getType();
2470 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2471 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2472
2473 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2474 return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2475
2476 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2477 // bit is set. Example:
2478 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2479 if (Pred == ICmpInst::ICMP_SGT)
2481
2482 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2483 // bit is set. Example:
2484 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2485 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2486}
2487
2488/// Fold icmp (udiv X, Y), C.
2490 BinaryOperator *UDiv,
2491 const APInt &C) {
2492 ICmpInst::Predicate Pred = Cmp.getPredicate();
2493 Value *X = UDiv->getOperand(0);
2494 Value *Y = UDiv->getOperand(1);
2495 Type *Ty = UDiv->getType();
2496
2497 const APInt *C2;
2498 if (!match(X, m_APInt(C2)))
2499 return nullptr;
2500
2501 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2502
2503 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2504 if (Pred == ICmpInst::ICMP_UGT) {
2505 assert(!C.isMaxValue() &&
2506 "icmp ugt X, UINT_MAX should have been simplified already.");
2507 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2508 ConstantInt::get(Ty, C2->udiv(C + 1)));
2509 }
2510
2511 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2512 if (Pred == ICmpInst::ICMP_ULT) {
2513 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2514 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2515 ConstantInt::get(Ty, C2->udiv(C)));
2516 }
2517
2518 return nullptr;
2519}
2520
2521/// Fold icmp ({su}div X, Y), C.
2523 BinaryOperator *Div,
2524 const APInt &C) {
2525 ICmpInst::Predicate Pred = Cmp.getPredicate();
2526 Value *X = Div->getOperand(0);
2527 Value *Y = Div->getOperand(1);
2528 Type *Ty = Div->getType();
2529 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2530
2531 // If unsigned division and the compare constant is bigger than
2532 // UMAX/2 (negative), there's only one pair of values that satisfies an
2533 // equality check, so eliminate the division:
2534 // (X u/ Y) == C --> (X == C) && (Y == 1)
2535 // (X u/ Y) != C --> (X != C) || (Y != 1)
2536 // Similarly, if signed division and the compare constant is exactly SMIN:
2537 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2538 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2539 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2540 (!DivIsSigned || C.isMinSignedValue())) {
2541 Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2542 Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2543 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2544 return BinaryOperator::Create(Logic, XBig, YOne);
2545 }
2546
2547 // Fold: icmp pred ([us]div X, C2), C -> range test
2548 // Fold this div into the comparison, producing a range check.
2549 // Determine, based on the divide type, what the range is being
2550 // checked. If there is an overflow on the low or high side, remember
2551 // it, otherwise compute the range [low, hi) bounding the new value.
2552 // See: InsertRangeTest above for the kinds of replacements possible.
2553 const APInt *C2;
2554 if (!match(Y, m_APInt(C2)))
2555 return nullptr;
2556
2557 // FIXME: If the operand types don't match the type of the divide
2558 // then don't attempt this transform. The code below doesn't have the
2559 // logic to deal with a signed divide and an unsigned compare (and
2560 // vice versa). This is because (x /s C2) <s C produces different
2561 // results than (x /s C2) <u C or (x /u C2) <s C or even
2562 // (x /u C2) <u C. Simply casting the operands and result won't
2563 // work. :( The if statement below tests that condition and bails
2564 // if it finds it.
2565 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
2566 return nullptr;
2567
2568 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2569 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2570 // division-by-constant cases should be present, we can not assert that they
2571 // have happened before we reach this icmp instruction.
2572 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2573 return nullptr;
2574
2575 // Compute Prod = C * C2. We are essentially solving an equation of
2576 // form X / C2 = C. We solve for X by multiplying C2 and C.
2577 // By solving for X, we can turn this into a range check instead of computing
2578 // a divide.
2579 APInt Prod = C * *C2;
2580
2581 // Determine if the product overflows by seeing if the product is not equal to
2582 // the divide. Make sure we do the same kind of divide as in the LHS
2583 // instruction that we're folding.
2584 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2585
2586 // If the division is known to be exact, then there is no remainder from the
2587 // divide, so the covered range size is unit, otherwise it is the divisor.
2588 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2589
2590 // Figure out the interval that is being checked. For example, a comparison
2591 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2592 // Compute this interval based on the constants involved and the signedness of
2593 // the compare/divide. This computes a half-open interval, keeping track of
2594 // whether either value in the interval overflows. After analysis each
2595 // overflow variable is set to 0 if it's corresponding bound variable is valid
2596 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2597 int LoOverflow = 0, HiOverflow = 0;
2598 APInt LoBound, HiBound;
2599
2600 if (!DivIsSigned) { // udiv
2601 // e.g. X/5 op 3 --> [15, 20)
2602 LoBound = Prod;
2603 HiOverflow = LoOverflow = ProdOV;
2604 if (!HiOverflow) {
2605 // If this is not an exact divide, then many values in the range collapse
2606 // to the same result value.
2607 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2608 }
2609 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2610 if (C.isZero()) { // (X / pos) op 0
2611 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2612 LoBound = -(RangeSize - 1);
2613 HiBound = RangeSize;
2614 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2615 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2616 HiOverflow = LoOverflow = ProdOV;
2617 if (!HiOverflow)
2618 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2619 } else { // (X / pos) op neg
2620 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2621 HiBound = Prod + 1;
2622 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2623 if (!LoOverflow) {
2624 APInt DivNeg = -RangeSize;
2625 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2626 }
2627 }
2628 } else if (C2->isNegative()) { // Divisor is < 0.
2629 if (Div->isExact())
2630 RangeSize.negate();
2631 if (C.isZero()) { // (X / neg) op 0
2632 // e.g. X/-5 op 0 --> [-4, 5)
2633 LoBound = RangeSize + 1;
2634 HiBound = -RangeSize;
2635 if (HiBound == *C2) { // -INTMIN = INTMIN
2636 HiOverflow = 1; // [INTMIN+1, overflow)
2637 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2638 }
2639 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2640 // e.g. X/-5 op 3 --> [-19, -14)
2641 HiBound = Prod + 1;
2642 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2643 if (!LoOverflow)
2644 LoOverflow =
2645 addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
2646 } else { // (X / neg) op neg
2647 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2648 LoOverflow = HiOverflow = ProdOV;
2649 if (!HiOverflow)
2650 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2651 }
2652
2653 // Dividing by a negative swaps the condition. LT <-> GT
2654 Pred = ICmpInst::getSwappedPredicate(Pred);
2655 }
2656
2657 switch (Pred) {
2658 default:
2659 llvm_unreachable("Unhandled icmp predicate!");
2660 case ICmpInst::ICMP_EQ:
2661 if (LoOverflow && HiOverflow)
2662 return replaceInstUsesWith(Cmp, Builder.getFalse());
2663 if (HiOverflow)
2664 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2665 X, ConstantInt::get(Ty, LoBound));
2666 if (LoOverflow)
2667 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2668 X, ConstantInt::get(Ty, HiBound));
2669 return replaceInstUsesWith(
2670 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
2671 case ICmpInst::ICMP_NE:
2672 if (LoOverflow && HiOverflow)
2673 return replaceInstUsesWith(Cmp, Builder.getTrue());
2674 if (HiOverflow)
2675 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2676 X, ConstantInt::get(Ty, LoBound));
2677 if (LoOverflow)
2678 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2679 X, ConstantInt::get(Ty, HiBound));
2680 return replaceInstUsesWith(
2681 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
2682 case ICmpInst::ICMP_ULT:
2683 case ICmpInst::ICMP_SLT:
2684 if (LoOverflow == +1) // Low bound is greater than input range.
2685 return replaceInstUsesWith(Cmp, Builder.getTrue());
2686 if (LoOverflow == -1) // Low bound is less than input range.
2687 return replaceInstUsesWith(Cmp, Builder.getFalse());
2688 return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
2689 case ICmpInst::ICMP_UGT:
2690 case ICmpInst::ICMP_SGT:
2691 if (HiOverflow == +1) // High bound greater than input range.
2692 return replaceInstUsesWith(Cmp, Builder.getFalse());
2693 if (HiOverflow == -1) // High bound less than input range.
2694 return replaceInstUsesWith(Cmp, Builder.getTrue());
2695 if (Pred == ICmpInst::ICMP_UGT)
2696 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
2697 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
2698 }
2699
2700 return nullptr;
2701}
2702
2703/// Fold icmp (sub X, Y), C.
2705 BinaryOperator *Sub,
2706 const APInt &C) {
2707 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
2708 ICmpInst::Predicate Pred = Cmp.getPredicate();
2709 Type *Ty = Sub->getType();
2710
2711 // (SubC - Y) == C) --> Y == (SubC - C)
2712 // (SubC - Y) != C) --> Y != (SubC - C)
2713 Constant *SubC;
2714 if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
2715 return new ICmpInst(Pred, Y,
2717 }
2718
2719 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
2720 const APInt *C2;
2721 APInt SubResult;
2722 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
2723 bool HasNSW = Sub->hasNoSignedWrap();
2724 bool HasNUW = Sub->hasNoUnsignedWrap();
2725 if (match(X, m_APInt(C2)) &&
2726 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
2727 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
2728 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
2729
2730 // X - Y == 0 --> X == Y.
2731 // X - Y != 0 --> X != Y.
2732 // TODO: We allow this with multiple uses as long as the other uses are not
2733 // in phis. The phi use check is guarding against a codegen regression
2734 // for a loop test. If the backend could undo this (and possibly
2735 // subsequent transforms), we would not need this hack.
2736 if (Cmp.isEquality() && C.isZero() &&
2737 none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
2738 return new ICmpInst(Pred, X, Y);
2739
2740 // The following transforms are only worth it if the only user of the subtract
2741 // is the icmp.
2742 // TODO: This is an artificial restriction for all of the transforms below
2743 // that only need a single replacement icmp. Can these use the phi test
2744 // like the transform above here?
2745 if (!Sub->hasOneUse())
2746 return nullptr;
2747
2748 if (Sub->hasNoSignedWrap()) {
2749 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
2750 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
2751 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
2752
2753 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
2754 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
2755 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
2756
2757 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
2758 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
2759 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
2760
2761 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
2762 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
2763 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
2764 }
2765
2766 if (!match(X, m_APInt(C2)))
2767 return nullptr;
2768
2769 // C2 - Y <u C -> (Y | (C - 1)) == C2
2770 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
2771 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
2772 (*C2 & (C - 1)) == (C - 1))
2773 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
2774
2775 // C2 - Y >u C -> (Y | C) != C2
2776 // iff C2 & C == C and C + 1 is a power of 2
2777 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
2778 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
2779
2780 // We have handled special cases that reduce.
2781 // Canonicalize any remaining sub to add as:
2782 // (C2 - Y) > C --> (Y + ~C2) < ~C
2783 Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
2784 HasNUW, HasNSW);
2785 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
2786}
2787
2788/// Fold icmp (add X, Y), C.
2791 const APInt &C) {
2792 Value *Y = Add->getOperand(1);
2793 const APInt *C2;
2794 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
2795 return nullptr;
2796
2797 // Fold icmp pred (add X, C2), C.
2798 Value *X = Add->getOperand(0);
2799 Type *Ty = Add->getType();
2800 const CmpInst::Predicate Pred = Cmp.getPredicate();
2801
2802 // If the add does not wrap, we can always adjust the compare by subtracting
2803 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
2804 // are canonicalized to SGT/SLT/UGT/ULT.
2805 if ((Add->hasNoSignedWrap() &&
2806 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) ||
2807 (Add->hasNoUnsignedWrap() &&
2808 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) {
2809 bool Overflow;
2810 APInt NewC =
2811 Cmp.isSigned() ? C.ssub_ov(*C2, Overflow) : C.usub_ov(*C2, Overflow);
2812 // If there is overflow, the result must be true or false.
2813 // TODO: Can we assert there is no overflow because InstSimplify always
2814 // handles those cases?
2815 if (!Overflow)
2816 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
2817 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
2818 }
2819
2820 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
2821 const APInt &Upper = CR.getUpper();
2822 const APInt &Lower = CR.getLower();
2823 if (Cmp.isSigned()) {
2824 if (Lower.isSignMask())
2826 if (Upper.isSignMask())
2828 } else {
2829 if (Lower.isMinValue())
2831 if (Upper.isMinValue())
2833 }
2834
2835 // This set of folds is intentionally placed after folds that use no-wrapping
2836 // flags because those folds are likely better for later analysis/codegen.
2839
2840 // Fold compare with offset to opposite sign compare if it eliminates offset:
2841 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
2842 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
2843 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
2844
2845 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
2846 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
2847 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
2848
2849 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
2850 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
2851 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
2852
2853 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
2854 if (Pred == CmpInst::ICMP_SLT && C == *C2)
2855 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
2856
2857 // (X + -1) <u C --> X <=u C (if X is never null)
2858 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
2859 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
2860 if (llvm::isKnownNonZero(X, DL, 0, Q.AC, Q.CxtI, Q.DT))
2861 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
2862 }
2863
2864 if (!Add->hasOneUse())
2865 return nullptr;
2866
2867 // X+C <u C2 -> (X & -C2) == C
2868 // iff C & (C2-1) == 0
2869 // C2 is a power of 2
2870 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
2872 ConstantExpr::getNeg(cast<Constant>(Y)));
2873
2874 // X+C >u C2 -> (X & ~C2) != C
2875 // iff C & C2 == 0
2876 // C2+1 is a power of 2
2877 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
2879 ConstantExpr::getNeg(cast<Constant>(Y)));
2880
2881 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
2882 // to the ult form.
2883 // X+C2 >u C -> X+(C2-C-1) <u ~C
2884 if (Pred == ICmpInst::ICMP_UGT)
2885 return new ICmpInst(ICmpInst::ICMP_ULT,
2886 Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
2887 ConstantInt::get(Ty, ~C));
2888
2889 return nullptr;
2890}
2891
2893 Value *&RHS, ConstantInt *&Less,
2894 ConstantInt *&Equal,
2895 ConstantInt *&Greater) {
2896 // TODO: Generalize this to work with other comparison idioms or ensure
2897 // they get canonicalized into this form.
2898
2899 // select i1 (a == b),
2900 // i32 Equal,
2901 // i32 (select i1 (a < b), i32 Less, i32 Greater)
2902 // where Equal, Less and Greater are placeholders for any three constants.
2903 ICmpInst::Predicate PredA;
2904 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
2905 !ICmpInst::isEquality(PredA))
2906 return false;
2907 Value *EqualVal = SI->getTrueValue();
2908 Value *UnequalVal = SI->getFalseValue();
2909 // We still can get non-canonical predicate here, so canonicalize.
2910 if (PredA == ICmpInst::ICMP_NE)
2911 std::swap(EqualVal, UnequalVal);
2912 if (!match(EqualVal, m_ConstantInt(Equal)))
2913 return false;
2914 ICmpInst::Predicate PredB;
2915 Value *LHS2, *RHS2;
2916 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
2917 m_ConstantInt(Less), m_ConstantInt(Greater))))
2918 return false;
2919 // We can get predicate mismatch here, so canonicalize if possible:
2920 // First, ensure that 'LHS' match.
2921 if (LHS2 != LHS) {
2922 // x sgt y <--> y slt x
2923 std::swap(LHS2, RHS2);
2924 PredB = ICmpInst::getSwappedPredicate(PredB);
2925 }
2926 if (LHS2 != LHS)
2927 return false;
2928 // We also need to canonicalize 'RHS'.
2929 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
2930 // x sgt C-1 <--> x sge C <--> not(x slt C)
2931 auto FlippedStrictness =
2933 PredB, cast<Constant>(RHS2));
2934 if (!FlippedStrictness)
2935 return false;
2936 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
2937 "basic correctness failure");
2938 RHS2 = FlippedStrictness->second;
2939 // And kind-of perform the result swap.
2940 std::swap(Less, Greater);
2941 PredB = ICmpInst::ICMP_SLT;
2942 }
2943 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
2944}
2945
2948 ConstantInt *C) {
2949
2950 assert(C && "Cmp RHS should be a constant int!");
2951 // If we're testing a constant value against the result of a three way
2952 // comparison, the result can be expressed directly in terms of the
2953 // original values being compared. Note: We could possibly be more
2954 // aggressive here and remove the hasOneUse test. The original select is
2955 // really likely to simplify or sink when we remove a test of the result.
2956 Value *OrigLHS, *OrigRHS;
2957 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
2958 if (Cmp.hasOneUse() &&
2959 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
2960 C3GreaterThan)) {
2961 assert(C1LessThan && C2Equal && C3GreaterThan);
2962
2963 bool TrueWhenLessThan =
2964 ConstantExpr::getCompare(Cmp.getPredicate(), C1LessThan, C)
2965 ->isAllOnesValue();
2966 bool TrueWhenEqual =
2967 ConstantExpr::getCompare(Cmp.getPredicate(), C2Equal, C)
2968 ->isAllOnesValue();
2969 bool TrueWhenGreaterThan =
2970 ConstantExpr::getCompare(Cmp.getPredicate(), C3GreaterThan, C)
2971 ->isAllOnesValue();
2972
2973 // This generates the new instruction that will replace the original Cmp
2974 // Instruction. Instead of enumerating the various combinations when
2975 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
2976 // false, we rely on chaining of ORs and future passes of InstCombine to
2977 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
2978
2979 // When none of the three constants satisfy the predicate for the RHS (C),
2980 // the entire original Cmp can be simplified to a false.
2982 if (TrueWhenLessThan)
2984 OrigLHS, OrigRHS));
2985 if (TrueWhenEqual)
2987 OrigLHS, OrigRHS));
2988 if (TrueWhenGreaterThan)
2990 OrigLHS, OrigRHS));
2991
2992 return replaceInstUsesWith(Cmp, Cond);
2993 }
2994 return nullptr;
2995}
2996
2998 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
2999 if (!Bitcast)
3000 return nullptr;
3001
3002 ICmpInst::Predicate Pred = Cmp.getPredicate();
3003 Value *Op1 = Cmp.getOperand(1);
3004 Value *BCSrcOp = Bitcast->getOperand(0);
3005 Type *SrcType = Bitcast->getSrcTy();
3006 Type *DstType = Bitcast->getType();
3007
3008 // Make sure the bitcast doesn't change between scalar and vector and
3009 // doesn't change the number of vector elements.
3010 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3011 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3012 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3013 Value *X;
3014 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
3015 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3016 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3017 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3018 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3019 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3020 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3021 match(Op1, m_Zero()))
3022 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3023
3024 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3025 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
3026 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
3027
3028 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3029 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
3030 return new ICmpInst(Pred, X,
3031 ConstantInt::getAllOnesValue(X->getType()));
3032 }
3033
3034 // Zero-equality checks are preserved through unsigned floating-point casts:
3035 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3036 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3037 if (match(BCSrcOp, m_UIToFP(m_Value(X))))
3038 if (Cmp.isEquality() && match(Op1, m_Zero()))
3039 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3040
3041 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3042 // the FP extend/truncate because that cast does not change the sign-bit.
3043 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3044 // The sign-bit is always the most significant bit in those types.
3045 const APInt *C;
3046 bool TrueIfSigned;
3047 if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse() &&
3048 isSignBitCheck(Pred, *C, TrueIfSigned)) {
3049 if (match(BCSrcOp, m_FPExt(m_Value(X))) ||
3050 match(BCSrcOp, m_FPTrunc(m_Value(X)))) {
3051 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3052 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3053 Type *XType = X->getType();
3054
3055 // We can't currently handle Power style floating point operations here.
3056 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3057 Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
3058 if (auto *XVTy = dyn_cast<VectorType>(XType))
3059 NewType = VectorType::get(NewType, XVTy->getElementCount());
3060 Value *NewBitcast = Builder.CreateBitCast(X, NewType);
3061 if (TrueIfSigned)
3062 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3063 ConstantInt::getNullValue(NewType));
3064 else
3065 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3067 }
3068 }
3069 }
3070 }
3071
3072 // Test to see if the operands of the icmp are casted versions of other
3073 // values. If the ptr->ptr cast can be stripped off both arguments, do so.
3074 if (DstType->isPointerTy() && (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
3075 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3076 // so eliminate it as well.
3077 if (auto *BC2 = dyn_cast<BitCastInst>(Op1))
3078 Op1 = BC2->getOperand(0);
3079
3080 Op1 = Builder.CreateBitCast(Op1, SrcType);
3081 return new ICmpInst(Pred, BCSrcOp, Op1);
3082 }
3083
3084 const APInt *C;
3085 if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3086 !SrcType->isIntOrIntVectorTy())
3087 return nullptr;
3088
3089 // If this is checking if all elements of a vector compare are set or not,
3090 // invert the casted vector equality compare and test if all compare
3091 // elements are clear or not. Compare against zero is generally easier for
3092 // analysis and codegen.
3093 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3094 // Example: are all elements equal? --> are zero elements not equal?
3095 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3096 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse() &&
3097 isFreeToInvert(BCSrcOp, BCSrcOp->hasOneUse())) {
3098 Value *Cast = Builder.CreateBitCast(Builder.CreateNot(BCSrcOp), DstType);
3099 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3100 }
3101
3102 // If this is checking if all elements of an extended vector are clear or not,
3103 // compare in a narrow type to eliminate the extend:
3104 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3105 Value *X;
3106 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3107 match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3108 if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3109 Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3110 Value *NewCast = Builder.CreateBitCast(X, NewType);
3111 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3112 }
3113 }
3114
3115 // Folding: icmp <pred> iN X, C
3116 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3117 // and C is a splat of a K-bit pattern
3118 // and SC is a constant vector = <C', C', C', ..., C'>
3119 // Into:
3120 // %E = extractelement <M x iK> %vec, i32 C'
3121 // icmp <pred> iK %E, trunc(C)
3122 Value *Vec;
3123 ArrayRef<int> Mask;
3124 if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3125 // Check whether every element of Mask is the same constant
3126 if (all_equal(Mask)) {
3127 auto *VecTy = cast<VectorType>(SrcType);
3128 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3129 if (C->isSplat(EltTy->getBitWidth())) {
3130 // Fold the icmp based on the value of C
3131 // If C is M copies of an iK sized bit pattern,
3132 // then:
3133 // => %E = extractelement <N x iK> %vec, i32 Elem
3134 // icmp <pred> iK %SplatVal, <pattern>
3135 Value *Elem = Builder.getInt32(Mask[0]);
3136 Value *Extract = Builder.CreateExtractElement(Vec, Elem);
3137 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3138 return new ICmpInst(Pred, Extract, NewC);
3139 }
3140 }
3141 }
3142 return nullptr;
3143}
3144
3145/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3146/// where X is some kind of instruction.
3148 const APInt *C;
3149
3150 if (match(Cmp.getOperand(1), m_APInt(C))) {
3151 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3152 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3153 return I;
3154
3155 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3156 // For now, we only support constant integers while folding the
3157 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3158 // similar to the cases handled by binary ops above.
3159 if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3160 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3161 return I;
3162
3163 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3164 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3165 return I;
3166
3167 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3168 if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, II, *C))
3169 return I;
3170
3171 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3172 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3173 // TODO: This checks one-use, but that is not strictly necessary.
3174 Value *Cmp0 = Cmp.getOperand(0);
3175 Value *X, *Y;
3176 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3177 (match(Cmp0,
3178 m_ExtractValue<0>(m_Intrinsic<Intrinsic::ssub_with_overflow>(
3179 m_Value(X), m_Value(Y)))) ||
3180 match(Cmp0,
3181 m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
3182 m_Value(X), m_Value(Y))))))
3183 return new ICmpInst(Cmp.getPredicate(), X, Y);
3184 }
3185
3186 if (match(Cmp.getOperand(1), m_APIntAllowUndef(C)))
3188
3189 return nullptr;
3190}
3191
3192/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3193/// icmp eq/ne BO, C.
3195 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3196 // TODO: Some of these folds could work with arbitrary constants, but this
3197 // function is limited to scalar and vector splat constants.
3198 if (!Cmp.isEquality())
3199 return nullptr;
3200
3201 ICmpInst::Predicate Pred = Cmp.getPredicate();
3202 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3203 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3204 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3205
3206 switch (BO->getOpcode()) {
3207 case Instruction::SRem:
3208 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3209 if (C.isZero() && BO->hasOneUse()) {
3210 const APInt *BOC;
3211 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3212 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3213 return new ICmpInst(Pred, NewRem,
3215 }
3216 }
3217 break;
3218 case Instruction::Add: {
3219 // (A + C2) == C --> A == (C - C2)
3220 // (A + C2) != C --> A != (C - C2)
3221 // TODO: Remove the one-use limitation? See discussion in D58633.
3222 if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
3223 if (BO->hasOneUse())
3224 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
3225 } else if (C.isZero()) {
3226 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3227 // efficiently invertible, or if the add has just this one use.
3228 if (Value *NegVal = dyn_castNegVal(BOp1))
3229 return new ICmpInst(Pred, BOp0, NegVal);
3230 if (Value *NegVal = dyn_castNegVal(BOp0))
3231 return new ICmpInst(Pred, NegVal, BOp1);
3232 if (BO->hasOneUse()) {
3233 Value *Neg = Builder.CreateNeg(BOp1);
3234 Neg->takeName(BO);
3235 return new ICmpInst(Pred, BOp0, Neg);
3236 }
3237 }
3238 break;
3239 }
3240 case Instruction::Xor:
3241 if (BO->hasOneUse()) {
3242 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3243 // For the xor case, we can xor two constants together, eliminating
3244 // the explicit xor.
3245 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3246 } else if (C.isZero()) {
3247 // Replace ((xor A, B) != 0) with (A != B)
3248 return new ICmpInst(Pred, BOp0, BOp1);
3249 }
3250 }
3251 break;
3252 case Instruction::Or: {
3253 const APInt *BOC;
3254 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3255 // Comparing if all bits outside of a constant mask are set?
3256 // Replace (X | C) == -1 with (X & ~C) == ~C.
3257 // This removes the -1 constant.
3258 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
3259 Value *And = Builder.CreateAnd(BOp0, NotBOC);
3260 return new ICmpInst(Pred, And, NotBOC);
3261 }
3262 break;
3263 }
3264 case Instruction::And: {
3265 const APInt *BOC;
3266 if (match(BOp1, m_APInt(BOC))) {
3267 // If we have ((X & C) == C), turn it into ((X & C) != 0).
3268 if (C == *BOC && C.isPowerOf2())
3269 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
3271 }
3272 break;
3273 }
3274 case Instruction::UDiv:
3275 if (C.isZero()) {
3276 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3277 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3278 return new ICmpInst(NewPred, BOp1, BOp0);
3279 }
3280 break;
3281 default:
3282 break;
3283 }
3284 return nullptr;
3285}
3286
3287/// Fold an equality icmp with LLVM intrinsic and constant operand.
3289 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3290 Type *Ty = II->getType();
3291 unsigned BitWidth = C.getBitWidth();
3292 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3293
3294 switch (II->getIntrinsicID()) {
3295 case Intrinsic::abs:
3296 // abs(A) == 0 -> A == 0
3297 // abs(A) == INT_MIN -> A == INT_MIN
3298 if (C.isZero() || C.isMinSignedValue())
3299 return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3300 break;
3301
3302 case Intrinsic::bswap:
3303 // bswap(A) == C -> A == bswap(C)
3304 return new ICmpInst(Pred, II->getArgOperand(0),
3305 ConstantInt::get(Ty, C.byteSwap()));
3306
3307 case Intrinsic::ctlz:
3308 case Intrinsic::cttz: {
3309 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3310 if (C == BitWidth)
3311 return new ICmpInst(Pred, II->getArgOperand(0),
3313
3314 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3315 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3316 // Limit to one use to ensure we don't increase instruction count.
3317 unsigned Num = C.getLimitedValue(BitWidth);
3318 if (Num != BitWidth && II->hasOneUse()) {
3319 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3320 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3321 : APInt::getHighBitsSet(BitWidth, Num + 1);
3322 APInt Mask2 = IsTrailing
3325 return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
3326 ConstantInt::get(Ty, Mask2));
3327 }
3328 break;
3329 }
3330
3331 case Intrinsic::ctpop: {
3332 // popcount(A) == 0 -> A == 0 and likewise for !=
3333 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3334 bool IsZero = C.isZero();
3335 if (IsZero || C == BitWidth)
3336 return new ICmpInst(Pred, II->getArgOperand(0),
3337 IsZero ? Constant::getNullValue(Ty)
3339
3340 break;
3341 }
3342
3343 case Intrinsic::fshl:
3344 case Intrinsic::fshr:
3345 if (II->getArgOperand(0) == II->getArgOperand(1)) {
3346 const APInt *RotAmtC;
3347 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3348 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3349 if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
3350 return new ICmpInst(Pred, II->getArgOperand(0),
3351 II->getIntrinsicID() == Intrinsic::fshl
3352 ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
3353 : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
3354 }
3355 break;
3356
3357 case Intrinsic::uadd_sat: {
3358 // uadd.sat(a, b) == 0 -> (a | b) == 0
3359 if (C.isZero()) {
3361 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
3362 }
3363 break;
3364 }
3365
3366 case Intrinsic::usub_sat: {
3367 // usub.sat(a, b) == 0 -> a <= b
3368 if (C.isZero()) {
3369 ICmpInst::Predicate NewPred =
3371 return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
3372 }
3373 break;
3374 }
3375 default:
3376 break;
3377 }
3378
3379 return nullptr;
3380}
3381
3382/// Fold an icmp with LLVM intrinsics
3384 assert(Cmp.isEquality());
3385
3386 ICmpInst::Predicate Pred = Cmp.getPredicate();
3387 Value *Op0 = Cmp.getOperand(0);
3388 Value *Op1 = Cmp.getOperand(1);
3389 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
3390 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
3391 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
3392 return nullptr;
3393
3394 switch (IIOp0->getIntrinsicID()) {
3395 case Intrinsic::bswap:
3396 case Intrinsic::bitreverse:
3397 // If both operands are byte-swapped or bit-reversed, just compare the
3398 // original values.
3399 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3400 case Intrinsic::fshl:
3401 case Intrinsic::fshr:
3402 // If both operands are rotated by same amount, just compare the
3403 // original values.
3404 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
3405 break;
3406 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
3407 break;
3408 if (IIOp0->getOperand(2) != IIOp1->getOperand(2))
3409 break;
3410 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3411 default:
3412 break;
3413 }
3414
3415 return nullptr;
3416}
3417
3418/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3419/// where X is some kind of instruction and C is AllowUndef.
3420/// TODO: Move more folds which allow undef to this function.
3423 const APInt &C) {
3424 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3425 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
3426 switch (II->getIntrinsicID()) {
3427 default:
3428 break;
3429 case Intrinsic::fshl:
3430 case Intrinsic::fshr:
3431 if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
3432 // (rot X, ?) == 0/-1 --> X == 0/-1
3433 if (C.isZero() || C.isAllOnes())
3434 return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
3435 }
3436 break;
3437 }
3438 }
3439
3440 return nullptr;
3441}
3442
3443/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
3445 BinaryOperator *BO,
3446 const APInt &C) {
3447 switch (BO->getOpcode()) {
3448 case Instruction::Xor:
3449 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
3450 return I;
3451 break;
3452 case Instruction::And:
3453 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
3454 return I;
3455 break;
3456 case Instruction::Or:
3457 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
3458 return I;
3459 break;
3460 case Instruction::Mul:
3461 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
3462 return I;
3463 break;
3464 case Instruction::Shl:
3465 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
3466 return I;
3467 break;
3468 case Instruction::LShr:
3469 case Instruction::AShr:
3470 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
3471 return I;
3472 break;
3473 case Instruction::SRem:
3474 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
3475 return I;
3476 break;
3477 case Instruction::UDiv:
3478 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
3479 return I;
3480 [[fallthrough]];
3481 case Instruction::SDiv:
3482 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
3483 return I;
3484 break;
3485 case Instruction::Sub:
3486 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
3487 return I;
3488 break;
3489 case Instruction::Add:
3490 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
3491 return I;
3492 break;
3493 default:
3494 break;
3495 }
3496
3497 // TODO: These folds could be refactored to be part of the above calls.
3498 return foldICmpBinOpEqualityWithConstant(Cmp, BO, C);
3499}
3500
3501/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
3503 IntrinsicInst *II,
3504 const APInt &C) {
3505 if (Cmp.isEquality())
3506 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
3507
3508 Type *Ty = II->getType();
3509 unsigned BitWidth = C.getBitWidth();
3510 ICmpInst::Predicate Pred = Cmp.getPredicate();
3511 switch (II->getIntrinsicID()) {
3512 case Intrinsic::ctpop: {
3513 // (ctpop X > BitWidth - 1) --> X == -1
3514 Value *X = II->getArgOperand(0);
3515 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
3516 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
3518 // (ctpop X < BitWidth) --> X != -1
3519 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
3520 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
3522 break;
3523 }
3524 case Intrinsic::ctlz: {
3525 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
3526 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3527 unsigned Num = C.getLimitedValue();
3528 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
3529 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
3530 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3531 }
3532
3533 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
3534 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
3535 unsigned Num = C.getLimitedValue();
3537 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
3538 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3539 }
3540 break;
3541 }
3542 case Intrinsic::cttz: {
3543 // Limit to one use to ensure we don't increase instruction count.
3544 if (!II->hasOneUse())
3545 return nullptr;
3546
3547 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
3548 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3549 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
3550 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
3551 Builder.CreateAnd(II->getArgOperand(0), Mask),
3553 }
3554
3555 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
3556 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
3557 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
3558 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
3559 Builder.CreateAnd(II->getArgOperand(0), Mask),
3561 }
3562 break;
3563 }
3564 default:
3565 break;
3566 }
3567
3568 return nullptr;
3569}
3570
3571/// Handle icmp with constant (but not simple integer constant) RHS.
3573 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3574 Constant *RHSC = dyn_cast<Constant>(Op1);
3575 Instruction *LHSI = dyn_cast<Instruction>(Op0);
3576 if (!RHSC || !LHSI)
3577 return nullptr;
3578
3579 switch (LHSI->getOpcode()) {
3580 case Instruction::GetElementPtr:
3581 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3582 if (RHSC->isNullValue() &&
3583 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3584 return new ICmpInst(
3585 I.getPredicate(), LHSI->getOperand(0),
3587 break;
3588 case Instruction::PHI:
3589 // Only fold icmp into the PHI if the phi and icmp are in the same
3590 // block. If in the same block, we're encouraging jump threading. If
3591 // not, we are just pessimizing the code by making an i1 phi.
3592 if (LHSI->getParent() == I.getParent())
3593 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
3594 return NV;
3595 break;
3596 case Instruction::IntToPtr:
3597 // icmp pred inttoptr(X), null -> icmp pred X, 0
3598 if (RHSC->isNullValue() &&
3599 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
3600 return new ICmpInst(
3601 I.getPredicate(), LHSI->getOperand(0),
3603 break;
3604
3605 case Instruction::Load:
3606 // Try to optimize things like "A[i] > 4" to index computations.
3607 if (GetElementPtrInst *GEP =
3608 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
3609 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3610 if (Instruction *Res =
3611 foldCmpLoadFromIndexedGlobal(cast<LoadInst>(LHSI), GEP, GV, I))
3612 return Res;
3613 break;
3614 }
3615
3616 return nullptr;
3617}
3618
3620 SelectInst *SI, Value *RHS,
3621 const ICmpInst &I) {
3622 // Try to fold the comparison into the select arms, which will cause the
3623 // select to be converted into a logical and/or.
3624 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
3625 if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
3626 return Res;
3627 if (std::optional<bool> Impl = isImpliedCondition(
3628 SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
3629 return ConstantInt::get(I.getType(), *Impl);
3630 return nullptr;
3631 };
3632
3633 ConstantInt *CI = nullptr;
3634 Value *Op1 = SimplifyOp(SI->getOperand(1), true);
3635 if (Op1)
3636 CI = dyn_cast<ConstantInt>(Op1);
3637
3638 Value *Op2 = SimplifyOp(SI->getOperand(2), false);
3639 if (Op2)
3640 CI = dyn_cast<ConstantInt>(Op2);
3641
3642 // We only want to perform this transformation if it will not lead to
3643 // additional code. This is true if either both sides of the select
3644 // fold to a constant (in which case the icmp is replaced with a select
3645 // which will usually simplify) or this is the only user of the
3646 // select (in which case we are trading a select+icmp for a simpler
3647 // select+icmp) or all uses of the select can be replaced based on
3648 // dominance information ("Global cases").
3649 bool Transform = false;
3650 if (Op1 && Op2)
3651 Transform = true;
3652 else if (Op1 || Op2) {
3653 // Local case
3654 if (SI->hasOneUse())
3655 Transform = true;
3656 // Global cases
3657 else if (CI && !CI->isZero())
3658 // When Op1 is constant try replacing select with second operand.
3659 // Otherwise Op2 is constant and try replacing select with first
3660 // operand.
3661 Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
3662 }
3663 if (Transform) {
3664 if (!Op1)
3665 Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
3666 if (!Op2)
3667 Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
3668 return SelectInst::Create(SI->getOperand(0), Op1, Op2);
3669 }
3670
3671 return nullptr;
3672}
3673
3674/// Some comparisons can be simplified.
3675/// In this case, we are looking for comparisons that look like
3676/// a check for a lossy truncation.
3677/// Folds:
3678/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
3679/// Where Mask is some pattern that produces all-ones in low bits:
3680/// (-1 >> y)
3681/// ((-1 << y) >> y) <- non-canonical, has extra uses
3682/// ~(-1 << y)
3683/// ((1 << y) + (-1)) <- non-canonical, has extra uses
3684/// The Mask can be a constant, too.
3685/// For some predicates, the operands are commutative.
3686/// For others, x can only be on a specific side.
3688 InstCombiner::BuilderTy &Builder) {
3689 ICmpInst::Predicate SrcPred;
3690 Value *X, *M, *Y;
3691 auto m_VariableMask = m_CombineOr(
3693 m_Add(m_Shl(m_One(), m_Value()), m_AllOnes())),
3696 auto m_Mask = m_CombineOr(m_VariableMask, m_LowBitMask());
3697 if (!match(&I, m_c_ICmp(SrcPred,
3699 m_Deferred(X))))
3700 return nullptr;
3701
3702 ICmpInst::Predicate DstPred;
3703 switch (SrcPred) {
3705 // x & (-1 >> y) == x -> x u<= (-1 >> y)
3707 break;
3709 // x & (-1 >> y) != x -> x u> (-1 >> y)
3711 break;
3713 // x & (-1 >> y) u< x -> x u> (-1 >> y)
3714 // x u> x & (-1 >> y) -> x u> (-1 >> y)
3716 break;
3718 // x & (-1 >> y) u>= x -> x u<= (-1 >> y)
3719 // x u<= x & (-1 >> y) -> x u<= (-1 >> y)
3721 break;
3723 // x & (-1 >> y) s< x -> x s> (-1 >> y)
3724 // x s> x & (-1 >> y) -> x s> (-1 >> y)
3725 if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3726 return nullptr;
3727 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3728 return nullptr;
3730 break;
3732 // x & (-1 >> y) s>= x -> x s<= (-1 >> y)
3733 // x s<= x & (-1 >> y) -> x s<= (-1 >> y)
3734 if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3735 return nullptr;
3736 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3737 return nullptr;
3739 break;
3742 return nullptr;
3745 llvm_unreachable("Instsimplify took care of commut. variant");
3746 break;
3747 default:
3748 llvm_unreachable("All possible folds are handled.");
3749 }
3750
3751 // The mask value may be a vector constant that has undefined elements. But it
3752 // may not be safe to propagate those undefs into the new compare, so replace
3753 // those elements by copying an existing, defined, and safe scalar constant.
3754 Type *OpTy = M->getType();
3755 auto *VecC = dyn_cast<Constant>(M);
3756 auto *OpVTy = dyn_cast<FixedVectorType>(OpTy);
3757 if (OpVTy && VecC && VecC->containsUndefOrPoisonElement()) {
3758 Constant *SafeReplacementConstant = nullptr;
3759 for (unsigned i = 0, e = OpVTy->getNumElements(); i != e; ++i) {
3760 if (!isa<UndefValue>(VecC->getAggregateElement(i))) {
3761 SafeReplacementConstant = VecC->getAggregateElement(i);
3762 break;
3763 }
3764 }
3765 assert(SafeReplacementConstant && "Failed to find undef replacement");
3766 M = Constant::replaceUndefsWith(VecC, SafeReplacementConstant);
3767 }
3768
3769 return Builder.CreateICmp(DstPred, X, M);
3770}
3771
3772/// Some comparisons can be simplified.
3773/// In this case, we are looking for comparisons that look like
3774/// a check for a lossy signed truncation.
3775/// Folds: (MaskedBits is a constant.)
3776/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
3777/// Into:
3778/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
3779/// Where KeptBits = bitwidth(%x) - MaskedBits
3780static Value *
3782 InstCombiner::BuilderTy &Builder) {
3783 ICmpInst::Predicate SrcPred;
3784 Value *X;
3785 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
3786 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
3787 if (!match(&I, m_c_ICmp(SrcPred,
3789 m_APInt(C1))),
3790 m_Deferred(X))))
3791 return nullptr;
3792
3793 // Potential handling of non-splats: for each element:
3794 // * if both are undef, replace with constant 0.
3795 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
3796 // * if both are not undef, and are different, bailout.
3797 // * else, only one is undef, then pick the non-undef one.
3798
3799 // The shift amount must be equal.
3800 if (*C0 != *C1)
3801 return nullptr;
3802 const APInt &MaskedBits = *C0;
3803 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
3804
3805 ICmpInst::Predicate DstPred;
3806 switch (SrcPred) {
3808 // ((%x << MaskedBits) a>> MaskedBits) == %x
3809 // =>
3810 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
3812 break;
3814 // ((%x << MaskedBits) a>> MaskedBits) != %x
3815 // =>
3816 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
3818 break;
3819 // FIXME: are more folds possible?
3820 default:
3821 return nullptr;
3822 }
3823
3824 auto *XType = X->getType();
3825 const unsigned XBitWidth = XType->getScalarSizeInBits();
3826 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
3827 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
3828
3829 // KeptBits = bitwidth(%x) - MaskedBits
3830 const APInt KeptBits = BitWidth - MaskedBits;
3831 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
3832 // ICmpCst = (1 << KeptBits)
3833 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
3834 assert(ICmpCst.isPowerOf2());
3835 // AddCst = (1 << (KeptBits-1))
3836 const APInt AddCst = ICmpCst.lshr(1);
3837 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
3838
3839 // T0 = add %x, AddCst
3840 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
3841 // T1 = T0 DstPred ICmpCst
3842 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
3843
3844 return T1;
3845}
3846
3847// Given pattern:
3848// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
3849// we should move shifts to the same hand of 'and', i.e. rewrite as
3850// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
3851// We are only interested in opposite logical shifts here.
3852// One of the shifts can be truncated.
3853// If we can, we want to end up creating 'lshr' shift.
3854static Value *
3856 InstCombiner::BuilderTy &Builder) {
3857 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
3858 !I.getOperand(0)->hasOneUse())
3859 return nullptr;
3860
3861 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
3862
3863 // Look for an 'and' of two logical shifts, one of which may be truncated.
3864 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
3865 Instruction *XShift, *MaybeTruncation, *YShift;
3866 if (!match(
3867 I.getOperand(0),
3868 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
3870 m_AnyLogicalShift, m_Instruction(YShift))),
3871 m_Instruction(MaybeTruncation)))))
3872 return nullptr;
3873
3874 // We potentially looked past 'trunc', but only when matching YShift,
3875 // therefore YShift must have the widest type.
3876 Instruction *WidestShift = YShift;
3877 // Therefore XShift must have the shallowest type.
3878 // Or they both have identical types if there was no truncation.
3879 Instruction *NarrowestShift = XShift;
3880
3881 Type *WidestTy = WidestShift->getType();
3882 Type *NarrowestTy = NarrowestShift->getType();
3883 assert(NarrowestTy == I.getOperand(0)->getType() &&
3884 "We did not look past any shifts while matching XShift though.");
3885 bool HadTrunc = WidestTy != I.getOperand(0)->getType();
3886
3887 // If YShift is a 'lshr', swap the shifts around.
3888 if (match(YShift, m_LShr(m_Value(), m_Value())))
3889 std::swap(XShift, YShift);
3890
3891 // The shifts must be in opposite directions.
3892 auto XShiftOpcode = XShift->getOpcode();
3893 if (XShiftOpcode == YShift->getOpcode())
3894 return nullptr; // Do not care about same-direction shifts here.
3895
3896 Value *X, *XShAmt, *Y, *YShAmt;
3897 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
3898 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
3899
3900 // If one of the values being shifted is a constant, then we will end with
3901 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
3902 // however, we will need to ensure that we won't increase instruction count.
3903 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
3904 // At least one of the hands of the 'and' should be one-use shift.
3905 if (!match(I.getOperand(0),
3906 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
3907 return nullptr;
3908 if (HadTrunc) {
3909 // Due to the 'trunc', we will need to widen X. For that either the old
3910 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
3911 if (!MaybeTruncation->hasOneUse() &&
3912 !NarrowestShift->getOperand(1)->hasOneUse())
3913 return nullptr;
3914 }
3915 }
3916
3917 // We have two shift amounts from two different shifts. The types of those
3918 // shift amounts may not match. If that's the case let's bailout now.
3919 if (XShAmt->getType() != YShAmt->getType())
3920 return nullptr;
3921
3922 // As input, we have the following pattern:
3923 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
3924 // We want to rewrite that as:
3925 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
3926 // While we know that originally (Q+K) would not overflow
3927 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
3928 // shift amounts. so it may now overflow in smaller bitwidth.
3929 // To ensure that does not happen, we need to ensure that the total maximal
3930 // shift amount is still representable in that smaller bit width.
3931 unsigned MaximalPossibleTotalShiftAmount =
3932 (WidestTy->getScalarSizeInBits() - 1) +
3933 (NarrowestTy->getScalarSizeInBits() - 1);
3934 APInt MaximalRepresentableShiftAmount =
3936 if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
3937 return nullptr;
3938
3939 // Can we fold (XShAmt+YShAmt) ?
3940 auto *NewShAmt = dyn_cast_or_null<Constant>(
3941 simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
3942 /*isNUW=*/false, SQ.getWithInstruction(&I)));
3943 if (!NewShAmt)
3944 return nullptr;
3945 NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, WidestTy);
3946 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
3947
3948 // Is the new shift amount smaller than the bit width?
3949 // FIXME: could also rely on ConstantRange.
3950 if (!match(NewShAmt,
3952 APInt(WidestBitWidth, WidestBitWidth))))
3953 return nullptr;
3954
3955 // An extra legality check is needed if we had trunc-of-lshr.
3956 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
3957 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
3958 WidestShift]() {
3959 // It isn't obvious whether it's worth it to analyze non-constants here.
3960 // Also, let's basically give up on non-splat cases, pessimizing vectors.
3961 // If *any* of these preconditions matches we can perform the fold.
3962 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
3963 ? NewShAmt->getSplatValue()
3964 : NewShAmt;
3965 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
3966 if (NewShAmtSplat &&
3967 (NewShAmtSplat->isNullValue() ||
3968 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
3969 return true;
3970 // We consider *min* leading zeros so a single outlier
3971 // blocks the transform as opposed to allowing it.
3972 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
3973 KnownBits Known = computeKnownBits(C, SQ.DL);
3974 unsigned MinLeadZero = Known.countMinLeadingZeros();
3975 // If the value being shifted has at most lowest bit set we can fold.
3976 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
3977 if (MaxActiveBits <= 1)
3978 return true;
3979 // Precondition: NewShAmt u<= countLeadingZeros(C)
3980 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
3981 return true;
3982 }
3983 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
3984 KnownBits Known = computeKnownBits(C, SQ.DL);
3985 unsigned MinLeadZero = Known.countMinLeadingZeros();
3986 // If the value being shifted has at most lowest bit set we can fold.
3987 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
3988 if (MaxActiveBits <= 1)
3989 return true;
3990 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
3991 if (NewShAmtSplat) {
3992 APInt AdjNewShAmt =
3993 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
3994 if (AdjNewShAmt.ule(MinLeadZero))
3995 return true;
3996 }
3997 }
3998 return false; // Can't tell if it's ok.
3999 };
4000 if (!CanFold())
4001 return nullptr;
4002 }
4003
4004 // All good, we can do this fold.
4005 X = Builder.CreateZExt(X, WidestTy);
4006 Y = Builder.CreateZExt(Y, WidestTy);
4007 // The shift is the same that was for X.
4008 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
4009 ? Builder.CreateLShr(X, NewShAmt)
4010 : Builder.CreateShl(X, NewShAmt);
4011 Value *T1 = Builder.CreateAnd(T0, Y);
4012 return Builder.CreateICmp(I.getPredicate(), T1,
4013 Constant::getNullValue(WidestTy));
4014}
4015
4016/// Fold
4017/// (-1 u/ x) u< y
4018/// ((x * y) ?/ x) != y
4019/// to
4020/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
4021/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
4022/// will mean that we are looking for the opposite answer.
4025 Value *X, *Y;
4027 Instruction *Div;
4028 bool NeedNegation;
4029 // Look for: (-1 u/ x) u</u>= y
4030 if (!I.isEquality() &&
4031 match(&I, m_c_ICmp(Pred,
4033 m_Instruction(Div)),
4034 m_Value(Y)))) {
4035 Mul = nullptr;
4036
4037 // Are we checking that overflow does not happen, or does happen?
4038 switch (Pred) {
4040 NeedNegation = false;
4041 break; // OK
4043 NeedNegation = true;
4044 break; // OK
4045 default:
4046 return nullptr; // Wrong predicate.
4047 }
4048 } else // Look for: ((x * y) / x) !=/== y
4049 if (I.isEquality() &&
4050 match(&I,
4051 m_c_ICmp(Pred, m_Value(Y),
4054 m_Value(X)),
4056 m_Deferred(X))),
4057 m_Instruction(Div))))) {
4058 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
4059 } else
4060 return nullptr;
4061
4063 // If the pattern included (x * y), we'll want to insert new instructions
4064 // right before that original multiplication so that we can replace it.
4065 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
4066 if (MulHadOtherUses)
4068
4069 Function *F = Intrinsic::getDeclaration(I.getModule(),
4070 Div->getOpcode() == Instruction::UDiv
4071 ? Intrinsic::umul_with_overflow
4072 : Intrinsic::smul_with_overflow,
4073 X->getType());
4074 CallInst *Call = Builder.CreateCall(F, {X, Y}, "mul");
4075
4076 // If the multiplication was used elsewhere, to ensure that we don't leave
4077 // "duplicate" instructions, replace uses of that original multiplication
4078 // with the multiplication result from the with.overflow intrinsic.
4079 if (MulHadOtherUses)
4080 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
4081
4082 Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
4083 if (NeedNegation) // This technically increases instruction count.
4084 Res = Builder.CreateNot(Res, "mul.not.ov");
4085
4086 // If we replaced the mul, erase it. Do this after all uses of Builder,
4087 // as the mul is used as insertion point.
4088 if (MulHadOtherUses)
4090
4091 return Res;
4092}
4093
4095 CmpInst::Predicate Pred;
4096 Value *X;
4097 if (!match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X))))
4098 return nullptr;
4099
4100 if (ICmpInst::isSigned(Pred))
4101 Pred = ICmpInst::getSwappedPredicate(Pred);
4102 else if (ICmpInst::isUnsigned(Pred))
4103 Pred = ICmpInst::getSignedPredicate(Pred);
4104 // else for equality-comparisons just keep the predicate.
4105
4106 return ICmpInst::Create(Instruction::ICmp, Pred, X,
4107 Constant::getNullValue(X->getType()), I.getName());
4108}
4109
4110/// Try to fold icmp (binop), X or icmp X, (binop).
4111/// TODO: A large part of this logic is duplicated in InstSimplify's
4112/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
4113/// duplication.
4115 const SimplifyQuery &SQ) {
4117 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4118
4119 // Special logic for binary operators.
4120 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
4121 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
4122 if (!BO0 && !BO1)
4123 return nullptr;
4124
4125 if (Instruction *NewICmp = foldICmpXNegX(I))
4126 return NewICmp;
4127
4128 const CmpInst::Predicate Pred = I.getPredicate();
4129 Value *X;
4130
4131 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
4132 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
4133 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
4134 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
4135 return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
4136 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
4137 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
4138 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
4139 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
4140
4141 {
4142 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
4143 Constant *C;
4144 if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
4145 m_ImmConstant(C)))) &&
4146 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
4148 return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
4149 }
4150 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
4151 if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
4152 m_ImmConstant(C)))) &&
4153 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
4155 return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
4156 }
4157 }
4158
4159 {
4160 // Similar to above: an unsigned overflow comparison may use offset + mask:
4161 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
4162 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
4163 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
4164 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
4165 BinaryOperator *BO;
4166 const APInt *C;
4167 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
4168 match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
4170 CmpInst::Predicate NewPred =
4172 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
4173 return new ICmpInst(NewPred, Op1, Zero);
4174 }
4175
4176 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
4177 match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
4179 CmpInst::Predicate NewPred =
4181 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
4182 return new ICmpInst(NewPred, Op0, Zero);
4183 }
4184 }
4185
4186 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
4187 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
4188 NoOp0WrapProblem =
4189 ICmpInst::isEquality(Pred) ||
4190 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
4191 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
4192 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
4193 NoOp1WrapProblem =
4194 ICmpInst::isEquality(Pred) ||
4195 (CmpInst::isUnsigned(Pred) && BO1->