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