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