[InstCombine] Check nowrap flags when folding comparison of GEPs with the same base...
[llvm-project.git] / llvm / lib / Transforms / InstCombine / InstCombineCompares.cpp
bloba8a5cb2b20d7adfdb739c155c6cc22f2d8bf0fe9
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.
11 //===----------------------------------------------------------------------===//
13 #include "InstCombineInternal.h"
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/CaptureTracking.h"
18 #include "llvm/Analysis/CmpInstAnalysis.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/Utils/Local.h"
22 #include "llvm/Analysis/VectorUtils.h"
23 #include "llvm/IR/ConstantRange.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/InstrTypes.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/PatternMatch.h"
28 #include "llvm/Support/KnownBits.h"
29 #include "llvm/Transforms/InstCombine/InstCombiner.h"
30 #include <bitset>
32 using namespace llvm;
33 using namespace PatternMatch;
35 #define DEBUG_TYPE "instcombine"
37 // How many times is a select replaced by one of its operands?
38 STATISTIC(NumSel, "Number of select opts");
40 /// Compute Result = In1+In2, returning true if the result overflowed for this
41 /// type.
42 static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
43 bool IsSigned = false) {
44 bool Overflow;
45 if (IsSigned)
46 Result = In1.sadd_ov(In2, Overflow);
47 else
48 Result = In1.uadd_ov(In2, Overflow);
50 return Overflow;
53 /// Compute Result = In1-In2, returning true if the result overflowed for this
54 /// type.
55 static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
56 bool IsSigned = false) {
57 bool Overflow;
58 if (IsSigned)
59 Result = In1.ssub_ov(In2, Overflow);
60 else
61 Result = In1.usub_ov(In2, Overflow);
63 return Overflow;
66 /// Given an icmp instruction, return true if any use of this comparison is a
67 /// branch on sign bit comparison.
68 static bool hasBranchUse(ICmpInst &I) {
69 for (auto *U : I.users())
70 if (isa<BranchInst>(U))
71 return true;
72 return false;
75 /// Returns true if the exploded icmp can be expressed as a signed comparison
76 /// to zero and updates the predicate accordingly.
77 /// The signedness of the comparison is preserved.
78 /// TODO: Refactor with decomposeBitTestICmp()?
79 static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
80 if (!ICmpInst::isSigned(Pred))
81 return false;
83 if (C.isZero())
84 return ICmpInst::isRelational(Pred);
86 if (C.isOne()) {
87 if (Pred == ICmpInst::ICMP_SLT) {
88 Pred = ICmpInst::ICMP_SLE;
89 return true;
91 } else if (C.isAllOnes()) {
92 if (Pred == ICmpInst::ICMP_SGT) {
93 Pred = ICmpInst::ICMP_SGE;
94 return true;
98 return false;
101 /// This is called when we see this pattern:
102 /// cmp pred (load (gep GV, ...)), cmpcst
103 /// where GV is a global variable with a constant initializer. Try to simplify
104 /// this into some simple computation that does not need the load. For example
105 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
107 /// If AndCst is non-null, then the loaded value is masked with that constant
108 /// before doing the comparison. This handles cases like "A[i]&4 == 0".
109 Instruction *InstCombinerImpl::foldCmpLoadFromIndexedGlobal(
110 LoadInst *LI, GetElementPtrInst *GEP, GlobalVariable *GV, CmpInst &ICI,
111 ConstantInt *AndCst) {
112 if (LI->isVolatile() || LI->getType() != GEP->getResultElementType() ||
113 GV->getValueType() != GEP->getSourceElementType() || !GV->isConstant() ||
114 !GV->hasDefinitiveInitializer())
115 return nullptr;
117 Constant *Init = GV->getInitializer();
118 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
119 return nullptr;
121 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
122 // Don't blow up on huge arrays.
123 if (ArrayElementCount > MaxArraySizeForCombine)
124 return nullptr;
126 // There are many forms of this optimization we can handle, for now, just do
127 // the simple index into a single-dimensional array.
129 // Require: GEP GV, 0, i {{, constant indices}}
130 if (GEP->getNumOperands() < 3 || !isa<ConstantInt>(GEP->getOperand(1)) ||
131 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
132 isa<Constant>(GEP->getOperand(2)))
133 return nullptr;
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;
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)
144 return nullptr; // Variable index.
146 uint64_t IdxVal = Idx->getZExtValue();
147 if ((unsigned)IdxVal != IdxVal)
148 return nullptr; // Too large array index.
150 if (StructType *STy = dyn_cast<StructType>(EltTy))
151 EltTy = STy->getElementType(IdxVal);
152 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
153 if (IdxVal >= ATy->getNumElements())
154 return nullptr;
155 EltTy = ATy->getElementType();
156 } else {
157 return nullptr; // Unknown type.
160 LaterIndices.push_back(IdxVal);
163 enum { Overdefined = -3, Undefined = -2 };
165 // Variables for our state machines.
167 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
168 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
169 // and 87 is the second (and last) index. FirstTrueElement is -2 when
170 // undefined, otherwise set to the first true element. SecondTrueElement is
171 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
172 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
174 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
175 // form "i != 47 & i != 87". Same state transitions as for true elements.
176 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
178 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
179 /// define a state machine that triggers for ranges of values that the index
180 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
181 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
182 /// index in the range (inclusive). We use -2 for undefined here because we
183 /// use relative comparisons and don't want 0-1 to match -1.
184 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
186 // MagicBitvector - This is a magic bitvector where we set a bit if the
187 // comparison is true for element 'i'. If there are 64 elements or less in
188 // the array, this will fully represent all the comparison results.
189 uint64_t MagicBitvector = 0;
191 // Scan the array and see if one of our patterns matches.
192 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
193 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
194 Constant *Elt = Init->getAggregateElement(i);
195 if (!Elt)
196 return nullptr;
198 // If this is indexing an array of structures, get the structure element.
199 if (!LaterIndices.empty()) {
200 Elt = ConstantFoldExtractValueInstruction(Elt, LaterIndices);
201 if (!Elt)
202 return nullptr;
205 // If the element is masked, handle it.
206 if (AndCst) {
207 Elt = ConstantFoldBinaryOpOperands(Instruction::And, Elt, AndCst, DL);
208 if (!Elt)
209 return nullptr;
212 // Find out if the comparison would be true or false for the i'th element.
213 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
214 CompareRHS, DL, &TLI);
215 if (!C)
216 return nullptr;
218 // If the result is undef for this element, ignore it.
219 if (isa<UndefValue>(C)) {
220 // Extend range state machines to cover this element in case there is an
221 // undef in the middle of the range.
222 if (TrueRangeEnd == (int)i - 1)
223 TrueRangeEnd = i;
224 if (FalseRangeEnd == (int)i - 1)
225 FalseRangeEnd = i;
226 continue;
229 // If we can't compute the result for any of the elements, we have to give
230 // up evaluating the entire conditional.
231 if (!isa<ConstantInt>(C))
232 return nullptr;
234 // Otherwise, we know if the comparison is true or false for this element,
235 // update our state machines.
236 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
238 // State machine for single/double/range index comparison.
239 if (IsTrueForElt) {
240 // Update the TrueElement state machine.
241 if (FirstTrueElement == Undefined)
242 FirstTrueElement = TrueRangeEnd = i; // First true element.
243 else {
244 // Update double-compare state machine.
245 if (SecondTrueElement == Undefined)
246 SecondTrueElement = i;
247 else
248 SecondTrueElement = Overdefined;
250 // Update range state machine.
251 if (TrueRangeEnd == (int)i - 1)
252 TrueRangeEnd = i;
253 else
254 TrueRangeEnd = Overdefined;
256 } else {
257 // Update the FalseElement state machine.
258 if (FirstFalseElement == Undefined)
259 FirstFalseElement = FalseRangeEnd = i; // First false element.
260 else {
261 // Update double-compare state machine.
262 if (SecondFalseElement == Undefined)
263 SecondFalseElement = i;
264 else
265 SecondFalseElement = Overdefined;
267 // Update range state machine.
268 if (FalseRangeEnd == (int)i - 1)
269 FalseRangeEnd = i;
270 else
271 FalseRangeEnd = Overdefined;
275 // If this element is in range, update our magic bitvector.
276 if (i < 64 && IsTrueForElt)
277 MagicBitvector |= 1ULL << i;
279 // If all of our states become overdefined, bail out early. Since the
280 // predicate is expensive, only check it every 8 elements. This is only
281 // really useful for really huge arrays.
282 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
283 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
284 FalseRangeEnd == Overdefined)
285 return nullptr;
288 // Now that we've scanned the entire array, emit our new comparison(s). We
289 // order the state machines in complexity of the generated code.
290 Value *Idx = GEP->getOperand(2);
292 // If the index is larger than the pointer offset size of the target, truncate
293 // the index down like the GEP would do implicitly. We don't have to do this
294 // for an inbounds GEP because the index can't be out of range.
295 if (!GEP->isInBounds()) {
296 Type *PtrIdxTy = DL.getIndexType(GEP->getType());
297 unsigned OffsetSize = PtrIdxTy->getIntegerBitWidth();
298 if (Idx->getType()->getPrimitiveSizeInBits().getFixedValue() > OffsetSize)
299 Idx = Builder.CreateTrunc(Idx, PtrIdxTy);
302 // If inbounds keyword is not present, Idx * ElementSize can overflow.
303 // Let's assume that ElementSize is 2 and the wanted value is at offset 0.
304 // Then, there are two possible values for Idx to match offset 0:
305 // 0x00..00, 0x80..00.
306 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
307 // comparison is false if Idx was 0x80..00.
308 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
309 unsigned ElementSize =
310 DL.getTypeAllocSize(Init->getType()->getArrayElementType());
311 auto MaskIdx = [&](Value *Idx) {
312 if (!GEP->isInBounds() && llvm::countr_zero(ElementSize) != 0) {
313 Value *Mask = Constant::getAllOnesValue(Idx->getType());
314 Mask = Builder.CreateLShr(Mask, llvm::countr_zero(ElementSize));
315 Idx = Builder.CreateAnd(Idx, Mask);
317 return Idx;
320 // If the comparison is only true for one or two elements, emit direct
321 // comparisons.
322 if (SecondTrueElement != Overdefined) {
323 Idx = MaskIdx(Idx);
324 // None true -> false.
325 if (FirstTrueElement == Undefined)
326 return replaceInstUsesWith(ICI, Builder.getFalse());
328 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
330 // True for one element -> 'i == 47'.
331 if (SecondTrueElement == Undefined)
332 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
334 // True for two elements -> 'i == 47 | i == 72'.
335 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
336 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
337 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
338 return BinaryOperator::CreateOr(C1, C2);
341 // If the comparison is only false for one or two elements, emit direct
342 // comparisons.
343 if (SecondFalseElement != Overdefined) {
344 Idx = MaskIdx(Idx);
345 // None false -> true.
346 if (FirstFalseElement == Undefined)
347 return replaceInstUsesWith(ICI, Builder.getTrue());
349 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
351 // False for one element -> 'i != 47'.
352 if (SecondFalseElement == Undefined)
353 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
355 // False for two elements -> 'i != 47 & i != 72'.
356 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
357 Value *SecondFalseIdx =
358 ConstantInt::get(Idx->getType(), SecondFalseElement);
359 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
360 return BinaryOperator::CreateAnd(C1, C2);
363 // If the comparison can be replaced with a range comparison for the elements
364 // where it is true, emit the range check.
365 if (TrueRangeEnd != Overdefined) {
366 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
367 Idx = MaskIdx(Idx);
369 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
370 if (FirstTrueElement) {
371 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
372 Idx = Builder.CreateAdd(Idx, Offs);
375 Value *End =
376 ConstantInt::get(Idx->getType(), TrueRangeEnd - FirstTrueElement + 1);
377 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
380 // False range check.
381 if (FalseRangeEnd != Overdefined) {
382 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
383 Idx = MaskIdx(Idx);
384 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
385 if (FirstFalseElement) {
386 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
387 Idx = Builder.CreateAdd(Idx, Offs);
390 Value *End =
391 ConstantInt::get(Idx->getType(), FalseRangeEnd - FirstFalseElement);
392 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
395 // If a magic bitvector captures the entire comparison state
396 // of this load, replace it with computation that does:
397 // ((magic_cst >> i) & 1) != 0
399 Type *Ty = nullptr;
401 // Look for an appropriate type:
402 // - The type of Idx if the magic fits
403 // - The smallest fitting legal type
404 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
405 Ty = Idx->getType();
406 else
407 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
409 if (Ty) {
410 Idx = MaskIdx(Idx);
411 Value *V = Builder.CreateIntCast(Idx, Ty, false);
412 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
413 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
414 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
418 return nullptr;
421 /// Returns true if we can rewrite Start as a GEP with pointer Base
422 /// and some integer offset. The nodes that need to be re-written
423 /// for this transformation will be added to Explored.
424 static bool canRewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags &NW,
425 const DataLayout &DL,
426 SetVector<Value *> &Explored) {
427 SmallVector<Value *, 16> WorkList(1, Start);
428 Explored.insert(Base);
430 // The following traversal gives us an order which can be used
431 // when doing the final transformation. Since in the final
432 // transformation we create the PHI replacement instructions first,
433 // we don't have to get them in any particular order.
435 // However, for other instructions we will have to traverse the
436 // operands of an instruction first, which means that we have to
437 // do a post-order traversal.
438 while (!WorkList.empty()) {
439 SetVector<PHINode *> PHIs;
441 while (!WorkList.empty()) {
442 if (Explored.size() >= 100)
443 return false;
445 Value *V = WorkList.back();
447 if (Explored.contains(V)) {
448 WorkList.pop_back();
449 continue;
452 if (!isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
453 // We've found some value that we can't explore which is different from
454 // the base. Therefore we can't do this transformation.
455 return false;
457 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
458 // Only allow inbounds GEPs with at most one variable offset.
459 auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(V); };
460 if (!GEP->isInBounds() || count_if(GEP->indices(), IsNonConst) > 1)
461 return false;
463 NW = NW.intersectForOffsetAdd(GEP->getNoWrapFlags());
464 if (!Explored.contains(GEP->getOperand(0)))
465 WorkList.push_back(GEP->getOperand(0));
468 if (WorkList.back() == V) {
469 WorkList.pop_back();
470 // We've finished visiting this node, mark it as such.
471 Explored.insert(V);
474 if (auto *PN = dyn_cast<PHINode>(V)) {
475 // We cannot transform PHIs on unsplittable basic blocks.
476 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
477 return false;
478 Explored.insert(PN);
479 PHIs.insert(PN);
483 // Explore the PHI nodes further.
484 for (auto *PN : PHIs)
485 for (Value *Op : PN->incoming_values())
486 if (!Explored.contains(Op))
487 WorkList.push_back(Op);
490 // Make sure that we can do this. Since we can't insert GEPs in a basic
491 // block before a PHI node, we can't easily do this transformation if
492 // we have PHI node users of transformed instructions.
493 for (Value *Val : Explored) {
494 for (Value *Use : Val->uses()) {
496 auto *PHI = dyn_cast<PHINode>(Use);
497 auto *Inst = dyn_cast<Instruction>(Val);
499 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
500 !Explored.contains(PHI))
501 continue;
503 if (PHI->getParent() == Inst->getParent())
504 return false;
507 return true;
510 // Sets the appropriate insert point on Builder where we can add
511 // a replacement Instruction for V (if that is possible).
512 static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
513 bool Before = true) {
514 if (auto *PHI = dyn_cast<PHINode>(V)) {
515 BasicBlock *Parent = PHI->getParent();
516 Builder.SetInsertPoint(Parent, Parent->getFirstInsertionPt());
517 return;
519 if (auto *I = dyn_cast<Instruction>(V)) {
520 if (!Before)
521 I = &*std::next(I->getIterator());
522 Builder.SetInsertPoint(I);
523 return;
525 if (auto *A = dyn_cast<Argument>(V)) {
526 // Set the insertion point in the entry block.
527 BasicBlock &Entry = A->getParent()->getEntryBlock();
528 Builder.SetInsertPoint(&Entry, Entry.getFirstInsertionPt());
529 return;
531 // Otherwise, this is a constant and we don't need to set a new
532 // insertion point.
533 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
536 /// Returns a re-written value of Start as an indexed GEP using Base as a
537 /// pointer.
538 static Value *rewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags NW,
539 const DataLayout &DL,
540 SetVector<Value *> &Explored,
541 InstCombiner &IC) {
542 // Perform all the substitutions. This is a bit tricky because we can
543 // have cycles in our use-def chains.
544 // 1. Create the PHI nodes without any incoming values.
545 // 2. Create all the other values.
546 // 3. Add the edges for the PHI nodes.
547 // 4. Emit GEPs to get the original pointers.
548 // 5. Remove the original instructions.
549 Type *IndexType = IntegerType::get(
550 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
552 DenseMap<Value *, Value *> NewInsts;
553 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
555 // Create the new PHI nodes, without adding any incoming values.
556 for (Value *Val : Explored) {
557 if (Val == Base)
558 continue;
559 // Create empty phi nodes. This avoids cyclic dependencies when creating
560 // the remaining instructions.
561 if (auto *PHI = dyn_cast<PHINode>(Val))
562 NewInsts[PHI] =
563 PHINode::Create(IndexType, PHI->getNumIncomingValues(),
564 PHI->getName() + ".idx", PHI->getIterator());
566 IRBuilder<> Builder(Base->getContext());
568 // Create all the other instructions.
569 for (Value *Val : Explored) {
570 if (NewInsts.contains(Val))
571 continue;
573 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
574 setInsertionPoint(Builder, GEP);
575 Value *Op = NewInsts[GEP->getOperand(0)];
576 Value *OffsetV = emitGEPOffset(&Builder, DL, GEP);
577 if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero())
578 NewInsts[GEP] = OffsetV;
579 else
580 NewInsts[GEP] = Builder.CreateAdd(
581 Op, OffsetV, GEP->getOperand(0)->getName() + ".add",
582 /*NUW=*/NW.hasNoUnsignedWrap(),
583 /*NSW=*/NW.hasNoUnsignedSignedWrap());
584 continue;
586 if (isa<PHINode>(Val))
587 continue;
589 llvm_unreachable("Unexpected instruction type");
592 // Add the incoming values to the PHI nodes.
593 for (Value *Val : Explored) {
594 if (Val == Base)
595 continue;
596 // All the instructions have been created, we can now add edges to the
597 // phi nodes.
598 if (auto *PHI = dyn_cast<PHINode>(Val)) {
599 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
600 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
601 Value *NewIncoming = PHI->getIncomingValue(I);
603 auto It = NewInsts.find(NewIncoming);
604 if (It != NewInsts.end())
605 NewIncoming = It->second;
607 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
612 for (Value *Val : Explored) {
613 if (Val == Base)
614 continue;
616 setInsertionPoint(Builder, Val, false);
617 // Create GEP for external users.
618 Value *NewVal = Builder.CreateGEP(Builder.getInt8Ty(), Base, NewInsts[Val],
619 Val->getName() + ".ptr", NW);
620 IC.replaceInstUsesWith(*cast<Instruction>(Val), NewVal);
621 // Add old instruction to worklist for DCE. We don't directly remove it
622 // here because the original compare is one of the users.
623 IC.addToWorklist(cast<Instruction>(Val));
626 return NewInsts[Start];
629 /// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
630 /// We can look through PHIs, GEPs and casts in order to determine a common base
631 /// between GEPLHS and RHS.
632 static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
633 CmpPredicate Cond,
634 const DataLayout &DL,
635 InstCombiner &IC) {
636 // FIXME: Support vector of pointers.
637 if (GEPLHS->getType()->isVectorTy())
638 return nullptr;
640 if (!GEPLHS->hasAllConstantIndices())
641 return nullptr;
643 APInt Offset(DL.getIndexTypeSizeInBits(GEPLHS->getType()), 0);
644 Value *PtrBase =
645 GEPLHS->stripAndAccumulateConstantOffsets(DL, Offset,
646 /*AllowNonInbounds*/ false);
648 // Bail if we looked through addrspacecast.
649 if (PtrBase->getType() != GEPLHS->getType())
650 return nullptr;
652 // The set of nodes that will take part in this transformation.
653 SetVector<Value *> Nodes;
654 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags();
655 if (!canRewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes))
656 return nullptr;
658 // We know we can re-write this as
659 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
660 // Since we've only looked through inbouds GEPs we know that we
661 // can't have overflow on either side. We can therefore re-write
662 // this as:
663 // OFFSET1 cmp OFFSET2
664 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes, IC);
666 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
667 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
668 // offset. Since Index is the offset of LHS to the base pointer, we will now
669 // compare the offsets instead of comparing the pointers.
670 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
671 IC.Builder.getInt(Offset), NewRHS);
674 /// Fold comparisons between a GEP instruction and something else. At this point
675 /// we know that the GEP is on the LHS of the comparison.
676 Instruction *InstCombinerImpl::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
677 CmpPredicate Cond, Instruction &I) {
678 // Don't transform signed compares of GEPs into index compares. Even if the
679 // GEP is inbounds, the final add of the base pointer can have signed overflow
680 // and would change the result of the icmp.
681 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
682 // the maximum signed value for the pointer type.
683 if (ICmpInst::isSigned(Cond))
684 return nullptr;
686 // Look through bitcasts and addrspacecasts. We do not however want to remove
687 // 0 GEPs.
688 if (!isa<GetElementPtrInst>(RHS))
689 RHS = RHS->stripPointerCasts();
691 auto CanFold = [Cond](GEPNoWrapFlags NW) {
692 if (ICmpInst::isEquality(Cond))
693 return true;
695 // Unsigned predicates can be folded if the GEPs have *any* nowrap flags.
696 assert(ICmpInst::isUnsigned(Cond));
697 return NW != GEPNoWrapFlags::none();
700 auto NewICmp = [Cond](GEPNoWrapFlags NW, Value *Op1, Value *Op2) {
701 if (!NW.hasNoUnsignedWrap()) {
702 // Convert signed to unsigned comparison.
703 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Op1, Op2);
706 auto *I = new ICmpInst(Cond, Op1, Op2);
707 I->setSameSign(NW.hasNoUnsignedSignedWrap());
708 return I;
711 Value *PtrBase = GEPLHS->getOperand(0);
712 if (PtrBase == RHS && CanFold(GEPLHS->getNoWrapFlags())) {
713 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
714 Value *Offset = EmitGEPOffset(GEPLHS);
715 return NewICmp(GEPLHS->getNoWrapFlags(), Offset,
716 Constant::getNullValue(Offset->getType()));
719 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
720 isa<Constant>(RHS) && cast<Constant>(RHS)->isNullValue() &&
721 !NullPointerIsDefined(I.getFunction(),
722 RHS->getType()->getPointerAddressSpace())) {
723 // For most address spaces, an allocation can't be placed at null, but null
724 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
725 // the only valid inbounds address derived from null, is null itself.
726 // Thus, we have four cases to consider:
727 // 1) Base == nullptr, Offset == 0 -> inbounds, null
728 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
729 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
730 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
732 // (Note if we're indexing a type of size 0, that simply collapses into one
733 // of the buckets above.)
735 // In general, we're allowed to make values less poison (i.e. remove
736 // sources of full UB), so in this case, we just select between the two
737 // non-poison cases (1 and 4 above).
739 // For vectors, we apply the same reasoning on a per-lane basis.
740 auto *Base = GEPLHS->getPointerOperand();
741 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
742 auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
743 Base = Builder.CreateVectorSplat(EC, Base);
745 return new ICmpInst(Cond, Base,
746 ConstantExpr::getPointerBitCastOrAddrSpaceCast(
747 cast<Constant>(RHS), Base->getType()));
748 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
749 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags() & GEPRHS->getNoWrapFlags();
751 // If the base pointers are different, but the indices are the same, just
752 // compare the base pointer.
753 if (PtrBase != GEPRHS->getOperand(0)) {
754 bool IndicesTheSame =
755 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
756 GEPLHS->getPointerOperand()->getType() ==
757 GEPRHS->getPointerOperand()->getType() &&
758 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
759 if (IndicesTheSame)
760 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
761 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
762 IndicesTheSame = false;
763 break;
766 // If all indices are the same, just compare the base pointers.
767 Type *BaseType = GEPLHS->getOperand(0)->getType();
768 if (IndicesTheSame &&
769 CmpInst::makeCmpResultType(BaseType) == I.getType() && CanFold(NW))
770 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
772 // If we're comparing GEPs with two base pointers that only differ in type
773 // and both GEPs have only constant indices or just one use, then fold
774 // the compare with the adjusted indices.
775 // FIXME: Support vector of pointers.
776 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
777 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
778 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
779 PtrBase->stripPointerCasts() ==
780 GEPRHS->getOperand(0)->stripPointerCasts() &&
781 !GEPLHS->getType()->isVectorTy()) {
782 Value *LOffset = EmitGEPOffset(GEPLHS);
783 Value *ROffset = EmitGEPOffset(GEPRHS);
785 // If we looked through an addrspacecast between different sized address
786 // spaces, the LHS and RHS pointers are different sized
787 // integers. Truncate to the smaller one.
788 Type *LHSIndexTy = LOffset->getType();
789 Type *RHSIndexTy = ROffset->getType();
790 if (LHSIndexTy != RHSIndexTy) {
791 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
792 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
793 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
794 } else
795 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
798 Value *Cmp = Builder.CreateICmp(ICmpInst::getSignedPredicate(Cond),
799 LOffset, ROffset);
800 return replaceInstUsesWith(I, Cmp);
803 // Otherwise, the base pointers are different and the indices are
804 // different. Try convert this to an indexed compare by looking through
805 // PHIs/casts.
806 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
809 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
810 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
811 // If the GEPs only differ by one index, compare it.
812 unsigned NumDifferences = 0; // Keep track of # differences.
813 unsigned DiffOperand = 0; // The operand that differs.
814 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
815 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
816 Type *LHSType = GEPLHS->getOperand(i)->getType();
817 Type *RHSType = GEPRHS->getOperand(i)->getType();
818 // FIXME: Better support for vector of pointers.
819 if (LHSType->getPrimitiveSizeInBits() !=
820 RHSType->getPrimitiveSizeInBits() ||
821 (GEPLHS->getType()->isVectorTy() &&
822 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
823 // Irreconcilable differences.
824 NumDifferences = 2;
825 break;
828 if (NumDifferences++)
829 break;
830 DiffOperand = i;
833 if (NumDifferences == 0) // SAME GEP?
834 return replaceInstUsesWith(
835 I, // No comparison is needed here.
836 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
837 // If two GEPs only differ by an index, compare them.
838 // Note that nowrap flags are always needed when comparing two indices.
839 else if (NumDifferences == 1 && NW != GEPNoWrapFlags::none()) {
840 Value *LHSV = GEPLHS->getOperand(DiffOperand);
841 Value *RHSV = GEPRHS->getOperand(DiffOperand);
842 return NewICmp(NW, LHSV, RHSV);
846 if (CanFold(NW)) {
847 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
848 Value *L = EmitGEPOffset(GEPLHS, /*RewriteGEP=*/true);
849 Value *R = EmitGEPOffset(GEPRHS, /*RewriteGEP=*/true);
850 return NewICmp(NW, L, R);
854 // Try convert this to an indexed compare by looking through PHIs/casts as a
855 // last resort.
856 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
859 bool InstCombinerImpl::foldAllocaCmp(AllocaInst *Alloca) {
860 // It would be tempting to fold away comparisons between allocas and any
861 // pointer not based on that alloca (e.g. an argument). However, even
862 // though such pointers cannot alias, they can still compare equal.
864 // But LLVM doesn't specify where allocas get their memory, so if the alloca
865 // doesn't escape we can argue that it's impossible to guess its value, and we
866 // can therefore act as if any such guesses are wrong.
868 // However, we need to ensure that this folding is consistent: We can't fold
869 // one comparison to false, and then leave a different comparison against the
870 // same value alone (as it might evaluate to true at runtime, leading to a
871 // contradiction). As such, this code ensures that all comparisons are folded
872 // at the same time, and there are no other escapes.
874 struct CmpCaptureTracker : public CaptureTracker {
875 AllocaInst *Alloca;
876 bool Captured = false;
877 /// The value of the map is a bit mask of which icmp operands the alloca is
878 /// used in.
879 SmallMapVector<ICmpInst *, unsigned, 4> ICmps;
881 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
883 void tooManyUses() override { Captured = true; }
885 bool captured(const Use *U) override {
886 auto *ICmp = dyn_cast<ICmpInst>(U->getUser());
887 // We need to check that U is based *only* on the alloca, and doesn't
888 // have other contributions from a select/phi operand.
889 // TODO: We could check whether getUnderlyingObjects() reduces to one
890 // object, which would allow looking through phi nodes.
891 if (ICmp && ICmp->isEquality() && getUnderlyingObject(*U) == Alloca) {
892 // Collect equality icmps of the alloca, and don't treat them as
893 // captures.
894 ICmps[ICmp] |= 1u << U->getOperandNo();
895 return false;
898 Captured = true;
899 return true;
903 CmpCaptureTracker Tracker(Alloca);
904 PointerMayBeCaptured(Alloca, &Tracker);
905 if (Tracker.Captured)
906 return false;
908 bool Changed = false;
909 for (auto [ICmp, Operands] : Tracker.ICmps) {
910 switch (Operands) {
911 case 1:
912 case 2: {
913 // The alloca is only used in one icmp operand. Assume that the
914 // equality is false.
915 auto *Res = ConstantInt::get(ICmp->getType(),
916 ICmp->getPredicate() == ICmpInst::ICMP_NE);
917 replaceInstUsesWith(*ICmp, Res);
918 eraseInstFromFunction(*ICmp);
919 Changed = true;
920 break;
922 case 3:
923 // Both icmp operands are based on the alloca, so this is comparing
924 // pointer offsets, without leaking any information about the address
925 // of the alloca. Ignore such comparisons.
926 break;
927 default:
928 llvm_unreachable("Cannot happen");
932 return Changed;
935 /// Fold "icmp pred (X+C), X".
936 Instruction *InstCombinerImpl::foldICmpAddOpConst(Value *X, const APInt &C,
937 CmpPredicate Pred) {
938 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
939 // so the values can never be equal. Similarly for all other "or equals"
940 // operators.
941 assert(!!C && "C should not be zero!");
943 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
944 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
945 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
946 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
947 Constant *R =
948 ConstantInt::get(X->getType(), APInt::getMaxValue(C.getBitWidth()) - C);
949 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
952 // (X+1) >u X --> X <u (0-1) --> X != 255
953 // (X+2) >u X --> X <u (0-2) --> X <u 254
954 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
955 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
956 return new ICmpInst(ICmpInst::ICMP_ULT, X,
957 ConstantInt::get(X->getType(), -C));
959 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
961 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
962 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
963 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
964 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
965 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
966 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
967 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
968 return new ICmpInst(ICmpInst::ICMP_SGT, X,
969 ConstantInt::get(X->getType(), SMax - C));
971 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
972 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
973 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
974 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
975 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
976 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
978 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
979 return new ICmpInst(ICmpInst::ICMP_SLT, X,
980 ConstantInt::get(X->getType(), SMax - (C - 1)));
983 /// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
984 /// (icmp eq/ne A, Log2(AP2/AP1)) ->
985 /// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
986 Instruction *InstCombinerImpl::foldICmpShrConstConst(ICmpInst &I, Value *A,
987 const APInt &AP1,
988 const APInt &AP2) {
989 assert(I.isEquality() && "Cannot fold icmp gt/lt");
991 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
992 if (I.getPredicate() == I.ICMP_NE)
993 Pred = CmpInst::getInversePredicate(Pred);
994 return new ICmpInst(Pred, LHS, RHS);
997 // Don't bother doing any work for cases which InstSimplify handles.
998 if (AP2.isZero())
999 return nullptr;
1001 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
1002 if (IsAShr) {
1003 if (AP2.isAllOnes())
1004 return nullptr;
1005 if (AP2.isNegative() != AP1.isNegative())
1006 return nullptr;
1007 if (AP2.sgt(AP1))
1008 return nullptr;
1011 if (!AP1)
1012 // 'A' must be large enough to shift out the highest set bit.
1013 return getICmp(I.ICMP_UGT, A,
1014 ConstantInt::get(A->getType(), AP2.logBase2()));
1016 if (AP1 == AP2)
1017 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1019 int Shift;
1020 if (IsAShr && AP1.isNegative())
1021 Shift = AP1.countl_one() - AP2.countl_one();
1022 else
1023 Shift = AP1.countl_zero() - AP2.countl_zero();
1025 if (Shift > 0) {
1026 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1027 // There are multiple solutions if we are comparing against -1 and the LHS
1028 // of the ashr is not a power of two.
1029 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1030 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1031 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1032 } else if (AP1 == AP2.lshr(Shift)) {
1033 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1037 // Shifting const2 will never be equal to const1.
1038 // FIXME: This should always be handled by InstSimplify?
1039 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1040 return replaceInstUsesWith(I, TorF);
1043 /// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1044 /// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1045 Instruction *InstCombinerImpl::foldICmpShlConstConst(ICmpInst &I, Value *A,
1046 const APInt &AP1,
1047 const APInt &AP2) {
1048 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1050 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1051 if (I.getPredicate() == I.ICMP_NE)
1052 Pred = CmpInst::getInversePredicate(Pred);
1053 return new ICmpInst(Pred, LHS, RHS);
1056 // Don't bother doing any work for cases which InstSimplify handles.
1057 if (AP2.isZero())
1058 return nullptr;
1060 unsigned AP2TrailingZeros = AP2.countr_zero();
1062 if (!AP1 && AP2TrailingZeros != 0)
1063 return getICmp(
1064 I.ICMP_UGE, A,
1065 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1067 if (AP1 == AP2)
1068 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1070 // Get the distance between the lowest bits that are set.
1071 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1073 if (Shift > 0 && AP2.shl(Shift) == AP1)
1074 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1076 // Shifting const2 will never be equal to const1.
1077 // FIXME: This should always be handled by InstSimplify?
1078 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1079 return replaceInstUsesWith(I, TorF);
1082 /// The caller has matched a pattern of the form:
1083 /// I = icmp ugt (add (add A, B), CI2), CI1
1084 /// If this is of the form:
1085 /// sum = a + b
1086 /// if (sum+128 >u 255)
1087 /// Then replace it with llvm.sadd.with.overflow.i8.
1089 static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1090 ConstantInt *CI2, ConstantInt *CI1,
1091 InstCombinerImpl &IC) {
1092 // The transformation we're trying to do here is to transform this into an
1093 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1094 // with a narrower add, and discard the add-with-constant that is part of the
1095 // range check (if we can't eliminate it, this isn't profitable).
1097 // In order to eliminate the add-with-constant, the compare can be its only
1098 // use.
1099 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1100 if (!AddWithCst->hasOneUse())
1101 return nullptr;
1103 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1104 if (!CI2->getValue().isPowerOf2())
1105 return nullptr;
1106 unsigned NewWidth = CI2->getValue().countr_zero();
1107 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1108 return nullptr;
1110 // The width of the new add formed is 1 more than the bias.
1111 ++NewWidth;
1113 // Check to see that CI1 is an all-ones value with NewWidth bits.
1114 if (CI1->getBitWidth() == NewWidth ||
1115 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1116 return nullptr;
1118 // This is only really a signed overflow check if the inputs have been
1119 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1120 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1121 if (IC.ComputeMaxSignificantBits(A, 0, &I) > NewWidth ||
1122 IC.ComputeMaxSignificantBits(B, 0, &I) > NewWidth)
1123 return nullptr;
1125 // In order to replace the original add with a narrower
1126 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1127 // and truncates that discard the high bits of the add. Verify that this is
1128 // the case.
1129 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1130 for (User *U : OrigAdd->users()) {
1131 if (U == AddWithCst)
1132 continue;
1134 // Only accept truncates for now. We would really like a nice recursive
1135 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1136 // chain to see which bits of a value are actually demanded. If the
1137 // original add had another add which was then immediately truncated, we
1138 // could still do the transformation.
1139 TruncInst *TI = dyn_cast<TruncInst>(U);
1140 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1141 return nullptr;
1144 // If the pattern matches, truncate the inputs to the narrower type and
1145 // use the sadd_with_overflow intrinsic to efficiently compute both the
1146 // result and the overflow bit.
1147 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1148 Function *F = Intrinsic::getOrInsertDeclaration(
1149 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1151 InstCombiner::BuilderTy &Builder = IC.Builder;
1153 // Put the new code above the original add, in case there are any uses of the
1154 // add between the add and the compare.
1155 Builder.SetInsertPoint(OrigAdd);
1157 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1158 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1159 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1160 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1161 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1163 // The inner add was the result of the narrow add, zero extended to the
1164 // wider type. Replace it with the result computed by the intrinsic.
1165 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1166 IC.eraseInstFromFunction(*OrigAdd);
1168 // The original icmp gets replaced with the overflow value.
1169 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1172 /// If we have:
1173 /// icmp eq/ne (urem/srem %x, %y), 0
1174 /// iff %y is a power-of-two, we can replace this with a bit test:
1175 /// icmp eq/ne (and %x, (add %y, -1)), 0
1176 Instruction *InstCombinerImpl::foldIRemByPowerOfTwoToBitTest(ICmpInst &I) {
1177 // This fold is only valid for equality predicates.
1178 if (!I.isEquality())
1179 return nullptr;
1180 CmpPredicate Pred;
1181 Value *X, *Y, *Zero;
1182 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1183 m_CombineAnd(m_Zero(), m_Value(Zero)))))
1184 return nullptr;
1185 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, 0, &I))
1186 return nullptr;
1187 // This may increase instruction count, we don't enforce that Y is a constant.
1188 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1189 Value *Masked = Builder.CreateAnd(X, Mask);
1190 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1193 /// Fold equality-comparison between zero and any (maybe truncated) right-shift
1194 /// by one-less-than-bitwidth into a sign test on the original value.
1195 Instruction *InstCombinerImpl::foldSignBitTest(ICmpInst &I) {
1196 Instruction *Val;
1197 CmpPredicate Pred;
1198 if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1199 return nullptr;
1201 Value *X;
1202 Type *XTy;
1204 Constant *C;
1205 if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1206 XTy = X->getType();
1207 unsigned XBitWidth = XTy->getScalarSizeInBits();
1208 if (!match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
1209 APInt(XBitWidth, XBitWidth - 1))))
1210 return nullptr;
1211 } else if (isa<BinaryOperator>(Val) &&
1212 (X = reassociateShiftAmtsOfTwoSameDirectionShifts(
1213 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1214 /*AnalyzeForSignBitExtraction=*/true))) {
1215 XTy = X->getType();
1216 } else
1217 return nullptr;
1219 return ICmpInst::Create(Instruction::ICmp,
1220 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SGE
1221 : ICmpInst::ICMP_SLT,
1222 X, ConstantInt::getNullValue(XTy));
1225 // Handle icmp pred X, 0
1226 Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) {
1227 CmpInst::Predicate Pred = Cmp.getPredicate();
1228 if (!match(Cmp.getOperand(1), m_Zero()))
1229 return nullptr;
1231 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1232 if (Pred == ICmpInst::ICMP_SGT) {
1233 Value *A, *B;
1234 if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1235 if (isKnownPositive(A, SQ.getWithInstruction(&Cmp)))
1236 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1237 if (isKnownPositive(B, SQ.getWithInstruction(&Cmp)))
1238 return new ICmpInst(Pred, A, Cmp.getOperand(1));
1242 if (Instruction *New = foldIRemByPowerOfTwoToBitTest(Cmp))
1243 return New;
1245 // Given:
1246 // icmp eq/ne (urem %x, %y), 0
1247 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1248 // icmp eq/ne %x, 0
1249 Value *X, *Y;
1250 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1251 ICmpInst::isEquality(Pred)) {
1252 KnownBits XKnown = computeKnownBits(X, 0, &Cmp);
1253 KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);
1254 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1255 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1258 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1259 // odd/non-zero/there is no overflow.
1260 if (match(Cmp.getOperand(0), m_Mul(m_Value(X), m_Value(Y))) &&
1261 ICmpInst::isEquality(Pred)) {
1263 KnownBits XKnown = computeKnownBits(X, 0, &Cmp);
1264 // if X % 2 != 0
1265 // (icmp eq/ne Y)
1266 if (XKnown.countMaxTrailingZeros() == 0)
1267 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1269 KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);
1270 // if Y % 2 != 0
1271 // (icmp eq/ne X)
1272 if (YKnown.countMaxTrailingZeros() == 0)
1273 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1275 auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1276 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1277 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
1278 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1279 // but to avoid unnecessary work, first just if this is an obvious case.
1281 // if X non-zero and NoOverflow(X * Y)
1282 // (icmp eq/ne Y)
1283 if (!XKnown.One.isZero() || isKnownNonZero(X, Q))
1284 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1286 // if Y non-zero and NoOverflow(X * Y)
1287 // (icmp eq/ne X)
1288 if (!YKnown.One.isZero() || isKnownNonZero(Y, Q))
1289 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1291 // Note, we are skipping cases:
1292 // if Y % 2 != 0 AND X % 2 != 0
1293 // (false/true)
1294 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1295 // (false/true)
1296 // Those can be simplified later as we would have already replaced the (icmp
1297 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1298 // will fold to a constant elsewhere.
1300 return nullptr;
1303 /// Fold icmp Pred X, C.
1304 /// TODO: This code structure does not make sense. The saturating add fold
1305 /// should be moved to some other helper and extended as noted below (it is also
1306 /// possible that code has been made unnecessary - do we canonicalize IR to
1307 /// overflow/saturating intrinsics or not?).
1308 Instruction *InstCombinerImpl::foldICmpWithConstant(ICmpInst &Cmp) {
1309 // Match the following pattern, which is a common idiom when writing
1310 // overflow-safe integer arithmetic functions. The source performs an addition
1311 // in wider type and explicitly checks for overflow using comparisons against
1312 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1314 // TODO: This could probably be generalized to handle other overflow-safe
1315 // operations if we worked out the formulas to compute the appropriate magic
1316 // constants.
1318 // sum = a + b
1319 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1320 CmpInst::Predicate Pred = Cmp.getPredicate();
1321 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1322 Value *A, *B;
1323 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1324 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1325 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1326 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1327 return Res;
1329 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1330 Constant *C = dyn_cast<Constant>(Op1);
1331 if (!C)
1332 return nullptr;
1334 if (auto *Phi = dyn_cast<PHINode>(Op0))
1335 if (all_of(Phi->operands(), [](Value *V) { return isa<Constant>(V); })) {
1336 SmallVector<Constant *> Ops;
1337 for (Value *V : Phi->incoming_values()) {
1338 Constant *Res =
1339 ConstantFoldCompareInstOperands(Pred, cast<Constant>(V), C, DL);
1340 if (!Res)
1341 return nullptr;
1342 Ops.push_back(Res);
1344 Builder.SetInsertPoint(Phi);
1345 PHINode *NewPhi = Builder.CreatePHI(Cmp.getType(), Phi->getNumOperands());
1346 for (auto [V, Pred] : zip(Ops, Phi->blocks()))
1347 NewPhi->addIncoming(V, Pred);
1348 return replaceInstUsesWith(Cmp, NewPhi);
1351 if (Instruction *R = tryFoldInstWithCtpopWithNot(&Cmp))
1352 return R;
1354 return nullptr;
1357 /// Canonicalize icmp instructions based on dominating conditions.
1358 Instruction *InstCombinerImpl::foldICmpWithDominatingICmp(ICmpInst &Cmp) {
1359 // We already checked simple implication in InstSimplify, only handle complex
1360 // cases here.
1361 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1362 const APInt *C;
1363 if (!match(Y, m_APInt(C)))
1364 return nullptr;
1366 CmpInst::Predicate Pred = Cmp.getPredicate();
1367 ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, *C);
1369 auto handleDomCond = [&](ICmpInst::Predicate DomPred,
1370 const APInt *DomC) -> Instruction * {
1371 // We have 2 compares of a variable with constants. Calculate the constant
1372 // ranges of those compares to see if we can transform the 2nd compare:
1373 // DomBB:
1374 // DomCond = icmp DomPred X, DomC
1375 // br DomCond, CmpBB, FalseBB
1376 // CmpBB:
1377 // Cmp = icmp Pred X, C
1378 ConstantRange DominatingCR =
1379 ConstantRange::makeExactICmpRegion(DomPred, *DomC);
1380 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1381 ConstantRange Difference = DominatingCR.difference(CR);
1382 if (Intersection.isEmptySet())
1383 return replaceInstUsesWith(Cmp, Builder.getFalse());
1384 if (Difference.isEmptySet())
1385 return replaceInstUsesWith(Cmp, Builder.getTrue());
1387 // Canonicalizing a sign bit comparison that gets used in a branch,
1388 // pessimizes codegen by generating branch on zero instruction instead
1389 // of a test and branch. So we avoid canonicalizing in such situations
1390 // because test and branch instruction has better branch displacement
1391 // than compare and branch instruction.
1392 bool UnusedBit;
1393 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1394 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1395 return nullptr;
1397 // Avoid an infinite loop with min/max canonicalization.
1398 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1399 if (Cmp.hasOneUse() &&
1400 match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1401 return nullptr;
1403 if (const APInt *EqC = Intersection.getSingleElement())
1404 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1405 if (const APInt *NeC = Difference.getSingleElement())
1406 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1407 return nullptr;
1410 for (BranchInst *BI : DC.conditionsFor(X)) {
1411 CmpPredicate DomPred;
1412 const APInt *DomC;
1413 if (!match(BI->getCondition(),
1414 m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))))
1415 continue;
1417 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1418 if (DT.dominates(Edge0, Cmp.getParent())) {
1419 if (auto *V = handleDomCond(DomPred, DomC))
1420 return V;
1421 } else {
1422 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1423 if (DT.dominates(Edge1, Cmp.getParent()))
1424 if (auto *V =
1425 handleDomCond(CmpInst::getInversePredicate(DomPred), DomC))
1426 return V;
1430 return nullptr;
1433 /// Fold icmp (trunc X), C.
1434 Instruction *InstCombinerImpl::foldICmpTruncConstant(ICmpInst &Cmp,
1435 TruncInst *Trunc,
1436 const APInt &C) {
1437 ICmpInst::Predicate Pred = Cmp.getPredicate();
1438 Value *X = Trunc->getOperand(0);
1439 Type *SrcTy = X->getType();
1440 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1441 SrcBits = SrcTy->getScalarSizeInBits();
1443 // Match (icmp pred (trunc nuw/nsw X), C)
1444 // Which we can convert to (icmp pred X, (sext/zext C))
1445 if (shouldChangeType(Trunc->getType(), SrcTy)) {
1446 if (Trunc->hasNoSignedWrap())
1447 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.sext(SrcBits)));
1448 if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())
1449 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.zext(SrcBits)));
1452 if (C.isOne() && C.getBitWidth() > 1) {
1453 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1454 Value *V = nullptr;
1455 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1456 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1457 ConstantInt::get(V->getType(), 1));
1460 // TODO: Handle any shifted constant by subtracting trailing zeros.
1461 // TODO: Handle non-equality predicates.
1462 Value *Y;
1463 if (Cmp.isEquality() && match(X, m_Shl(m_One(), m_Value(Y)))) {
1464 // (trunc (1 << Y) to iN) == 0 --> Y u>= N
1465 // (trunc (1 << Y) to iN) != 0 --> Y u< N
1466 if (C.isZero()) {
1467 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1468 return new ICmpInst(NewPred, Y, ConstantInt::get(SrcTy, DstBits));
1470 // (trunc (1 << Y) to iN) == 2**C --> Y == C
1471 // (trunc (1 << Y) to iN) != 2**C --> Y != C
1472 if (C.isPowerOf2())
1473 return new ICmpInst(Pred, Y, ConstantInt::get(SrcTy, C.logBase2()));
1476 if (Cmp.isEquality() && Trunc->hasOneUse()) {
1477 // Canonicalize to a mask and wider compare if the wide type is suitable:
1478 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1479 if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1480 Constant *Mask =
1481 ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1482 Value *And = Builder.CreateAnd(X, Mask);
1483 Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1484 return new ICmpInst(Pred, And, WideC);
1487 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1488 // of the high bits truncated out of x are known.
1489 KnownBits Known = computeKnownBits(X, 0, &Cmp);
1491 // If all the high bits are known, we can do this xform.
1492 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1493 // Pull in the high bits from known-ones set.
1494 APInt NewRHS = C.zext(SrcBits);
1495 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1496 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1500 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1501 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1502 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1503 Value *ShOp;
1504 const APInt *ShAmtC;
1505 bool TrueIfSigned;
1506 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1507 match(X, m_Shr(m_Value(ShOp), m_APInt(ShAmtC))) &&
1508 DstBits == SrcBits - ShAmtC->getZExtValue()) {
1509 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1510 ConstantInt::getNullValue(SrcTy))
1511 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1512 ConstantInt::getAllOnesValue(SrcTy));
1515 return nullptr;
1518 /// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
1519 /// Fold icmp (trunc nuw/nsw X), (zext/sext Y).
1520 Instruction *
1521 InstCombinerImpl::foldICmpTruncWithTruncOrExt(ICmpInst &Cmp,
1522 const SimplifyQuery &Q) {
1523 Value *X, *Y;
1524 CmpPredicate Pred;
1525 bool YIsSExt = false;
1526 // Try to match icmp (trunc X), (trunc Y)
1527 if (match(&Cmp, m_ICmp(Pred, m_Trunc(m_Value(X)), m_Trunc(m_Value(Y))))) {
1528 unsigned NoWrapFlags = cast<TruncInst>(Cmp.getOperand(0))->getNoWrapKind() &
1529 cast<TruncInst>(Cmp.getOperand(1))->getNoWrapKind();
1530 if (Cmp.isSigned()) {
1531 // For signed comparisons, both truncs must be nsw.
1532 if (!(NoWrapFlags & TruncInst::NoSignedWrap))
1533 return nullptr;
1534 } else {
1535 // For unsigned and equality comparisons, either both must be nuw or
1536 // both must be nsw, we don't care which.
1537 if (!NoWrapFlags)
1538 return nullptr;
1541 if (X->getType() != Y->getType() &&
1542 (!Cmp.getOperand(0)->hasOneUse() || !Cmp.getOperand(1)->hasOneUse()))
1543 return nullptr;
1544 if (!isDesirableIntType(X->getType()->getScalarSizeInBits()) &&
1545 isDesirableIntType(Y->getType()->getScalarSizeInBits())) {
1546 std::swap(X, Y);
1547 Pred = Cmp.getSwappedPredicate(Pred);
1549 YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);
1551 // Try to match icmp (trunc nuw X), (zext Y)
1552 else if (!Cmp.isSigned() &&
1553 match(&Cmp, m_c_ICmp(Pred, m_NUWTrunc(m_Value(X)),
1554 m_OneUse(m_ZExt(m_Value(Y)))))) {
1555 // Can fold trunc nuw + zext for unsigned and equality predicates.
1557 // Try to match icmp (trunc nsw X), (sext Y)
1558 else if (match(&Cmp, m_c_ICmp(Pred, m_NSWTrunc(m_Value(X)),
1559 m_OneUse(m_ZExtOrSExt(m_Value(Y)))))) {
1560 // Can fold trunc nsw + zext/sext for all predicates.
1561 YIsSExt =
1562 isa<SExtInst>(Cmp.getOperand(0)) || isa<SExtInst>(Cmp.getOperand(1));
1563 } else
1564 return nullptr;
1566 Type *TruncTy = Cmp.getOperand(0)->getType();
1567 unsigned TruncBits = TruncTy->getScalarSizeInBits();
1569 // If this transform will end up changing from desirable types -> undesirable
1570 // types skip it.
1571 if (isDesirableIntType(TruncBits) &&
1572 !isDesirableIntType(X->getType()->getScalarSizeInBits()))
1573 return nullptr;
1575 Value *NewY = Builder.CreateIntCast(Y, X->getType(), YIsSExt);
1576 return new ICmpInst(Pred, X, NewY);
1579 /// Fold icmp (xor X, Y), C.
1580 Instruction *InstCombinerImpl::foldICmpXorConstant(ICmpInst &Cmp,
1581 BinaryOperator *Xor,
1582 const APInt &C) {
1583 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1584 return I;
1586 Value *X = Xor->getOperand(0);
1587 Value *Y = Xor->getOperand(1);
1588 const APInt *XorC;
1589 if (!match(Y, m_APInt(XorC)))
1590 return nullptr;
1592 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1593 // fold the xor.
1594 ICmpInst::Predicate Pred = Cmp.getPredicate();
1595 bool TrueIfSigned = false;
1596 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1598 // If the sign bit of the XorCst is not set, there is no change to
1599 // the operation, just stop using the Xor.
1600 if (!XorC->isNegative())
1601 return replaceOperand(Cmp, 0, X);
1603 // Emit the opposite comparison.
1604 if (TrueIfSigned)
1605 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1606 ConstantInt::getAllOnesValue(X->getType()));
1607 else
1608 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1609 ConstantInt::getNullValue(X->getType()));
1612 if (Xor->hasOneUse()) {
1613 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1614 if (!Cmp.isEquality() && XorC->isSignMask()) {
1615 Pred = Cmp.getFlippedSignednessPredicate();
1616 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1619 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1620 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1621 Pred = Cmp.getFlippedSignednessPredicate();
1622 Pred = Cmp.getSwappedPredicate(Pred);
1623 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1627 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1628 if (Pred == ICmpInst::ICMP_UGT) {
1629 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1630 if (*XorC == ~C && (C + 1).isPowerOf2())
1631 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1632 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1633 if (*XorC == C && (C + 1).isPowerOf2())
1634 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1636 if (Pred == ICmpInst::ICMP_ULT) {
1637 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1638 if (*XorC == -C && C.isPowerOf2())
1639 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1640 ConstantInt::get(X->getType(), ~C));
1641 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1642 if (*XorC == C && (-C).isPowerOf2())
1643 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1644 ConstantInt::get(X->getType(), ~C));
1646 return nullptr;
1649 /// For power-of-2 C:
1650 /// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1651 /// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1652 Instruction *InstCombinerImpl::foldICmpXorShiftConst(ICmpInst &Cmp,
1653 BinaryOperator *Xor,
1654 const APInt &C) {
1655 CmpInst::Predicate Pred = Cmp.getPredicate();
1656 APInt PowerOf2;
1657 if (Pred == ICmpInst::ICMP_ULT)
1658 PowerOf2 = C;
1659 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1660 PowerOf2 = C + 1;
1661 else
1662 return nullptr;
1663 if (!PowerOf2.isPowerOf2())
1664 return nullptr;
1665 Value *X;
1666 const APInt *ShiftC;
1667 if (!match(Xor, m_OneUse(m_c_Xor(m_Value(X),
1668 m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1669 return nullptr;
1670 uint64_t Shift = ShiftC->getLimitedValue();
1671 Type *XType = X->getType();
1672 if (Shift == 0 || PowerOf2.isMinSignedValue())
1673 return nullptr;
1674 Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1675 APInt Bound =
1676 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1677 return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1680 /// Fold icmp (and (sh X, Y), C2), C1.
1681 Instruction *InstCombinerImpl::foldICmpAndShift(ICmpInst &Cmp,
1682 BinaryOperator *And,
1683 const APInt &C1,
1684 const APInt &C2) {
1685 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1686 if (!Shift || !Shift->isShift())
1687 return nullptr;
1689 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1690 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1691 // code produced by the clang front-end, for bitfield access.
1692 // This seemingly simple opportunity to fold away a shift turns out to be
1693 // rather complicated. See PR17827 for details.
1694 unsigned ShiftOpcode = Shift->getOpcode();
1695 bool IsShl = ShiftOpcode == Instruction::Shl;
1696 const APInt *C3;
1697 if (match(Shift->getOperand(1), m_APInt(C3))) {
1698 APInt NewAndCst, NewCmpCst;
1699 bool AnyCmpCstBitsShiftedOut;
1700 if (ShiftOpcode == Instruction::Shl) {
1701 // For a left shift, we can fold if the comparison is not signed. We can
1702 // also fold a signed comparison if the mask value and comparison value
1703 // are not negative. These constraints may not be obvious, but we can
1704 // prove that they are correct using an SMT solver.
1705 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1706 return nullptr;
1708 NewCmpCst = C1.lshr(*C3);
1709 NewAndCst = C2.lshr(*C3);
1710 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1711 } else if (ShiftOpcode == Instruction::LShr) {
1712 // For a logical right shift, we can fold if the comparison is not signed.
1713 // We can also fold a signed comparison if the shifted mask value and the
1714 // shifted comparison value are not negative. These constraints may not be
1715 // obvious, but we can prove that they are correct using an SMT solver.
1716 NewCmpCst = C1.shl(*C3);
1717 NewAndCst = C2.shl(*C3);
1718 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1719 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1720 return nullptr;
1721 } else {
1722 // For an arithmetic shift, check that both constants don't use (in a
1723 // signed sense) the top bits being shifted out.
1724 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1725 NewCmpCst = C1.shl(*C3);
1726 NewAndCst = C2.shl(*C3);
1727 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1728 if (NewAndCst.ashr(*C3) != C2)
1729 return nullptr;
1732 if (AnyCmpCstBitsShiftedOut) {
1733 // If we shifted bits out, the fold is not going to work out. As a
1734 // special case, check to see if this means that the result is always
1735 // true or false now.
1736 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1737 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1738 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1739 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1740 } else {
1741 Value *NewAnd = Builder.CreateAnd(
1742 Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1743 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1744 ConstantInt::get(And->getType(), NewCmpCst));
1748 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1749 // preferable because it allows the C2 << Y expression to be hoisted out of a
1750 // loop if Y is invariant and X is not.
1751 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1752 !Shift->isArithmeticShift() &&
1753 ((!IsShl && C2.isOne()) || !isa<Constant>(Shift->getOperand(0)))) {
1754 // Compute C2 << Y.
1755 Value *NewShift =
1756 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1757 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1759 // Compute X & (C2 << Y).
1760 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1761 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1764 return nullptr;
1767 /// Fold icmp (and X, C2), C1.
1768 Instruction *InstCombinerImpl::foldICmpAndConstConst(ICmpInst &Cmp,
1769 BinaryOperator *And,
1770 const APInt &C1) {
1771 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1773 // For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i1
1774 // TODO: We canonicalize to the longer form for scalars because we have
1775 // better analysis/folds for icmp, and codegen may be better with icmp.
1776 if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.isZero() &&
1777 match(And->getOperand(1), m_One()))
1778 return new TruncInst(And->getOperand(0), Cmp.getType());
1780 const APInt *C2;
1781 Value *X;
1782 if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1783 return nullptr;
1785 // (and X, highmask) s> [0, ~highmask] --> X s> ~highmask
1786 if (Cmp.getPredicate() == ICmpInst::ICMP_SGT && C1.ule(~*C2) &&
1787 C2->isNegatedPowerOf2())
1788 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1789 ConstantInt::get(X->getType(), ~*C2));
1790 // (and X, highmask) s< [1, -highmask] --> X s< -highmask
1791 if (Cmp.getPredicate() == ICmpInst::ICMP_SLT && !C1.isSignMask() &&
1792 (C1 - 1).ule(~*C2) && C2->isNegatedPowerOf2() && !C2->isSignMask())
1793 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1794 ConstantInt::get(X->getType(), -*C2));
1796 // Don't perform the following transforms if the AND has multiple uses
1797 if (!And->hasOneUse())
1798 return nullptr;
1800 if (Cmp.isEquality() && C1.isZero()) {
1801 // Restrict this fold to single-use 'and' (PR10267).
1802 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1803 if (C2->isSignMask()) {
1804 Constant *Zero = Constant::getNullValue(X->getType());
1805 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1806 return new ICmpInst(NewPred, X, Zero);
1809 APInt NewC2 = *C2;
1810 KnownBits Know = computeKnownBits(And->getOperand(0), 0, And);
1811 // Set high zeros of C2 to allow matching negated power-of-2.
1812 NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
1813 Know.countMinLeadingZeros());
1815 // Restrict this fold only for single-use 'and' (PR10267).
1816 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1817 if (NewC2.isNegatedPowerOf2()) {
1818 Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1819 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1820 return new ICmpInst(NewPred, X, NegBOC);
1824 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1825 // the input width without changing the value produced, eliminate the cast:
1827 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1829 // We can do this transformation if the constants do not have their sign bits
1830 // set or if it is an equality comparison. Extending a relational comparison
1831 // when we're checking the sign bit would not work.
1832 Value *W;
1833 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1834 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1835 // TODO: Is this a good transform for vectors? Wider types may reduce
1836 // throughput. Should this transform be limited (even for scalars) by using
1837 // shouldChangeType()?
1838 if (!Cmp.getType()->isVectorTy()) {
1839 Type *WideType = W->getType();
1840 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1841 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1842 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1843 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1844 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1848 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1849 return I;
1851 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1852 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1854 // iff pred isn't signed
1855 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1856 match(And->getOperand(1), m_One())) {
1857 Constant *One = cast<Constant>(And->getOperand(1));
1858 Value *Or = And->getOperand(0);
1859 Value *A, *B, *LShr;
1860 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1861 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1862 unsigned UsesRemoved = 0;
1863 if (And->hasOneUse())
1864 ++UsesRemoved;
1865 if (Or->hasOneUse())
1866 ++UsesRemoved;
1867 if (LShr->hasOneUse())
1868 ++UsesRemoved;
1870 // Compute A & ((1 << B) | 1)
1871 unsigned RequireUsesRemoved = match(B, m_ImmConstant()) ? 1 : 3;
1872 if (UsesRemoved >= RequireUsesRemoved) {
1873 Value *NewOr =
1874 Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1875 /*HasNUW=*/true),
1876 One, Or->getName());
1877 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1878 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1883 // (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->
1884 // llvm.is.fpclass(X, fcInf|fcNan)
1885 // (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->
1886 // llvm.is.fpclass(X, ~(fcInf|fcNan))
1887 Value *V;
1888 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1889 Attribute::NoImplicitFloat) &&
1890 Cmp.isEquality() &&
1891 match(X, m_OneUse(m_ElementWiseBitCast(m_Value(V))))) {
1892 Type *FPType = V->getType()->getScalarType();
1893 if (FPType->isIEEELikeFPTy() && C1 == *C2) {
1894 APInt ExponentMask =
1895 APFloat::getInf(FPType->getFltSemantics()).bitcastToAPInt();
1896 if (C1 == ExponentMask) {
1897 unsigned Mask = FPClassTest::fcNan | FPClassTest::fcInf;
1898 if (isICMP_NE)
1899 Mask = ~Mask & fcAllFlags;
1900 return replaceInstUsesWith(Cmp, Builder.createIsFPClass(V, Mask));
1905 return nullptr;
1908 /// Fold icmp (and X, Y), C.
1909 Instruction *InstCombinerImpl::foldICmpAndConstant(ICmpInst &Cmp,
1910 BinaryOperator *And,
1911 const APInt &C) {
1912 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1913 return I;
1915 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1916 bool TrueIfNeg;
1917 if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1918 // ((X - 1) & ~X) < 0 --> X == 0
1919 // ((X - 1) & ~X) >= 0 --> X != 0
1920 Value *X;
1921 if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1922 match(And->getOperand(1), m_Not(m_Specific(X)))) {
1923 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1924 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1926 // (X & -X) < 0 --> X == MinSignedC
1927 // (X & -X) > -1 --> X != MinSignedC
1928 if (match(And, m_c_And(m_Neg(m_Value(X)), m_Deferred(X)))) {
1929 Constant *MinSignedC = ConstantInt::get(
1930 X->getType(),
1931 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits()));
1932 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1933 return new ICmpInst(NewPred, X, MinSignedC);
1937 // TODO: These all require that Y is constant too, so refactor with the above.
1939 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1940 Value *X = And->getOperand(0);
1941 Value *Y = And->getOperand(1);
1942 if (auto *C2 = dyn_cast<ConstantInt>(Y))
1943 if (auto *LI = dyn_cast<LoadInst>(X))
1944 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1945 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1946 if (Instruction *Res =
1947 foldCmpLoadFromIndexedGlobal(LI, GEP, GV, Cmp, C2))
1948 return Res;
1950 if (!Cmp.isEquality())
1951 return nullptr;
1953 // X & -C == -C -> X > u ~C
1954 // X & -C != -C -> X <= u ~C
1955 // iff C is a power of 2
1956 if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
1957 auto NewPred =
1958 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT : CmpInst::ICMP_ULE;
1959 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1962 // If we are testing the intersection of 2 select-of-nonzero-constants with no
1963 // common bits set, it's the same as checking if exactly one select condition
1964 // is set:
1965 // ((A ? TC : FC) & (B ? TC : FC)) == 0 --> xor A, B
1966 // ((A ? TC : FC) & (B ? TC : FC)) != 0 --> not(xor A, B)
1967 // TODO: Generalize for non-constant values.
1968 // TODO: Handle signed/unsigned predicates.
1969 // TODO: Handle other bitwise logic connectors.
1970 // TODO: Extend to handle a non-zero compare constant.
1971 if (C.isZero() && (Pred == CmpInst::ICMP_EQ || And->hasOneUse())) {
1972 assert(Cmp.isEquality() && "Not expecting non-equality predicates");
1973 Value *A, *B;
1974 const APInt *TC, *FC;
1975 if (match(X, m_Select(m_Value(A), m_APInt(TC), m_APInt(FC))) &&
1976 match(Y,
1977 m_Select(m_Value(B), m_SpecificInt(*TC), m_SpecificInt(*FC))) &&
1978 !TC->isZero() && !FC->isZero() && !TC->intersects(*FC)) {
1979 Value *R = Builder.CreateXor(A, B);
1980 if (Pred == CmpInst::ICMP_NE)
1981 R = Builder.CreateNot(R);
1982 return replaceInstUsesWith(Cmp, R);
1986 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
1987 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
1988 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
1989 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
1990 if (match(And, m_OneUse(m_c_And(m_OneUse(m_ZExt(m_Value(X))), m_Value(Y)))) &&
1991 X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
1992 Value *TruncY = Builder.CreateTrunc(Y, X->getType());
1993 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
1994 Value *And = Builder.CreateAnd(TruncY, X);
1995 return BinaryOperator::CreateNot(And);
1997 return BinaryOperator::CreateAnd(TruncY, X);
2000 // (icmp eq/ne (and (shl -1, X), Y), 0)
2001 // -> (icmp eq/ne (lshr Y, X), 0)
2002 // We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems
2003 // highly unlikely the non-zero case will ever show up in code.
2004 if (C.isZero() &&
2005 match(And, m_OneUse(m_c_And(m_OneUse(m_Shl(m_AllOnes(), m_Value(X))),
2006 m_Value(Y))))) {
2007 Value *LShr = Builder.CreateLShr(Y, X);
2008 return new ICmpInst(Pred, LShr, Constant::getNullValue(LShr->getType()));
2011 // (icmp eq/ne (and (add A, Addend), Msk), C)
2012 // -> (icmp eq/ne (and A, Msk), (and (sub C, Addend), Msk))
2014 Value *A;
2015 const APInt *Addend, *Msk;
2016 if (match(And, m_And(m_OneUse(m_Add(m_Value(A), m_APInt(Addend))),
2017 m_LowBitMask(Msk))) &&
2018 C.ule(*Msk)) {
2019 APInt NewComperand = (C - *Addend) & *Msk;
2020 Value *MaskA = Builder.CreateAnd(A, ConstantInt::get(A->getType(), *Msk));
2021 return new ICmpInst(Pred, MaskA,
2022 ConstantInt::get(MaskA->getType(), NewComperand));
2026 return nullptr;
2029 /// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
2030 static Value *foldICmpOrXorSubChain(ICmpInst &Cmp, BinaryOperator *Or,
2031 InstCombiner::BuilderTy &Builder) {
2032 // Are we using xors or subs to bitwise check for a pair or pairs of
2033 // (in)equalities? Convert to a shorter form that has more potential to be
2034 // folded even further.
2035 // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
2036 // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
2037 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
2038 // (X1 == X2) && (X3 == X4) && (X5 == X6)
2039 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
2040 // (X1 != X2) || (X3 != X4) || (X5 != X6)
2041 SmallVector<std::pair<Value *, Value *>, 2> CmpValues;
2042 SmallVector<Value *, 16> WorkList(1, Or);
2044 while (!WorkList.empty()) {
2045 auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
2046 Value *Lhs, *Rhs;
2048 if (match(OrOperatorArgument,
2049 m_OneUse(m_Xor(m_Value(Lhs), m_Value(Rhs))))) {
2050 CmpValues.emplace_back(Lhs, Rhs);
2051 return;
2054 if (match(OrOperatorArgument,
2055 m_OneUse(m_Sub(m_Value(Lhs), m_Value(Rhs))))) {
2056 CmpValues.emplace_back(Lhs, Rhs);
2057 return;
2060 WorkList.push_back(OrOperatorArgument);
2063 Value *CurrentValue = WorkList.pop_back_val();
2064 Value *OrOperatorLhs, *OrOperatorRhs;
2066 if (!match(CurrentValue,
2067 m_Or(m_Value(OrOperatorLhs), m_Value(OrOperatorRhs)))) {
2068 return nullptr;
2071 MatchOrOperatorArgument(OrOperatorRhs);
2072 MatchOrOperatorArgument(OrOperatorLhs);
2075 ICmpInst::Predicate Pred = Cmp.getPredicate();
2076 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2077 Value *LhsCmp = Builder.CreateICmp(Pred, CmpValues.rbegin()->first,
2078 CmpValues.rbegin()->second);
2080 for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
2081 Value *RhsCmp = Builder.CreateICmp(Pred, It->first, It->second);
2082 LhsCmp = Builder.CreateBinOp(BOpc, LhsCmp, RhsCmp);
2085 return LhsCmp;
2088 /// Fold icmp (or X, Y), C.
2089 Instruction *InstCombinerImpl::foldICmpOrConstant(ICmpInst &Cmp,
2090 BinaryOperator *Or,
2091 const APInt &C) {
2092 ICmpInst::Predicate Pred = Cmp.getPredicate();
2093 if (C.isOne()) {
2094 // icmp slt signum(V) 1 --> icmp slt V, 1
2095 Value *V = nullptr;
2096 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
2097 return new ICmpInst(ICmpInst::ICMP_SLT, V,
2098 ConstantInt::get(V->getType(), 1));
2101 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
2103 // (icmp eq/ne (or disjoint x, C0), C1)
2104 // -> (icmp eq/ne x, C0^C1)
2105 if (Cmp.isEquality() && match(OrOp1, m_ImmConstant()) &&
2106 cast<PossiblyDisjointInst>(Or)->isDisjoint()) {
2107 Value *NewC =
2108 Builder.CreateXor(OrOp1, ConstantInt::get(OrOp1->getType(), C));
2109 return new ICmpInst(Pred, OrOp0, NewC);
2112 const APInt *MaskC;
2113 if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
2114 if (*MaskC == C && (C + 1).isPowerOf2()) {
2115 // X | C == C --> X <=u C
2116 // X | C != C --> X >u C
2117 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
2118 Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT;
2119 return new ICmpInst(Pred, OrOp0, OrOp1);
2122 // More general: canonicalize 'equality with set bits mask' to
2123 // 'equality with clear bits mask'.
2124 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2125 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2126 if (Or->hasOneUse()) {
2127 Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
2128 Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
2129 return new ICmpInst(Pred, And, NewC);
2133 // (X | (X-1)) s< 0 --> X s< 1
2134 // (X | (X-1)) s> -1 --> X s> 0
2135 Value *X;
2136 bool TrueIfSigned;
2137 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
2138 match(Or, m_c_Or(m_Add(m_Value(X), m_AllOnes()), m_Deferred(X)))) {
2139 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2140 Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
2141 return new ICmpInst(NewPred, X, NewC);
2144 const APInt *OrC;
2145 // icmp(X | OrC, C) --> icmp(X, 0)
2146 if (C.isNonNegative() && match(Or, m_Or(m_Value(X), m_APInt(OrC)))) {
2147 switch (Pred) {
2148 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2149 case ICmpInst::ICMP_SLT:
2150 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2151 case ICmpInst::ICMP_SGE:
2152 if (OrC->sge(C))
2153 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2154 break;
2155 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2156 case ICmpInst::ICMP_SLE:
2157 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2158 case ICmpInst::ICMP_SGT:
2159 if (OrC->sgt(C))
2160 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(Pred), X,
2161 ConstantInt::getNullValue(X->getType()));
2162 break;
2163 default:
2164 break;
2168 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2169 return nullptr;
2171 Value *P, *Q;
2172 if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
2173 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2174 // -> and (icmp eq P, null), (icmp eq Q, null).
2175 Value *CmpP =
2176 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
2177 Value *CmpQ =
2178 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
2179 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2180 return BinaryOperator::Create(BOpc, CmpP, CmpQ);
2183 if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2184 return replaceInstUsesWith(Cmp, V);
2186 return nullptr;
2189 /// Fold icmp (mul X, Y), C.
2190 Instruction *InstCombinerImpl::foldICmpMulConstant(ICmpInst &Cmp,
2191 BinaryOperator *Mul,
2192 const APInt &C) {
2193 ICmpInst::Predicate Pred = Cmp.getPredicate();
2194 Type *MulTy = Mul->getType();
2195 Value *X = Mul->getOperand(0);
2197 // If there's no overflow:
2198 // X * X == 0 --> X == 0
2199 // X * X != 0 --> X != 0
2200 if (Cmp.isEquality() && C.isZero() && X == Mul->getOperand(1) &&
2201 (Mul->hasNoUnsignedWrap() || Mul->hasNoSignedWrap()))
2202 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2204 const APInt *MulC;
2205 if (!match(Mul->getOperand(1), m_APInt(MulC)))
2206 return nullptr;
2208 // If this is a test of the sign bit and the multiply is sign-preserving with
2209 // a constant operand, use the multiply LHS operand instead:
2210 // (X * +MulC) < 0 --> X < 0
2211 // (X * -MulC) < 0 --> X > 0
2212 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2213 if (MulC->isNegative())
2214 Pred = ICmpInst::getSwappedPredicate(Pred);
2215 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2218 if (MulC->isZero())
2219 return nullptr;
2221 // If the multiply does not wrap or the constant is odd, try to divide the
2222 // compare constant by the multiplication factor.
2223 if (Cmp.isEquality()) {
2224 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2225 if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
2226 Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
2227 return new ICmpInst(Pred, X, NewC);
2230 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2231 // correct to transform if MulC * N == C including overflow. I.e with i8
2232 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2233 // miss that case.
2234 if (C.urem(*MulC).isZero()) {
2235 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2236 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2237 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2238 Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
2239 return new ICmpInst(Pred, X, NewC);
2244 // With a matching no-overflow guarantee, fold the constants:
2245 // (X * MulC) < C --> X < (C / MulC)
2246 // (X * MulC) > C --> X > (C / MulC)
2247 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2248 Constant *NewC = nullptr;
2249 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2250 // MININT / -1 --> overflow.
2251 if (C.isMinSignedValue() && MulC->isAllOnes())
2252 return nullptr;
2253 if (MulC->isNegative())
2254 Pred = ICmpInst::getSwappedPredicate(Pred);
2256 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2257 NewC = ConstantInt::get(
2258 MulTy, APIntOps::RoundingSDiv(C, *MulC, APInt::Rounding::UP));
2259 } else {
2260 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2261 "Unexpected predicate");
2262 NewC = ConstantInt::get(
2263 MulTy, APIntOps::RoundingSDiv(C, *MulC, APInt::Rounding::DOWN));
2265 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2266 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2267 NewC = ConstantInt::get(
2268 MulTy, APIntOps::RoundingUDiv(C, *MulC, APInt::Rounding::UP));
2269 } else {
2270 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2271 "Unexpected predicate");
2272 NewC = ConstantInt::get(
2273 MulTy, APIntOps::RoundingUDiv(C, *MulC, APInt::Rounding::DOWN));
2277 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2280 /// Fold icmp (shl nuw C2, Y), C.
2281 static Instruction *foldICmpShlLHSC(ICmpInst &Cmp, Instruction *Shl,
2282 const APInt &C) {
2283 Value *Y;
2284 const APInt *C2;
2285 if (!match(Shl, m_NUWShl(m_APInt(C2), m_Value(Y))))
2286 return nullptr;
2288 Type *ShiftType = Shl->getType();
2289 unsigned TypeBits = C.getBitWidth();
2290 ICmpInst::Predicate Pred = Cmp.getPredicate();
2291 if (Cmp.isUnsigned()) {
2292 if (C2->isZero() || C2->ugt(C))
2293 return nullptr;
2294 APInt Div, Rem;
2295 APInt::udivrem(C, *C2, Div, Rem);
2296 bool CIsPowerOf2 = Rem.isZero() && Div.isPowerOf2();
2298 // (1 << Y) pred C -> Y pred Log2(C)
2299 if (!CIsPowerOf2) {
2300 // (1 << Y) < 30 -> Y <= 4
2301 // (1 << Y) <= 30 -> Y <= 4
2302 // (1 << Y) >= 30 -> Y > 4
2303 // (1 << Y) > 30 -> Y > 4
2304 if (Pred == ICmpInst::ICMP_ULT)
2305 Pred = ICmpInst::ICMP_ULE;
2306 else if (Pred == ICmpInst::ICMP_UGE)
2307 Pred = ICmpInst::ICMP_UGT;
2310 unsigned CLog2 = Div.logBase2();
2311 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2312 } else if (Cmp.isSigned() && C2->isOne()) {
2313 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2314 // (1 << Y) > 0 -> Y != 31
2315 // (1 << Y) > C -> Y != 31 if C is negative.
2316 if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
2317 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2319 // (1 << Y) < 0 -> Y == 31
2320 // (1 << Y) < 1 -> Y == 31
2321 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2322 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2323 if (Pred == ICmpInst::ICMP_SLT && (C - 1).sle(0))
2324 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2327 return nullptr;
2330 /// Fold icmp (shl X, Y), C.
2331 Instruction *InstCombinerImpl::foldICmpShlConstant(ICmpInst &Cmp,
2332 BinaryOperator *Shl,
2333 const APInt &C) {
2334 const APInt *ShiftVal;
2335 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2336 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2338 ICmpInst::Predicate Pred = Cmp.getPredicate();
2339 // (icmp pred (shl nuw&nsw X, Y), Csle0)
2340 // -> (icmp pred X, Csle0)
2342 // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2343 // so X's must be what is used.
2344 if (C.sle(0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2345 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2347 // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2348 // -> (icmp eq/ne X, 0)
2349 if (ICmpInst::isEquality(Pred) && C.isZero() &&
2350 (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2351 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2353 // (icmp slt (shl nsw X, Y), 0/1)
2354 // -> (icmp slt X, 0/1)
2355 // (icmp sgt (shl nsw X, Y), 0/-1)
2356 // -> (icmp sgt X, 0/-1)
2358 // NB: sge/sle with a constant will canonicalize to sgt/slt.
2359 if (Shl->hasNoSignedWrap() &&
2360 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2361 if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2362 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2364 const APInt *ShiftAmt;
2365 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2366 return foldICmpShlLHSC(Cmp, Shl, C);
2368 // Check that the shift amount is in range. If not, don't perform undefined
2369 // shifts. When the shift is visited, it will be simplified.
2370 unsigned TypeBits = C.getBitWidth();
2371 if (ShiftAmt->uge(TypeBits))
2372 return nullptr;
2374 Value *X = Shl->getOperand(0);
2375 Type *ShType = Shl->getType();
2377 // NSW guarantees that we are only shifting out sign bits from the high bits,
2378 // so we can ASHR the compare constant without needing a mask and eliminate
2379 // the shift.
2380 if (Shl->hasNoSignedWrap()) {
2381 if (Pred == ICmpInst::ICMP_SGT) {
2382 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2383 APInt ShiftedC = C.ashr(*ShiftAmt);
2384 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2386 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2387 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2388 APInt ShiftedC = C.ashr(*ShiftAmt);
2389 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2391 if (Pred == ICmpInst::ICMP_SLT) {
2392 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2393 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2394 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2395 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2396 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2397 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2398 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2402 // NUW guarantees that we are only shifting out zero bits from the high bits,
2403 // so we can LSHR the compare constant without needing a mask and eliminate
2404 // the shift.
2405 if (Shl->hasNoUnsignedWrap()) {
2406 if (Pred == ICmpInst::ICMP_UGT) {
2407 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2408 APInt ShiftedC = C.lshr(*ShiftAmt);
2409 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2411 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2412 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2413 APInt ShiftedC = C.lshr(*ShiftAmt);
2414 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2416 if (Pred == ICmpInst::ICMP_ULT) {
2417 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2418 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2419 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2420 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2421 assert(C.ugt(0) && "ult 0 should have been eliminated");
2422 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2423 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2427 if (Cmp.isEquality() && Shl->hasOneUse()) {
2428 // Strength-reduce the shift into an 'and'.
2429 Constant *Mask = ConstantInt::get(
2430 ShType,
2431 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2432 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2433 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2434 return new ICmpInst(Pred, And, LShrC);
2437 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2438 bool TrueIfSigned = false;
2439 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2440 // (X << 31) <s 0 --> (X & 1) != 0
2441 Constant *Mask = ConstantInt::get(
2442 ShType,
2443 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2444 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2445 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2446 And, Constant::getNullValue(ShType));
2449 // Simplify 'shl' inequality test into 'and' equality test.
2450 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2451 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2452 if ((C + 1).isPowerOf2() &&
2453 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2454 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2455 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2456 : ICmpInst::ICMP_NE,
2457 And, Constant::getNullValue(ShType));
2459 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2460 if (C.isPowerOf2() &&
2461 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2462 Value *And =
2463 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2464 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2465 : ICmpInst::ICMP_NE,
2466 And, Constant::getNullValue(ShType));
2470 // Transform (icmp pred iM (shl iM %v, N), C)
2471 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2472 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2473 // This enables us to get rid of the shift in favor of a trunc that may be
2474 // free on the target. It has the additional benefit of comparing to a
2475 // smaller constant that may be more target-friendly.
2476 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2477 if (Shl->hasOneUse() && Amt != 0 &&
2478 shouldChangeType(ShType->getScalarSizeInBits(), TypeBits - Amt)) {
2479 ICmpInst::Predicate CmpPred = Pred;
2480 APInt RHSC = C;
2482 if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(CmpPred)) {
2483 // Try the flipped strictness predicate.
2484 // e.g.:
2485 // icmp ult i64 (shl X, 32), 8589934593 ->
2486 // icmp ule i64 (shl X, 32), 8589934592 ->
2487 // icmp ule i32 (trunc X, i32), 2 ->
2488 // icmp ult i32 (trunc X, i32), 3
2489 if (auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(
2490 Pred, ConstantInt::get(ShType->getContext(), C))) {
2491 CmpPred = FlippedStrictness->first;
2492 RHSC = cast<ConstantInt>(FlippedStrictness->second)->getValue();
2496 if (RHSC.countr_zero() >= Amt) {
2497 Type *TruncTy = ShType->getWithNewBitWidth(TypeBits - Amt);
2498 Constant *NewC =
2499 ConstantInt::get(TruncTy, RHSC.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2500 return new ICmpInst(CmpPred,
2501 Builder.CreateTrunc(X, TruncTy, "", /*IsNUW=*/false,
2502 Shl->hasNoSignedWrap()),
2503 NewC);
2507 return nullptr;
2510 /// Fold icmp ({al}shr X, Y), C.
2511 Instruction *InstCombinerImpl::foldICmpShrConstant(ICmpInst &Cmp,
2512 BinaryOperator *Shr,
2513 const APInt &C) {
2514 // An exact shr only shifts out zero bits, so:
2515 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2516 Value *X = Shr->getOperand(0);
2517 CmpInst::Predicate Pred = Cmp.getPredicate();
2518 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2519 return new ICmpInst(Pred, X, Cmp.getOperand(1));
2521 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2522 const APInt *ShiftValC;
2523 if (match(X, m_APInt(ShiftValC))) {
2524 if (Cmp.isEquality())
2525 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2527 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2528 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2529 bool TrueIfSigned;
2530 if (!IsAShr && ShiftValC->isNegative() &&
2531 isSignBitCheck(Pred, C, TrueIfSigned))
2532 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2533 Shr->getOperand(1),
2534 ConstantInt::getNullValue(X->getType()));
2536 // If the shifted constant is a power-of-2, test the shift amount directly:
2537 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2538 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2539 if (!IsAShr && ShiftValC->isPowerOf2() &&
2540 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2541 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2542 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2543 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2545 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2546 unsigned ShiftLZ = ShiftValC->countl_zero();
2547 Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2548 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2549 return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2553 const APInt *ShiftAmtC;
2554 if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2555 return nullptr;
2557 // Check that the shift amount is in range. If not, don't perform undefined
2558 // shifts. When the shift is visited it will be simplified.
2559 unsigned TypeBits = C.getBitWidth();
2560 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2561 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2562 return nullptr;
2564 bool IsExact = Shr->isExact();
2565 Type *ShrTy = Shr->getType();
2566 // TODO: If we could guarantee that InstSimplify would handle all of the
2567 // constant-value-based preconditions in the folds below, then we could assert
2568 // those conditions rather than checking them. This is difficult because of
2569 // undef/poison (PR34838).
2570 if (IsAShr && Shr->hasOneUse()) {
2571 if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&
2572 (C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {
2573 // When C - 1 is a power of two and the transform can be legally
2574 // performed, prefer this form so the produced constant is close to a
2575 // power of two.
2576 // icmp slt/ult (ashr exact X, ShAmtC), C
2577 // --> icmp slt/ult X, (C - 1) << ShAmtC) + 1
2578 APInt ShiftedC = (C - 1).shl(ShAmtVal) + 1;
2579 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2581 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2582 // When ShAmtC can be shifted losslessly:
2583 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2584 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2585 APInt ShiftedC = C.shl(ShAmtVal);
2586 if (ShiftedC.ashr(ShAmtVal) == C)
2587 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2589 if (Pred == CmpInst::ICMP_SGT) {
2590 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2591 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2592 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2593 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2594 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2596 if (Pred == CmpInst::ICMP_UGT) {
2597 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2598 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2599 // clause accounts for that pattern.
2600 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2601 if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2602 (C + 1).shl(ShAmtVal).isMinSignedValue())
2603 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2606 // If the compare constant has significant bits above the lowest sign-bit,
2607 // then convert an unsigned cmp to a test of the sign-bit:
2608 // (ashr X, ShiftC) u> C --> X s< 0
2609 // (ashr X, ShiftC) u< C --> X s> -1
2610 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2611 if (Pred == CmpInst::ICMP_UGT) {
2612 return new ICmpInst(CmpInst::ICMP_SLT, X,
2613 ConstantInt::getNullValue(ShrTy));
2615 if (Pred == CmpInst::ICMP_ULT) {
2616 return new ICmpInst(CmpInst::ICMP_SGT, X,
2617 ConstantInt::getAllOnesValue(ShrTy));
2620 } else if (!IsAShr) {
2621 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2622 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2623 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2624 APInt ShiftedC = C.shl(ShAmtVal);
2625 if (ShiftedC.lshr(ShAmtVal) == C)
2626 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2628 if (Pred == CmpInst::ICMP_UGT) {
2629 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2630 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2631 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2632 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2636 if (!Cmp.isEquality())
2637 return nullptr;
2639 // Handle equality comparisons of shift-by-constant.
2641 // If the comparison constant changes with the shift, the comparison cannot
2642 // succeed (bits of the comparison constant cannot match the shifted value).
2643 // This should be known by InstSimplify and already be folded to true/false.
2644 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2645 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2646 "Expected icmp+shr simplify did not occur.");
2648 // If the bits shifted out are known zero, compare the unshifted value:
2649 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2650 if (Shr->isExact())
2651 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2653 if (C.isZero()) {
2654 // == 0 is u< 1.
2655 if (Pred == CmpInst::ICMP_EQ)
2656 return new ICmpInst(CmpInst::ICMP_ULT, X,
2657 ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal)));
2658 else
2659 return new ICmpInst(CmpInst::ICMP_UGT, X,
2660 ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal) - 1));
2663 if (Shr->hasOneUse()) {
2664 // Canonicalize the shift into an 'and':
2665 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2666 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2667 Constant *Mask = ConstantInt::get(ShrTy, Val);
2668 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2669 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2672 return nullptr;
2675 Instruction *InstCombinerImpl::foldICmpSRemConstant(ICmpInst &Cmp,
2676 BinaryOperator *SRem,
2677 const APInt &C) {
2678 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2679 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT) {
2680 // Canonicalize unsigned predicates to signed:
2681 // (X s% DivisorC) u> C -> (X s% DivisorC) s< 0
2682 // iff (C s< 0 ? ~C : C) u>= abs(DivisorC)-1
2683 // (X s% DivisorC) u< C+1 -> (X s% DivisorC) s> -1
2684 // iff (C+1 s< 0 ? ~C : C) u>= abs(DivisorC)-1
2686 const APInt *DivisorC;
2687 if (!match(SRem->getOperand(1), m_APInt(DivisorC)))
2688 return nullptr;
2690 APInt NormalizedC = C;
2691 if (Pred == ICmpInst::ICMP_ULT) {
2692 assert(!NormalizedC.isZero() &&
2693 "ult X, 0 should have been simplified already.");
2694 --NormalizedC;
2696 if (C.isNegative())
2697 NormalizedC.flipAllBits();
2698 assert(!DivisorC->isZero() &&
2699 "srem X, 0 should have been simplified already.");
2700 if (!NormalizedC.uge(DivisorC->abs() - 1))
2701 return nullptr;
2703 Type *Ty = SRem->getType();
2704 if (Pred == ICmpInst::ICMP_UGT)
2705 return new ICmpInst(ICmpInst::ICMP_SLT, SRem,
2706 ConstantInt::getNullValue(Ty));
2707 return new ICmpInst(ICmpInst::ICMP_SGT, SRem,
2708 ConstantInt::getAllOnesValue(Ty));
2710 // Match an 'is positive' or 'is negative' comparison of remainder by a
2711 // constant power-of-2 value:
2712 // (X % pow2C) sgt/slt 0
2713 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2714 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2715 return nullptr;
2717 // TODO: The one-use check is standard because we do not typically want to
2718 // create longer instruction sequences, but this might be a special-case
2719 // because srem is not good for analysis or codegen.
2720 if (!SRem->hasOneUse())
2721 return nullptr;
2723 const APInt *DivisorC;
2724 if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2725 return nullptr;
2727 // For cmp_sgt/cmp_slt only zero valued C is handled.
2728 // For cmp_eq/cmp_ne only positive valued C is handled.
2729 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2730 !C.isZero()) ||
2731 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2732 !C.isStrictlyPositive()))
2733 return nullptr;
2735 // Mask off the sign bit and the modulo bits (low-bits).
2736 Type *Ty = SRem->getType();
2737 APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
2738 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2739 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2741 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2742 return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2744 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2745 // bit is set. Example:
2746 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2747 if (Pred == ICmpInst::ICMP_SGT)
2748 return new ICmpInst(ICmpInst::ICMP_SGT, And, ConstantInt::getNullValue(Ty));
2750 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2751 // bit is set. Example:
2752 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2753 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2756 /// Fold icmp (udiv X, Y), C.
2757 Instruction *InstCombinerImpl::foldICmpUDivConstant(ICmpInst &Cmp,
2758 BinaryOperator *UDiv,
2759 const APInt &C) {
2760 ICmpInst::Predicate Pred = Cmp.getPredicate();
2761 Value *X = UDiv->getOperand(0);
2762 Value *Y = UDiv->getOperand(1);
2763 Type *Ty = UDiv->getType();
2765 const APInt *C2;
2766 if (!match(X, m_APInt(C2)))
2767 return nullptr;
2769 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2771 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2772 if (Pred == ICmpInst::ICMP_UGT) {
2773 assert(!C.isMaxValue() &&
2774 "icmp ugt X, UINT_MAX should have been simplified already.");
2775 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2776 ConstantInt::get(Ty, C2->udiv(C + 1)));
2779 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2780 if (Pred == ICmpInst::ICMP_ULT) {
2781 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2782 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2783 ConstantInt::get(Ty, C2->udiv(C)));
2786 return nullptr;
2789 /// Fold icmp ({su}div X, Y), C.
2790 Instruction *InstCombinerImpl::foldICmpDivConstant(ICmpInst &Cmp,
2791 BinaryOperator *Div,
2792 const APInt &C) {
2793 ICmpInst::Predicate Pred = Cmp.getPredicate();
2794 Value *X = Div->getOperand(0);
2795 Value *Y = Div->getOperand(1);
2796 Type *Ty = Div->getType();
2797 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2799 // If unsigned division and the compare constant is bigger than
2800 // UMAX/2 (negative), there's only one pair of values that satisfies an
2801 // equality check, so eliminate the division:
2802 // (X u/ Y) == C --> (X == C) && (Y == 1)
2803 // (X u/ Y) != C --> (X != C) || (Y != 1)
2804 // Similarly, if signed division and the compare constant is exactly SMIN:
2805 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2806 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2807 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2808 (!DivIsSigned || C.isMinSignedValue())) {
2809 Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2810 Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2811 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2812 return BinaryOperator::Create(Logic, XBig, YOne);
2815 // Fold: icmp pred ([us]div X, C2), C -> range test
2816 // Fold this div into the comparison, producing a range check.
2817 // Determine, based on the divide type, what the range is being
2818 // checked. If there is an overflow on the low or high side, remember
2819 // it, otherwise compute the range [low, hi) bounding the new value.
2820 // See: InsertRangeTest above for the kinds of replacements possible.
2821 const APInt *C2;
2822 if (!match(Y, m_APInt(C2)))
2823 return nullptr;
2825 // FIXME: If the operand types don't match the type of the divide
2826 // then don't attempt this transform. The code below doesn't have the
2827 // logic to deal with a signed divide and an unsigned compare (and
2828 // vice versa). This is because (x /s C2) <s C produces different
2829 // results than (x /s C2) <u C or (x /u C2) <s C or even
2830 // (x /u C2) <u C. Simply casting the operands and result won't
2831 // work. :( The if statement below tests that condition and bails
2832 // if it finds it.
2833 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
2834 return nullptr;
2836 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2837 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2838 // division-by-constant cases should be present, we can not assert that they
2839 // have happened before we reach this icmp instruction.
2840 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2841 return nullptr;
2843 // Compute Prod = C * C2. We are essentially solving an equation of
2844 // form X / C2 = C. We solve for X by multiplying C2 and C.
2845 // By solving for X, we can turn this into a range check instead of computing
2846 // a divide.
2847 APInt Prod = C * *C2;
2849 // Determine if the product overflows by seeing if the product is not equal to
2850 // the divide. Make sure we do the same kind of divide as in the LHS
2851 // instruction that we're folding.
2852 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2854 // If the division is known to be exact, then there is no remainder from the
2855 // divide, so the covered range size is unit, otherwise it is the divisor.
2856 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2858 // Figure out the interval that is being checked. For example, a comparison
2859 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2860 // Compute this interval based on the constants involved and the signedness of
2861 // the compare/divide. This computes a half-open interval, keeping track of
2862 // whether either value in the interval overflows. After analysis each
2863 // overflow variable is set to 0 if it's corresponding bound variable is valid
2864 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2865 int LoOverflow = 0, HiOverflow = 0;
2866 APInt LoBound, HiBound;
2868 if (!DivIsSigned) { // udiv
2869 // e.g. X/5 op 3 --> [15, 20)
2870 LoBound = Prod;
2871 HiOverflow = LoOverflow = ProdOV;
2872 if (!HiOverflow) {
2873 // If this is not an exact divide, then many values in the range collapse
2874 // to the same result value.
2875 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2877 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2878 if (C.isZero()) { // (X / pos) op 0
2879 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2880 LoBound = -(RangeSize - 1);
2881 HiBound = RangeSize;
2882 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2883 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2884 HiOverflow = LoOverflow = ProdOV;
2885 if (!HiOverflow)
2886 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2887 } else { // (X / pos) op neg
2888 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2889 HiBound = Prod + 1;
2890 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2891 if (!LoOverflow) {
2892 APInt DivNeg = -RangeSize;
2893 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2896 } else if (C2->isNegative()) { // Divisor is < 0.
2897 if (Div->isExact())
2898 RangeSize.negate();
2899 if (C.isZero()) { // (X / neg) op 0
2900 // e.g. X/-5 op 0 --> [-4, 5)
2901 LoBound = RangeSize + 1;
2902 HiBound = -RangeSize;
2903 if (HiBound == *C2) { // -INTMIN = INTMIN
2904 HiOverflow = 1; // [INTMIN+1, overflow)
2905 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2907 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2908 // e.g. X/-5 op 3 --> [-19, -14)
2909 HiBound = Prod + 1;
2910 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2911 if (!LoOverflow)
2912 LoOverflow =
2913 addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
2914 } else { // (X / neg) op neg
2915 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2916 LoOverflow = HiOverflow = ProdOV;
2917 if (!HiOverflow)
2918 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2921 // Dividing by a negative swaps the condition. LT <-> GT
2922 Pred = ICmpInst::getSwappedPredicate(Pred);
2925 switch (Pred) {
2926 default:
2927 llvm_unreachable("Unhandled icmp predicate!");
2928 case ICmpInst::ICMP_EQ:
2929 if (LoOverflow && HiOverflow)
2930 return replaceInstUsesWith(Cmp, Builder.getFalse());
2931 if (HiOverflow)
2932 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2933 X, ConstantInt::get(Ty, LoBound));
2934 if (LoOverflow)
2935 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2936 X, ConstantInt::get(Ty, HiBound));
2937 return replaceInstUsesWith(
2938 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
2939 case ICmpInst::ICMP_NE:
2940 if (LoOverflow && HiOverflow)
2941 return replaceInstUsesWith(Cmp, Builder.getTrue());
2942 if (HiOverflow)
2943 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2944 X, ConstantInt::get(Ty, LoBound));
2945 if (LoOverflow)
2946 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2947 X, ConstantInt::get(Ty, HiBound));
2948 return replaceInstUsesWith(
2949 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
2950 case ICmpInst::ICMP_ULT:
2951 case ICmpInst::ICMP_SLT:
2952 if (LoOverflow == +1) // Low bound is greater than input range.
2953 return replaceInstUsesWith(Cmp, Builder.getTrue());
2954 if (LoOverflow == -1) // Low bound is less than input range.
2955 return replaceInstUsesWith(Cmp, Builder.getFalse());
2956 return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
2957 case ICmpInst::ICMP_UGT:
2958 case ICmpInst::ICMP_SGT:
2959 if (HiOverflow == +1) // High bound greater than input range.
2960 return replaceInstUsesWith(Cmp, Builder.getFalse());
2961 if (HiOverflow == -1) // High bound less than input range.
2962 return replaceInstUsesWith(Cmp, Builder.getTrue());
2963 if (Pred == ICmpInst::ICMP_UGT)
2964 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
2965 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
2968 return nullptr;
2971 /// Fold icmp (sub X, Y), C.
2972 Instruction *InstCombinerImpl::foldICmpSubConstant(ICmpInst &Cmp,
2973 BinaryOperator *Sub,
2974 const APInt &C) {
2975 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
2976 ICmpInst::Predicate Pred = Cmp.getPredicate();
2977 Type *Ty = Sub->getType();
2979 // (SubC - Y) == C) --> Y == (SubC - C)
2980 // (SubC - Y) != C) --> Y != (SubC - C)
2981 Constant *SubC;
2982 if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
2983 return new ICmpInst(Pred, Y,
2984 ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C)));
2987 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
2988 const APInt *C2;
2989 APInt SubResult;
2990 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
2991 bool HasNSW = Sub->hasNoSignedWrap();
2992 bool HasNUW = Sub->hasNoUnsignedWrap();
2993 if (match(X, m_APInt(C2)) &&
2994 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
2995 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
2996 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
2998 // X - Y == 0 --> X == Y.
2999 // X - Y != 0 --> X != Y.
3000 // TODO: We allow this with multiple uses as long as the other uses are not
3001 // in phis. The phi use check is guarding against a codegen regression
3002 // for a loop test. If the backend could undo this (and possibly
3003 // subsequent transforms), we would not need this hack.
3004 if (Cmp.isEquality() && C.isZero() &&
3005 none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
3006 return new ICmpInst(Pred, X, Y);
3008 // The following transforms are only worth it if the only user of the subtract
3009 // is the icmp.
3010 // TODO: This is an artificial restriction for all of the transforms below
3011 // that only need a single replacement icmp. Can these use the phi test
3012 // like the transform above here?
3013 if (!Sub->hasOneUse())
3014 return nullptr;
3016 if (Sub->hasNoSignedWrap()) {
3017 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
3018 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3019 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3021 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
3022 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
3023 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3025 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
3026 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
3027 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3029 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
3030 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3031 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3034 if (!match(X, m_APInt(C2)))
3035 return nullptr;
3037 // C2 - Y <u C -> (Y | (C - 1)) == C2
3038 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
3039 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
3040 (*C2 & (C - 1)) == (C - 1))
3041 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
3043 // C2 - Y >u C -> (Y | C) != C2
3044 // iff C2 & C == C and C + 1 is a power of 2
3045 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
3046 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
3048 // We have handled special cases that reduce.
3049 // Canonicalize any remaining sub to add as:
3050 // (C2 - Y) > C --> (Y + ~C2) < ~C
3051 Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
3052 HasNUW, HasNSW);
3053 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
3056 static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
3057 Value *Op1, IRBuilderBase &Builder,
3058 bool HasOneUse) {
3059 auto FoldConstant = [&](bool Val) {
3060 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3061 if (Op0->getType()->isVectorTy())
3062 Res = ConstantVector::getSplat(
3063 cast<VectorType>(Op0->getType())->getElementCount(), Res);
3064 return Res;
3067 switch (Table.to_ulong()) {
3068 case 0: // 0 0 0 0
3069 return FoldConstant(false);
3070 case 1: // 0 0 0 1
3071 return HasOneUse ? Builder.CreateNot(Builder.CreateOr(Op0, Op1)) : nullptr;
3072 case 2: // 0 0 1 0
3073 return HasOneUse ? Builder.CreateAnd(Builder.CreateNot(Op0), Op1) : nullptr;
3074 case 3: // 0 0 1 1
3075 return Builder.CreateNot(Op0);
3076 case 4: // 0 1 0 0
3077 return HasOneUse ? Builder.CreateAnd(Op0, Builder.CreateNot(Op1)) : nullptr;
3078 case 5: // 0 1 0 1
3079 return Builder.CreateNot(Op1);
3080 case 6: // 0 1 1 0
3081 return Builder.CreateXor(Op0, Op1);
3082 case 7: // 0 1 1 1
3083 return HasOneUse ? Builder.CreateNot(Builder.CreateAnd(Op0, Op1)) : nullptr;
3084 case 8: // 1 0 0 0
3085 return Builder.CreateAnd(Op0, Op1);
3086 case 9: // 1 0 0 1
3087 return HasOneUse ? Builder.CreateNot(Builder.CreateXor(Op0, Op1)) : nullptr;
3088 case 10: // 1 0 1 0
3089 return Op1;
3090 case 11: // 1 0 1 1
3091 return HasOneUse ? Builder.CreateOr(Builder.CreateNot(Op0), Op1) : nullptr;
3092 case 12: // 1 1 0 0
3093 return Op0;
3094 case 13: // 1 1 0 1
3095 return HasOneUse ? Builder.CreateOr(Op0, Builder.CreateNot(Op1)) : nullptr;
3096 case 14: // 1 1 1 0
3097 return Builder.CreateOr(Op0, Op1);
3098 case 15: // 1 1 1 1
3099 return FoldConstant(true);
3100 default:
3101 llvm_unreachable("Invalid Operation");
3103 return nullptr;
3106 /// Fold icmp (add X, Y), C.
3107 Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp,
3108 BinaryOperator *Add,
3109 const APInt &C) {
3110 Value *Y = Add->getOperand(1);
3111 Value *X = Add->getOperand(0);
3113 Value *Op0, *Op1;
3114 Instruction *Ext0, *Ext1;
3115 const CmpInst::Predicate Pred = Cmp.getPredicate();
3116 if (match(Add,
3117 m_Add(m_CombineAnd(m_Instruction(Ext0), m_ZExtOrSExt(m_Value(Op0))),
3118 m_CombineAnd(m_Instruction(Ext1),
3119 m_ZExtOrSExt(m_Value(Op1))))) &&
3120 Op0->getType()->isIntOrIntVectorTy(1) &&
3121 Op1->getType()->isIntOrIntVectorTy(1)) {
3122 unsigned BW = C.getBitWidth();
3123 std::bitset<4> Table;
3124 auto ComputeTable = [&](bool Op0Val, bool Op1Val) {
3125 APInt Res(BW, 0);
3126 if (Op0Val)
3127 Res += APInt(BW, isa<ZExtInst>(Ext0) ? 1 : -1, /*isSigned=*/true);
3128 if (Op1Val)
3129 Res += APInt(BW, isa<ZExtInst>(Ext1) ? 1 : -1, /*isSigned=*/true);
3130 return ICmpInst::compare(Res, C, Pred);
3133 Table[0] = ComputeTable(false, false);
3134 Table[1] = ComputeTable(false, true);
3135 Table[2] = ComputeTable(true, false);
3136 Table[3] = ComputeTable(true, true);
3137 if (auto *Cond =
3138 createLogicFromTable(Table, Op0, Op1, Builder, Add->hasOneUse()))
3139 return replaceInstUsesWith(Cmp, Cond);
3141 const APInt *C2;
3142 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
3143 return nullptr;
3145 // Fold icmp pred (add X, C2), C.
3146 Type *Ty = Add->getType();
3148 // If the add does not wrap, we can always adjust the compare by subtracting
3149 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3150 // are canonicalized to SGT/SLT/UGT/ULT.
3151 if ((Add->hasNoSignedWrap() &&
3152 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) ||
3153 (Add->hasNoUnsignedWrap() &&
3154 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) {
3155 bool Overflow;
3156 APInt NewC =
3157 Cmp.isSigned() ? C.ssub_ov(*C2, Overflow) : C.usub_ov(*C2, Overflow);
3158 // If there is overflow, the result must be true or false.
3159 // TODO: Can we assert there is no overflow because InstSimplify always
3160 // handles those cases?
3161 if (!Overflow)
3162 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
3163 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
3166 if (ICmpInst::isUnsigned(Pred) && Add->hasNoSignedWrap() &&
3167 C.isNonNegative() && (C - *C2).isNonNegative() &&
3168 computeConstantRange(X, /*ForSigned=*/true).add(*C2).isAllNonNegative())
3169 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), X,
3170 ConstantInt::get(Ty, C - *C2));
3172 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
3173 const APInt &Upper = CR.getUpper();
3174 const APInt &Lower = CR.getLower();
3175 if (Cmp.isSigned()) {
3176 if (Lower.isSignMask())
3177 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
3178 if (Upper.isSignMask())
3179 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
3180 } else {
3181 if (Lower.isMinValue())
3182 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
3183 if (Upper.isMinValue())
3184 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
3187 // This set of folds is intentionally placed after folds that use no-wrapping
3188 // flags because those folds are likely better for later analysis/codegen.
3189 const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
3190 const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
3192 // Fold compare with offset to opposite sign compare if it eliminates offset:
3193 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3194 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3195 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
3197 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3198 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3199 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
3201 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3202 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3203 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
3205 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3206 if (Pred == CmpInst::ICMP_SLT && C == *C2)
3207 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
3209 // (X + -1) <u C --> X <=u C (if X is never null)
3210 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3211 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3212 if (llvm::isKnownNonZero(X, Q))
3213 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
3216 if (!Add->hasOneUse())
3217 return nullptr;
3219 // X+C <u C2 -> (X & -C2) == C
3220 // iff C & (C2-1) == 0
3221 // C2 is a power of 2
3222 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3223 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
3224 ConstantExpr::getNeg(cast<Constant>(Y)));
3226 // X+C2 <u C -> (X & C) == 2C
3227 // iff C == -(C2)
3228 // C2 is a power of 2
3229 if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)
3230 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, C),
3231 ConstantInt::get(Ty, C * 2));
3233 // X+C >u C2 -> (X & ~C2) != C
3234 // iff C & C2 == 0
3235 // C2+1 is a power of 2
3236 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3237 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
3238 ConstantExpr::getNeg(cast<Constant>(Y)));
3240 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3241 // to the ult form.
3242 // X+C2 >u C -> X+(C2-C-1) <u ~C
3243 if (Pred == ICmpInst::ICMP_UGT)
3244 return new ICmpInst(ICmpInst::ICMP_ULT,
3245 Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
3246 ConstantInt::get(Ty, ~C));
3248 // zext(V) + C2 pred C -> V + C3 pred' C4
3249 Value *V;
3250 if (match(X, m_ZExt(m_Value(V)))) {
3251 Type *NewCmpTy = V->getType();
3252 unsigned NewCmpBW = NewCmpTy->getScalarSizeInBits();
3253 if (shouldChangeType(Ty, NewCmpTy)) {
3254 if (CR.getActiveBits() <= NewCmpBW) {
3255 ConstantRange SrcCR = CR.truncate(NewCmpBW);
3256 CmpInst::Predicate EquivPred;
3257 APInt EquivInt;
3258 APInt EquivOffset;
3260 SrcCR.getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
3261 return new ICmpInst(
3262 EquivPred,
3263 EquivOffset.isZero()
3265 : Builder.CreateAdd(V, ConstantInt::get(NewCmpTy, EquivOffset)),
3266 ConstantInt::get(NewCmpTy, EquivInt));
3271 return nullptr;
3274 bool InstCombinerImpl::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS,
3275 Value *&RHS, ConstantInt *&Less,
3276 ConstantInt *&Equal,
3277 ConstantInt *&Greater) {
3278 // TODO: Generalize this to work with other comparison idioms or ensure
3279 // they get canonicalized into this form.
3281 // select i1 (a == b),
3282 // i32 Equal,
3283 // i32 (select i1 (a < b), i32 Less, i32 Greater)
3284 // where Equal, Less and Greater are placeholders for any three constants.
3285 CmpPredicate PredA;
3286 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
3287 !ICmpInst::isEquality(PredA))
3288 return false;
3289 Value *EqualVal = SI->getTrueValue();
3290 Value *UnequalVal = SI->getFalseValue();
3291 // We still can get non-canonical predicate here, so canonicalize.
3292 if (PredA == ICmpInst::ICMP_NE)
3293 std::swap(EqualVal, UnequalVal);
3294 if (!match(EqualVal, m_ConstantInt(Equal)))
3295 return false;
3296 CmpPredicate PredB;
3297 Value *LHS2, *RHS2;
3298 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
3299 m_ConstantInt(Less), m_ConstantInt(Greater))))
3300 return false;
3301 // We can get predicate mismatch here, so canonicalize if possible:
3302 // First, ensure that 'LHS' match.
3303 if (LHS2 != LHS) {
3304 // x sgt y <--> y slt x
3305 std::swap(LHS2, RHS2);
3306 PredB = ICmpInst::getSwappedPredicate(PredB);
3308 if (LHS2 != LHS)
3309 return false;
3310 // We also need to canonicalize 'RHS'.
3311 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
3312 // x sgt C-1 <--> x sge C <--> not(x slt C)
3313 auto FlippedStrictness =
3314 getFlippedStrictnessPredicateAndConstant(PredB, cast<Constant>(RHS2));
3315 if (!FlippedStrictness)
3316 return false;
3317 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3318 "basic correctness failure");
3319 RHS2 = FlippedStrictness->second;
3320 // And kind-of perform the result swap.
3321 std::swap(Less, Greater);
3322 PredB = ICmpInst::ICMP_SLT;
3324 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3327 Instruction *InstCombinerImpl::foldICmpSelectConstant(ICmpInst &Cmp,
3328 SelectInst *Select,
3329 ConstantInt *C) {
3331 assert(C && "Cmp RHS should be a constant int!");
3332 // If we're testing a constant value against the result of a three way
3333 // comparison, the result can be expressed directly in terms of the
3334 // original values being compared. Note: We could possibly be more
3335 // aggressive here and remove the hasOneUse test. The original select is
3336 // really likely to simplify or sink when we remove a test of the result.
3337 Value *OrigLHS, *OrigRHS;
3338 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3339 if (Cmp.hasOneUse() &&
3340 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
3341 C3GreaterThan)) {
3342 assert(C1LessThan && C2Equal && C3GreaterThan);
3344 bool TrueWhenLessThan = ICmpInst::compare(
3345 C1LessThan->getValue(), C->getValue(), Cmp.getPredicate());
3346 bool TrueWhenEqual = ICmpInst::compare(C2Equal->getValue(), C->getValue(),
3347 Cmp.getPredicate());
3348 bool TrueWhenGreaterThan = ICmpInst::compare(
3349 C3GreaterThan->getValue(), C->getValue(), Cmp.getPredicate());
3351 // This generates the new instruction that will replace the original Cmp
3352 // Instruction. Instead of enumerating the various combinations when
3353 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3354 // false, we rely on chaining of ORs and future passes of InstCombine to
3355 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3357 // When none of the three constants satisfy the predicate for the RHS (C),
3358 // the entire original Cmp can be simplified to a false.
3359 Value *Cond = Builder.getFalse();
3360 if (TrueWhenLessThan)
3361 Cond = Builder.CreateOr(
3362 Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT, OrigLHS, OrigRHS));
3363 if (TrueWhenEqual)
3364 Cond = Builder.CreateOr(
3365 Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ, OrigLHS, OrigRHS));
3366 if (TrueWhenGreaterThan)
3367 Cond = Builder.CreateOr(
3368 Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT, OrigLHS, OrigRHS));
3370 return replaceInstUsesWith(Cmp, Cond);
3372 return nullptr;
3375 Instruction *InstCombinerImpl::foldICmpBitCast(ICmpInst &Cmp) {
3376 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3377 if (!Bitcast)
3378 return nullptr;
3380 ICmpInst::Predicate Pred = Cmp.getPredicate();
3381 Value *Op1 = Cmp.getOperand(1);
3382 Value *BCSrcOp = Bitcast->getOperand(0);
3383 Type *SrcType = Bitcast->getSrcTy();
3384 Type *DstType = Bitcast->getType();
3386 // Make sure the bitcast doesn't change between scalar and vector and
3387 // doesn't change the number of vector elements.
3388 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3389 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3390 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3391 Value *X;
3392 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
3393 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3394 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3395 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3396 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3397 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3398 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3399 match(Op1, m_Zero()))
3400 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3402 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3403 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
3404 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
3406 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3407 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
3408 return new ICmpInst(Pred, X,
3409 ConstantInt::getAllOnesValue(X->getType()));
3412 // Zero-equality checks are preserved through unsigned floating-point casts:
3413 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3414 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3415 if (match(BCSrcOp, m_UIToFP(m_Value(X))))
3416 if (Cmp.isEquality() && match(Op1, m_Zero()))
3417 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3419 const APInt *C;
3420 bool TrueIfSigned;
3421 if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse()) {
3422 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3423 // the FP extend/truncate because that cast does not change the sign-bit.
3424 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3425 // The sign-bit is always the most significant bit in those types.
3426 if (isSignBitCheck(Pred, *C, TrueIfSigned) &&
3427 (match(BCSrcOp, m_FPExt(m_Value(X))) ||
3428 match(BCSrcOp, m_FPTrunc(m_Value(X))))) {
3429 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3430 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3431 Type *XType = X->getType();
3433 // We can't currently handle Power style floating point operations here.
3434 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3435 Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
3436 if (auto *XVTy = dyn_cast<VectorType>(XType))
3437 NewType = VectorType::get(NewType, XVTy->getElementCount());
3438 Value *NewBitcast = Builder.CreateBitCast(X, NewType);
3439 if (TrueIfSigned)
3440 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3441 ConstantInt::getNullValue(NewType));
3442 else
3443 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3444 ConstantInt::getAllOnesValue(NewType));
3448 // icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)
3449 Type *FPType = SrcType->getScalarType();
3450 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3451 Attribute::NoImplicitFloat) &&
3452 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3453 FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();
3454 if (Mask & (fcInf | fcZero)) {
3455 if (Pred == ICmpInst::ICMP_NE)
3456 Mask = ~Mask;
3457 return replaceInstUsesWith(Cmp,
3458 Builder.createIsFPClass(BCSrcOp, Mask));
3464 const APInt *C;
3465 if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3466 !SrcType->isIntOrIntVectorTy())
3467 return nullptr;
3469 // If this is checking if all elements of a vector compare are set or not,
3470 // invert the casted vector equality compare and test if all compare
3471 // elements are clear or not. Compare against zero is generally easier for
3472 // analysis and codegen.
3473 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3474 // Example: are all elements equal? --> are zero elements not equal?
3475 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3476 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3477 if (Value *NotBCSrcOp =
3478 getFreelyInverted(BCSrcOp, BCSrcOp->hasOneUse(), &Builder)) {
3479 Value *Cast = Builder.CreateBitCast(NotBCSrcOp, DstType);
3480 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3484 // If this is checking if all elements of an extended vector are clear or not,
3485 // compare in a narrow type to eliminate the extend:
3486 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3487 Value *X;
3488 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3489 match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3490 if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3491 Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3492 Value *NewCast = Builder.CreateBitCast(X, NewType);
3493 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3497 // Folding: icmp <pred> iN X, C
3498 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3499 // and C is a splat of a K-bit pattern
3500 // and SC is a constant vector = <C', C', C', ..., C'>
3501 // Into:
3502 // %E = extractelement <M x iK> %vec, i32 C'
3503 // icmp <pred> iK %E, trunc(C)
3504 Value *Vec;
3505 ArrayRef<int> Mask;
3506 if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3507 // Check whether every element of Mask is the same constant
3508 if (all_equal(Mask)) {
3509 auto *VecTy = cast<VectorType>(SrcType);
3510 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3511 if (C->isSplat(EltTy->getBitWidth())) {
3512 // Fold the icmp based on the value of C
3513 // If C is M copies of an iK sized bit pattern,
3514 // then:
3515 // => %E = extractelement <N x iK> %vec, i32 Elem
3516 // icmp <pred> iK %SplatVal, <pattern>
3517 Value *Elem = Builder.getInt32(Mask[0]);
3518 Value *Extract = Builder.CreateExtractElement(Vec, Elem);
3519 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3520 return new ICmpInst(Pred, Extract, NewC);
3524 return nullptr;
3527 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3528 /// where X is some kind of instruction.
3529 Instruction *InstCombinerImpl::foldICmpInstWithConstant(ICmpInst &Cmp) {
3530 const APInt *C;
3532 if (match(Cmp.getOperand(1), m_APInt(C))) {
3533 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3534 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3535 return I;
3537 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3538 // For now, we only support constant integers while folding the
3539 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3540 // similar to the cases handled by binary ops above.
3541 if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3542 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3543 return I;
3545 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3546 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3547 return I;
3549 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3550 if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, II, *C))
3551 return I;
3553 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3554 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3555 // TODO: This checks one-use, but that is not strictly necessary.
3556 Value *Cmp0 = Cmp.getOperand(0);
3557 Value *X, *Y;
3558 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3559 (match(Cmp0,
3560 m_ExtractValue<0>(m_Intrinsic<Intrinsic::ssub_with_overflow>(
3561 m_Value(X), m_Value(Y)))) ||
3562 match(Cmp0,
3563 m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
3564 m_Value(X), m_Value(Y))))))
3565 return new ICmpInst(Cmp.getPredicate(), X, Y);
3568 if (match(Cmp.getOperand(1), m_APIntAllowPoison(C)))
3569 return foldICmpInstWithConstantAllowPoison(Cmp, *C);
3571 return nullptr;
3574 /// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3575 /// icmp eq/ne BO, C.
3576 Instruction *InstCombinerImpl::foldICmpBinOpEqualityWithConstant(
3577 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3578 // TODO: Some of these folds could work with arbitrary constants, but this
3579 // function is limited to scalar and vector splat constants.
3580 if (!Cmp.isEquality())
3581 return nullptr;
3583 ICmpInst::Predicate Pred = Cmp.getPredicate();
3584 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3585 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3586 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3588 switch (BO->getOpcode()) {
3589 case Instruction::SRem:
3590 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3591 if (C.isZero() && BO->hasOneUse()) {
3592 const APInt *BOC;
3593 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3594 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3595 return new ICmpInst(Pred, NewRem,
3596 Constant::getNullValue(BO->getType()));
3599 break;
3600 case Instruction::Add: {
3601 // (A + C2) == C --> A == (C - C2)
3602 // (A + C2) != C --> A != (C - C2)
3603 // TODO: Remove the one-use limitation? See discussion in D58633.
3604 if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
3605 if (BO->hasOneUse())
3606 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
3607 } else if (C.isZero()) {
3608 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3609 // efficiently invertible, or if the add has just this one use.
3610 if (Value *NegVal = dyn_castNegVal(BOp1))
3611 return new ICmpInst(Pred, BOp0, NegVal);
3612 if (Value *NegVal = dyn_castNegVal(BOp0))
3613 return new ICmpInst(Pred, NegVal, BOp1);
3614 if (BO->hasOneUse()) {
3615 // (add nuw A, B) != 0 -> (or A, B) != 0
3616 if (match(BO, m_NUWAdd(m_Value(), m_Value()))) {
3617 Value *Or = Builder.CreateOr(BOp0, BOp1);
3618 return new ICmpInst(Pred, Or, Constant::getNullValue(BO->getType()));
3620 Value *Neg = Builder.CreateNeg(BOp1);
3621 Neg->takeName(BO);
3622 return new ICmpInst(Pred, BOp0, Neg);
3625 break;
3627 case Instruction::Xor:
3628 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3629 // For the xor case, we can xor two constants together, eliminating
3630 // the explicit xor.
3631 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3632 } else if (C.isZero()) {
3633 // Replace ((xor A, B) != 0) with (A != B)
3634 return new ICmpInst(Pred, BOp0, BOp1);
3636 break;
3637 case Instruction::Or: {
3638 const APInt *BOC;
3639 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3640 // Comparing if all bits outside of a constant mask are set?
3641 // Replace (X | C) == -1 with (X & ~C) == ~C.
3642 // This removes the -1 constant.
3643 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
3644 Value *And = Builder.CreateAnd(BOp0, NotBOC);
3645 return new ICmpInst(Pred, And, NotBOC);
3647 // (icmp eq (or (select cond, 0, NonZero), Other), 0)
3648 // -> (and cond, (icmp eq Other, 0))
3649 // (icmp ne (or (select cond, NonZero, 0), Other), 0)
3650 // -> (or cond, (icmp ne Other, 0))
3651 Value *Cond, *TV, *FV, *Other, *Sel;
3652 if (C.isZero() &&
3653 match(BO,
3654 m_OneUse(m_c_Or(m_CombineAnd(m_Value(Sel),
3655 m_Select(m_Value(Cond), m_Value(TV),
3656 m_Value(FV))),
3657 m_Value(Other)))) &&
3658 Cond->getType() == Cmp.getType()) {
3659 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3660 // Easy case is if eq/ne matches whether 0 is trueval/falseval.
3661 if (Pred == ICmpInst::ICMP_EQ
3662 ? (match(TV, m_Zero()) && isKnownNonZero(FV, Q))
3663 : (match(FV, m_Zero()) && isKnownNonZero(TV, Q))) {
3664 Value *Cmp = Builder.CreateICmp(
3665 Pred, Other, Constant::getNullValue(Other->getType()));
3666 return BinaryOperator::Create(
3667 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3668 Cond);
3670 // Harder case is if eq/ne matches whether 0 is falseval/trueval. In this
3671 // case we need to invert the select condition so we need to be careful to
3672 // avoid creating extra instructions.
3673 // (icmp ne (or (select cond, 0, NonZero), Other), 0)
3674 // -> (or (not cond), (icmp ne Other, 0))
3675 // (icmp eq (or (select cond, NonZero, 0), Other), 0)
3676 // -> (and (not cond), (icmp eq Other, 0))
3678 // Only do this if the inner select has one use, in which case we are
3679 // replacing `select` with `(not cond)`. Otherwise, we will create more
3680 // uses. NB: Trying to freely invert cond doesn't make sense here, as if
3681 // cond was freely invertable, the select arms would have been inverted.
3682 if (Sel->hasOneUse() &&
3683 (Pred == ICmpInst::ICMP_EQ
3684 ? (match(FV, m_Zero()) && isKnownNonZero(TV, Q))
3685 : (match(TV, m_Zero()) && isKnownNonZero(FV, Q)))) {
3686 Value *NotCond = Builder.CreateNot(Cond);
3687 Value *Cmp = Builder.CreateICmp(
3688 Pred, Other, Constant::getNullValue(Other->getType()));
3689 return BinaryOperator::Create(
3690 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3691 NotCond);
3694 break;
3696 case Instruction::UDiv:
3697 case Instruction::SDiv:
3698 if (BO->isExact()) {
3699 // div exact X, Y eq/ne 0 -> X eq/ne 0
3700 // div exact X, Y eq/ne 1 -> X eq/ne Y
3701 // div exact X, Y eq/ne C ->
3702 // if Y * C never-overflow && OneUse:
3703 // -> Y * C eq/ne X
3704 if (C.isZero())
3705 return new ICmpInst(Pred, BOp0, Constant::getNullValue(BO->getType()));
3706 else if (C.isOne())
3707 return new ICmpInst(Pred, BOp0, BOp1);
3708 else if (BO->hasOneUse()) {
3709 OverflowResult OR = computeOverflow(
3710 Instruction::Mul, BO->getOpcode() == Instruction::SDiv, BOp1,
3711 Cmp.getOperand(1), BO);
3712 if (OR == OverflowResult::NeverOverflows) {
3713 Value *YC =
3714 Builder.CreateMul(BOp1, ConstantInt::get(BO->getType(), C));
3715 return new ICmpInst(Pred, YC, BOp0);
3719 if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3720 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3721 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3722 return new ICmpInst(NewPred, BOp1, BOp0);
3724 break;
3725 default:
3726 break;
3728 return nullptr;
3731 static Instruction *foldCtpopPow2Test(ICmpInst &I, IntrinsicInst *CtpopLhs,
3732 const APInt &CRhs,
3733 InstCombiner::BuilderTy &Builder,
3734 const SimplifyQuery &Q) {
3735 assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3736 "Non-ctpop intrin in ctpop fold");
3737 if (!CtpopLhs->hasOneUse())
3738 return nullptr;
3740 // Power of 2 test:
3741 // isPow2OrZero : ctpop(X) u< 2
3742 // isPow2 : ctpop(X) == 1
3743 // NotPow2OrZero: ctpop(X) u> 1
3744 // NotPow2 : ctpop(X) != 1
3745 // If we know any bit of X can be folded to:
3746 // IsPow2 : X & (~Bit) == 0
3747 // NotPow2 : X & (~Bit) != 0
3748 const ICmpInst::Predicate Pred = I.getPredicate();
3749 if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3750 (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3751 Value *Op = CtpopLhs->getArgOperand(0);
3752 KnownBits OpKnown = computeKnownBits(Op, Q.DL,
3753 /*Depth*/ 0, Q.AC, Q.CxtI, Q.DT);
3754 // No need to check for count > 1, that should be already constant folded.
3755 if (OpKnown.countMinPopulation() == 1) {
3756 Value *And = Builder.CreateAnd(
3757 Op, Constant::getIntegerValue(Op->getType(), ~(OpKnown.One)));
3758 return new ICmpInst(
3759 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3760 ? ICmpInst::ICMP_EQ
3761 : ICmpInst::ICMP_NE,
3762 And, Constant::getNullValue(Op->getType()));
3766 return nullptr;
3769 /// Fold an equality icmp with LLVM intrinsic and constant operand.
3770 Instruction *InstCombinerImpl::foldICmpEqIntrinsicWithConstant(
3771 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3772 Type *Ty = II->getType();
3773 unsigned BitWidth = C.getBitWidth();
3774 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3776 switch (II->getIntrinsicID()) {
3777 case Intrinsic::abs:
3778 // abs(A) == 0 -> A == 0
3779 // abs(A) == INT_MIN -> A == INT_MIN
3780 if (C.isZero() || C.isMinSignedValue())
3781 return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3782 break;
3784 case Intrinsic::bswap:
3785 // bswap(A) == C -> A == bswap(C)
3786 return new ICmpInst(Pred, II->getArgOperand(0),
3787 ConstantInt::get(Ty, C.byteSwap()));
3789 case Intrinsic::bitreverse:
3790 // bitreverse(A) == C -> A == bitreverse(C)
3791 return new ICmpInst(Pred, II->getArgOperand(0),
3792 ConstantInt::get(Ty, C.reverseBits()));
3794 case Intrinsic::ctlz:
3795 case Intrinsic::cttz: {
3796 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3797 if (C == BitWidth)
3798 return new ICmpInst(Pred, II->getArgOperand(0),
3799 ConstantInt::getNullValue(Ty));
3801 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3802 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3803 // Limit to one use to ensure we don't increase instruction count.
3804 unsigned Num = C.getLimitedValue(BitWidth);
3805 if (Num != BitWidth && II->hasOneUse()) {
3806 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3807 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3808 : APInt::getHighBitsSet(BitWidth, Num + 1);
3809 APInt Mask2 = IsTrailing
3810 ? APInt::getOneBitSet(BitWidth, Num)
3811 : APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
3812 return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
3813 ConstantInt::get(Ty, Mask2));
3815 break;
3818 case Intrinsic::ctpop: {
3819 // popcount(A) == 0 -> A == 0 and likewise for !=
3820 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3821 bool IsZero = C.isZero();
3822 if (IsZero || C == BitWidth)
3823 return new ICmpInst(Pred, II->getArgOperand(0),
3824 IsZero ? Constant::getNullValue(Ty)
3825 : Constant::getAllOnesValue(Ty));
3827 break;
3830 case Intrinsic::fshl:
3831 case Intrinsic::fshr:
3832 if (II->getArgOperand(0) == II->getArgOperand(1)) {
3833 const APInt *RotAmtC;
3834 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3835 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3836 if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
3837 return new ICmpInst(Pred, II->getArgOperand(0),
3838 II->getIntrinsicID() == Intrinsic::fshl
3839 ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
3840 : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
3842 break;
3844 case Intrinsic::umax:
3845 case Intrinsic::uadd_sat: {
3846 // uadd.sat(a, b) == 0 -> (a | b) == 0
3847 // umax(a, b) == 0 -> (a | b) == 0
3848 if (C.isZero() && II->hasOneUse()) {
3849 Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));
3850 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
3852 break;
3855 case Intrinsic::ssub_sat:
3856 // ssub.sat(a, b) == 0 -> a == b
3857 if (C.isZero())
3858 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
3859 break;
3860 case Intrinsic::usub_sat: {
3861 // usub.sat(a, b) == 0 -> a <= b
3862 if (C.isZero()) {
3863 ICmpInst::Predicate NewPred =
3864 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3865 return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
3867 break;
3869 default:
3870 break;
3873 return nullptr;
3876 /// Fold an icmp with LLVM intrinsics
3877 static Instruction *
3878 foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp,
3879 InstCombiner::BuilderTy &Builder) {
3880 assert(Cmp.isEquality());
3882 ICmpInst::Predicate Pred = Cmp.getPredicate();
3883 Value *Op0 = Cmp.getOperand(0);
3884 Value *Op1 = Cmp.getOperand(1);
3885 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
3886 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
3887 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
3888 return nullptr;
3890 switch (IIOp0->getIntrinsicID()) {
3891 case Intrinsic::bswap:
3892 case Intrinsic::bitreverse:
3893 // If both operands are byte-swapped or bit-reversed, just compare the
3894 // original values.
3895 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3896 case Intrinsic::fshl:
3897 case Intrinsic::fshr: {
3898 // If both operands are rotated by same amount, just compare the
3899 // original values.
3900 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
3901 break;
3902 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
3903 break;
3904 if (IIOp0->getOperand(2) == IIOp1->getOperand(2))
3905 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3907 // rotate(X, AmtX) == rotate(Y, AmtY)
3908 // -> rotate(X, AmtX - AmtY) == Y
3909 // Do this if either both rotates have one use or if only one has one use
3910 // and AmtX/AmtY are constants.
3911 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
3912 if (OneUses == 2 ||
3913 (OneUses == 1 && match(IIOp0->getOperand(2), m_ImmConstant()) &&
3914 match(IIOp1->getOperand(2), m_ImmConstant()))) {
3915 Value *SubAmt =
3916 Builder.CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));
3917 Value *CombinedRotate = Builder.CreateIntrinsic(
3918 Op0->getType(), IIOp0->getIntrinsicID(),
3919 {IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});
3920 return new ICmpInst(Pred, IIOp1->getOperand(0), CombinedRotate);
3922 } break;
3923 default:
3924 break;
3927 return nullptr;
3930 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3931 /// where X is some kind of instruction and C is AllowPoison.
3932 /// TODO: Move more folds which allow poison to this function.
3933 Instruction *
3934 InstCombinerImpl::foldICmpInstWithConstantAllowPoison(ICmpInst &Cmp,
3935 const APInt &C) {
3936 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3937 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
3938 switch (II->getIntrinsicID()) {
3939 default:
3940 break;
3941 case Intrinsic::fshl:
3942 case Intrinsic::fshr:
3943 if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
3944 // (rot X, ?) == 0/-1 --> X == 0/-1
3945 if (C.isZero() || C.isAllOnes())
3946 return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
3948 break;
3952 return nullptr;
3955 /// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
3956 Instruction *InstCombinerImpl::foldICmpBinOpWithConstant(ICmpInst &Cmp,
3957 BinaryOperator *BO,
3958 const APInt &C) {
3959 switch (BO->getOpcode()) {
3960 case Instruction::Xor:
3961 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
3962 return I;
3963 break;
3964 case Instruction::And:
3965 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
3966 return I;
3967 break;
3968 case Instruction::Or:
3969 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
3970 return I;
3971 break;
3972 case Instruction::Mul:
3973 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
3974 return I;
3975 break;
3976 case Instruction::Shl:
3977 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
3978 return I;
3979 break;
3980 case Instruction::LShr:
3981 case Instruction::AShr:
3982 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
3983 return I;
3984 break;
3985 case Instruction::SRem:
3986 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
3987 return I;
3988 break;
3989 case Instruction::UDiv:
3990 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
3991 return I;
3992 [[fallthrough]];
3993 case Instruction::SDiv:
3994 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
3995 return I;
3996 break;
3997 case Instruction::Sub:
3998 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
3999 return I;
4000 break;
4001 case Instruction::Add:
4002 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
4003 return I;
4004 break;
4005 default:
4006 break;
4009 // TODO: These folds could be refactored to be part of the above calls.
4010 return foldICmpBinOpEqualityWithConstant(Cmp, BO, C);
4013 static Instruction *
4014 foldICmpUSubSatOrUAddSatWithConstant(CmpPredicate Pred, SaturatingInst *II,
4015 const APInt &C,
4016 InstCombiner::BuilderTy &Builder) {
4017 // This transform may end up producing more than one instruction for the
4018 // intrinsic, so limit it to one user of the intrinsic.
4019 if (!II->hasOneUse())
4020 return nullptr;
4022 // Let Y = [add/sub]_sat(X, C) pred C2
4023 // SatVal = The saturating value for the operation
4024 // WillWrap = Whether or not the operation will underflow / overflow
4025 // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
4026 // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
4028 // When (SatVal pred C2) is true, then
4029 // Y = WillWrap ? true : ((X binop C) pred C2)
4030 // => Y = WillWrap || ((X binop C) pred C2)
4031 // else
4032 // Y = WillWrap ? false : ((X binop C) pred C2)
4033 // => Y = !WillWrap ? ((X binop C) pred C2) : false
4034 // => Y = !WillWrap && ((X binop C) pred C2)
4035 Value *Op0 = II->getOperand(0);
4036 Value *Op1 = II->getOperand(1);
4038 const APInt *COp1;
4039 // This transform only works when the intrinsic has an integral constant or
4040 // splat vector as the second operand.
4041 if (!match(Op1, m_APInt(COp1)))
4042 return nullptr;
4044 APInt SatVal;
4045 switch (II->getIntrinsicID()) {
4046 default:
4047 llvm_unreachable(
4048 "This function only works with usub_sat and uadd_sat for now!");
4049 case Intrinsic::uadd_sat:
4050 SatVal = APInt::getAllOnes(C.getBitWidth());
4051 break;
4052 case Intrinsic::usub_sat:
4053 SatVal = APInt::getZero(C.getBitWidth());
4054 break;
4057 // Check (SatVal pred C2)
4058 bool SatValCheck = ICmpInst::compare(SatVal, C, Pred);
4060 // !WillWrap.
4061 ConstantRange C1 = ConstantRange::makeExactNoWrapRegion(
4062 II->getBinaryOp(), *COp1, II->getNoWrapKind());
4064 // WillWrap.
4065 if (SatValCheck)
4066 C1 = C1.inverse();
4068 ConstantRange C2 = ConstantRange::makeExactICmpRegion(Pred, C);
4069 if (II->getBinaryOp() == Instruction::Add)
4070 C2 = C2.sub(*COp1);
4071 else
4072 C2 = C2.add(*COp1);
4074 Instruction::BinaryOps CombiningOp =
4075 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4077 std::optional<ConstantRange> Combination;
4078 if (CombiningOp == Instruction::BinaryOps::Or)
4079 Combination = C1.exactUnionWith(C2);
4080 else /* CombiningOp == Instruction::BinaryOps::And */
4081 Combination = C1.exactIntersectWith(C2);
4083 if (!Combination)
4084 return nullptr;
4086 CmpInst::Predicate EquivPred;
4087 APInt EquivInt;
4088 APInt EquivOffset;
4090 Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
4092 return new ICmpInst(
4093 EquivPred,
4094 Builder.CreateAdd(Op0, ConstantInt::get(Op1->getType(), EquivOffset)),
4095 ConstantInt::get(Op1->getType(), EquivInt));
4098 static Instruction *
4099 foldICmpOfCmpIntrinsicWithConstant(CmpPredicate Pred, IntrinsicInst *I,
4100 const APInt &C,
4101 InstCombiner::BuilderTy &Builder) {
4102 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4103 switch (Pred) {
4104 case ICmpInst::ICMP_EQ:
4105 case ICmpInst::ICMP_NE:
4106 if (C.isZero())
4107 NewPredicate = Pred;
4108 else if (C.isOne())
4109 NewPredicate =
4110 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
4111 else if (C.isAllOnes())
4112 NewPredicate =
4113 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
4114 break;
4116 case ICmpInst::ICMP_SGT:
4117 if (C.isAllOnes())
4118 NewPredicate = ICmpInst::ICMP_UGE;
4119 else if (C.isZero())
4120 NewPredicate = ICmpInst::ICMP_UGT;
4121 break;
4123 case ICmpInst::ICMP_SLT:
4124 if (C.isZero())
4125 NewPredicate = ICmpInst::ICMP_ULT;
4126 else if (C.isOne())
4127 NewPredicate = ICmpInst::ICMP_ULE;
4128 break;
4130 case ICmpInst::ICMP_ULT:
4131 if (C.ugt(1))
4132 NewPredicate = ICmpInst::ICMP_UGE;
4133 break;
4135 case ICmpInst::ICMP_UGT:
4136 if (!C.isZero() && !C.isAllOnes())
4137 NewPredicate = ICmpInst::ICMP_ULT;
4138 break;
4140 default:
4141 break;
4144 if (!NewPredicate)
4145 return nullptr;
4147 if (I->getIntrinsicID() == Intrinsic::scmp)
4148 NewPredicate = ICmpInst::getSignedPredicate(*NewPredicate);
4149 Value *LHS = I->getOperand(0);
4150 Value *RHS = I->getOperand(1);
4151 return new ICmpInst(*NewPredicate, LHS, RHS);
4154 /// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
4155 Instruction *InstCombinerImpl::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
4156 IntrinsicInst *II,
4157 const APInt &C) {
4158 ICmpInst::Predicate Pred = Cmp.getPredicate();
4160 // Handle folds that apply for any kind of icmp.
4161 switch (II->getIntrinsicID()) {
4162 default:
4163 break;
4164 case Intrinsic::uadd_sat:
4165 case Intrinsic::usub_sat:
4166 if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(
4167 Pred, cast<SaturatingInst>(II), C, Builder))
4168 return Folded;
4169 break;
4170 case Intrinsic::ctpop: {
4171 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
4172 if (Instruction *R = foldCtpopPow2Test(Cmp, II, C, Builder, Q))
4173 return R;
4174 } break;
4175 case Intrinsic::scmp:
4176 case Intrinsic::ucmp:
4177 if (auto *Folded = foldICmpOfCmpIntrinsicWithConstant(Pred, II, C, Builder))
4178 return Folded;
4179 break;
4182 if (Cmp.isEquality())
4183 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
4185 Type *Ty = II->getType();
4186 unsigned BitWidth = C.getBitWidth();
4187 switch (II->getIntrinsicID()) {
4188 case Intrinsic::ctpop: {
4189 // (ctpop X > BitWidth - 1) --> X == -1
4190 Value *X = II->getArgOperand(0);
4191 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
4192 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
4193 ConstantInt::getAllOnesValue(Ty));
4194 // (ctpop X < BitWidth) --> X != -1
4195 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
4196 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
4197 ConstantInt::getAllOnesValue(Ty));
4198 break;
4200 case Intrinsic::ctlz: {
4201 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
4202 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4203 unsigned Num = C.getLimitedValue();
4204 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
4205 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
4206 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4209 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
4210 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4211 unsigned Num = C.getLimitedValue();
4212 APInt Limit = APInt::getLowBitsSet(BitWidth, BitWidth - Num);
4213 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
4214 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4216 break;
4218 case Intrinsic::cttz: {
4219 // Limit to one use to ensure we don't increase instruction count.
4220 if (!II->hasOneUse())
4221 return nullptr;
4223 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
4224 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4225 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
4226 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
4227 Builder.CreateAnd(II->getArgOperand(0), Mask),
4228 ConstantInt::getNullValue(Ty));
4231 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
4232 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4233 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
4234 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
4235 Builder.CreateAnd(II->getArgOperand(0), Mask),
4236 ConstantInt::getNullValue(Ty));
4238 break;
4240 case Intrinsic::ssub_sat:
4241 // ssub.sat(a, b) spred 0 -> a spred b
4242 if (ICmpInst::isSigned(Pred)) {
4243 if (C.isZero())
4244 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4245 // X s<= 0 is cannonicalized to X s< 1
4246 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
4247 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(0),
4248 II->getArgOperand(1));
4249 // X s>= 0 is cannonicalized to X s> -1
4250 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
4251 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(0),
4252 II->getArgOperand(1));
4254 break;
4255 default:
4256 break;
4259 return nullptr;
4262 /// Handle icmp with constant (but not simple integer constant) RHS.
4263 Instruction *InstCombinerImpl::foldICmpInstWithConstantNotInt(ICmpInst &I) {
4264 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4265 Constant *RHSC = dyn_cast<Constant>(Op1);
4266 Instruction *LHSI = dyn_cast<Instruction>(Op0);
4267 if (!RHSC || !LHSI)
4268 return nullptr;
4270 switch (LHSI->getOpcode()) {
4271 case Instruction::PHI:
4272 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
4273 return NV;
4274 break;
4275 case Instruction::IntToPtr:
4276 // icmp pred inttoptr(X), null -> icmp pred X, 0
4277 if (RHSC->isNullValue() &&
4278 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
4279 return new ICmpInst(
4280 I.getPredicate(), LHSI->getOperand(0),
4281 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4282 break;
4284 case Instruction::Load:
4285 // Try to optimize things like "A[i] > 4" to index computations.
4286 if (GetElementPtrInst *GEP =
4287 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
4288 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4289 if (Instruction *Res =
4290 foldCmpLoadFromIndexedGlobal(cast<LoadInst>(LHSI), GEP, GV, I))
4291 return Res;
4292 break;
4295 return nullptr;
4298 Instruction *InstCombinerImpl::foldSelectICmp(CmpPredicate Pred, SelectInst *SI,
4299 Value *RHS, const ICmpInst &I) {
4300 // Try to fold the comparison into the select arms, which will cause the
4301 // select to be converted into a logical and/or.
4302 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
4303 if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
4304 return Res;
4305 if (std::optional<bool> Impl = isImpliedCondition(
4306 SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
4307 return ConstantInt::get(I.getType(), *Impl);
4308 return nullptr;
4311 ConstantInt *CI = nullptr;
4312 Value *Op1 = SimplifyOp(SI->getOperand(1), true);
4313 if (Op1)
4314 CI = dyn_cast<ConstantInt>(Op1);
4316 Value *Op2 = SimplifyOp(SI->getOperand(2), false);
4317 if (Op2)
4318 CI = dyn_cast<ConstantInt>(Op2);
4320 auto Simplifies = [&](Value *Op, unsigned Idx) {
4321 // A comparison of ucmp/scmp with a constant will fold into an icmp.
4322 const APInt *Dummy;
4323 return Op ||
4324 (isa<CmpIntrinsic>(SI->getOperand(Idx)) &&
4325 SI->getOperand(Idx)->hasOneUse() && match(RHS, m_APInt(Dummy)));
4328 // We only want to perform this transformation if it will not lead to
4329 // additional code. This is true if either both sides of the select
4330 // fold to a constant (in which case the icmp is replaced with a select
4331 // which will usually simplify) or this is the only user of the
4332 // select (in which case we are trading a select+icmp for a simpler
4333 // select+icmp) or all uses of the select can be replaced based on
4334 // dominance information ("Global cases").
4335 bool Transform = false;
4336 if (Op1 && Op2)
4337 Transform = true;
4338 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4339 // Local case
4340 if (SI->hasOneUse())
4341 Transform = true;
4342 // Global cases
4343 else if (CI && !CI->isZero())
4344 // When Op1 is constant try replacing select with second operand.
4345 // Otherwise Op2 is constant and try replacing select with first
4346 // operand.
4347 Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
4349 if (Transform) {
4350 if (!Op1)
4351 Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
4352 if (!Op2)
4353 Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
4354 return SelectInst::Create(SI->getOperand(0), Op1, Op2);
4357 return nullptr;
4360 // Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)
4361 static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,
4362 unsigned Depth = 0) {
4363 if (Not ? match(V, m_NegatedPower2OrZero()) : match(V, m_LowBitMaskOrZero()))
4364 return true;
4365 if (V->getType()->getScalarSizeInBits() == 1)
4366 return true;
4367 if (Depth++ >= MaxAnalysisRecursionDepth)
4368 return false;
4369 Value *X;
4370 const Instruction *I = dyn_cast<Instruction>(V);
4371 if (!I)
4372 return false;
4373 switch (I->getOpcode()) {
4374 case Instruction::ZExt:
4375 // ZExt(Mask) is a Mask.
4376 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4377 case Instruction::SExt:
4378 // SExt(Mask) is a Mask.
4379 // SExt(~Mask) is a ~Mask.
4380 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4381 case Instruction::And:
4382 case Instruction::Or:
4383 // Mask0 | Mask1 is a Mask.
4384 // Mask0 & Mask1 is a Mask.
4385 // ~Mask0 | ~Mask1 is a ~Mask.
4386 // ~Mask0 & ~Mask1 is a ~Mask.
4387 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4388 isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4389 case Instruction::Xor:
4390 if (match(V, m_Not(m_Value(X))))
4391 return isMaskOrZero(X, !Not, Q, Depth);
4393 // (X ^ -X) is a ~Mask
4394 if (Not)
4395 return match(V, m_c_Xor(m_Value(X), m_Neg(m_Deferred(X))));
4396 // (X ^ (X - 1)) is a Mask
4397 else
4398 return match(V, m_c_Xor(m_Value(X), m_Add(m_Deferred(X), m_AllOnes())));
4399 case Instruction::Select:
4400 // c ? Mask0 : Mask1 is a Mask.
4401 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4402 isMaskOrZero(I->getOperand(2), Not, Q, Depth);
4403 case Instruction::Shl:
4404 // (~Mask) << X is a ~Mask.
4405 return Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4406 case Instruction::LShr:
4407 // Mask >> X is a Mask.
4408 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4409 case Instruction::AShr:
4410 // Mask s>> X is a Mask.
4411 // ~Mask s>> X is a ~Mask.
4412 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4413 case Instruction::Add:
4414 // Pow2 - 1 is a Mask.
4415 if (!Not && match(I->getOperand(1), m_AllOnes()))
4416 return isKnownToBeAPowerOfTwo(I->getOperand(0), Q.DL, /*OrZero*/ true,
4417 Depth, Q.AC, Q.CxtI, Q.DT);
4418 break;
4419 case Instruction::Sub:
4420 // -Pow2 is a ~Mask.
4421 if (Not && match(I->getOperand(0), m_Zero()))
4422 return isKnownToBeAPowerOfTwo(I->getOperand(1), Q.DL, /*OrZero*/ true,
4423 Depth, Q.AC, Q.CxtI, Q.DT);
4424 break;
4425 case Instruction::Call: {
4426 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
4427 switch (II->getIntrinsicID()) {
4428 // min/max(Mask0, Mask1) is a Mask.
4429 // min/max(~Mask0, ~Mask1) is a ~Mask.
4430 case Intrinsic::umax:
4431 case Intrinsic::smax:
4432 case Intrinsic::umin:
4433 case Intrinsic::smin:
4434 return isMaskOrZero(II->getArgOperand(1), Not, Q, Depth) &&
4435 isMaskOrZero(II->getArgOperand(0), Not, Q, Depth);
4437 // In the context of masks, bitreverse(Mask) == ~Mask
4438 case Intrinsic::bitreverse:
4439 return isMaskOrZero(II->getArgOperand(0), !Not, Q, Depth);
4440 default:
4441 break;
4444 break;
4446 default:
4447 break;
4449 return false;
4452 /// Some comparisons can be simplified.
4453 /// In this case, we are looking for comparisons that look like
4454 /// a check for a lossy truncation.
4455 /// Folds:
4456 /// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
4457 /// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask
4458 /// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask
4459 /// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask
4460 /// Where Mask is some pattern that produces all-ones in low bits:
4461 /// (-1 >> y)
4462 /// ((-1 << y) >> y) <- non-canonical, has extra uses
4463 /// ~(-1 << y)
4464 /// ((1 << y) + (-1)) <- non-canonical, has extra uses
4465 /// The Mask can be a constant, too.
4466 /// For some predicates, the operands are commutative.
4467 /// For others, x can only be on a specific side.
4468 static Value *foldICmpWithLowBitMaskedVal(CmpPredicate Pred, Value *Op0,
4469 Value *Op1, const SimplifyQuery &Q,
4470 InstCombiner &IC) {
4472 ICmpInst::Predicate DstPred;
4473 switch (Pred) {
4474 case ICmpInst::Predicate::ICMP_EQ:
4475 // x & Mask == x
4476 // x & ~Mask == 0
4477 // ~x | Mask == -1
4478 // -> x u<= Mask
4479 // x & ~Mask == ~Mask
4480 // -> ~Mask u<= x
4481 DstPred = ICmpInst::Predicate::ICMP_ULE;
4482 break;
4483 case ICmpInst::Predicate::ICMP_NE:
4484 // x & Mask != x
4485 // x & ~Mask != 0
4486 // ~x | Mask != -1
4487 // -> x u> Mask
4488 // x & ~Mask != ~Mask
4489 // -> ~Mask u> x
4490 DstPred = ICmpInst::Predicate::ICMP_UGT;
4491 break;
4492 case ICmpInst::Predicate::ICMP_ULT:
4493 // x & Mask u< x
4494 // -> x u> Mask
4495 // x & ~Mask u< ~Mask
4496 // -> ~Mask u> x
4497 DstPred = ICmpInst::Predicate::ICMP_UGT;
4498 break;
4499 case ICmpInst::Predicate::ICMP_UGE:
4500 // x & Mask u>= x
4501 // -> x u<= Mask
4502 // x & ~Mask u>= ~Mask
4503 // -> ~Mask u<= x
4504 DstPred = ICmpInst::Predicate::ICMP_ULE;
4505 break;
4506 case ICmpInst::Predicate::ICMP_SLT:
4507 // x & Mask s< x [iff Mask s>= 0]
4508 // -> x s> Mask
4509 // x & ~Mask s< ~Mask [iff ~Mask != 0]
4510 // -> ~Mask s> x
4511 DstPred = ICmpInst::Predicate::ICMP_SGT;
4512 break;
4513 case ICmpInst::Predicate::ICMP_SGE:
4514 // x & Mask s>= x [iff Mask s>= 0]
4515 // -> x s<= Mask
4516 // x & ~Mask s>= ~Mask [iff ~Mask != 0]
4517 // -> ~Mask s<= x
4518 DstPred = ICmpInst::Predicate::ICMP_SLE;
4519 break;
4520 default:
4521 // We don't support sgt,sle
4522 // ult/ugt are simplified to true/false respectively.
4523 return nullptr;
4526 Value *X, *M;
4527 // Put search code in lambda for early positive returns.
4528 auto IsLowBitMask = [&]() {
4529 if (match(Op0, m_c_And(m_Specific(Op1), m_Value(M)))) {
4530 X = Op1;
4531 // Look for: x & Mask pred x
4532 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4533 return !ICmpInst::isSigned(Pred) ||
4534 (match(M, m_NonNegative()) || isKnownNonNegative(M, Q));
4537 // Look for: x & ~Mask pred ~Mask
4538 if (isMaskOrZero(X, /*Not=*/true, Q)) {
4539 return !ICmpInst::isSigned(Pred) || isKnownNonZero(X, Q);
4541 return false;
4543 if (ICmpInst::isEquality(Pred) && match(Op1, m_AllOnes()) &&
4544 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(M))))) {
4546 auto Check = [&]() {
4547 // Look for: ~x | Mask == -1
4548 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4549 if (Value *NotX =
4550 IC.getFreelyInverted(X, X->hasOneUse(), &IC.Builder)) {
4551 X = NotX;
4552 return true;
4555 return false;
4557 if (Check())
4558 return true;
4559 std::swap(X, M);
4560 return Check();
4562 if (ICmpInst::isEquality(Pred) && match(Op1, m_Zero()) &&
4563 match(Op0, m_OneUse(m_And(m_Value(X), m_Value(M))))) {
4564 auto Check = [&]() {
4565 // Look for: x & ~Mask == 0
4566 if (isMaskOrZero(M, /*Not=*/true, Q)) {
4567 if (Value *NotM =
4568 IC.getFreelyInverted(M, M->hasOneUse(), &IC.Builder)) {
4569 M = NotM;
4570 return true;
4573 return false;
4575 if (Check())
4576 return true;
4577 std::swap(X, M);
4578 return Check();
4580 return false;
4583 if (!IsLowBitMask())
4584 return nullptr;
4586 return IC.Builder.CreateICmp(DstPred, X, M);
4589 /// Some comparisons can be simplified.
4590 /// In this case, we are looking for comparisons that look like
4591 /// a check for a lossy signed truncation.
4592 /// Folds: (MaskedBits is a constant.)
4593 /// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4594 /// Into:
4595 /// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4596 /// Where KeptBits = bitwidth(%x) - MaskedBits
4597 static Value *
4598 foldICmpWithTruncSignExtendedVal(ICmpInst &I,
4599 InstCombiner::BuilderTy &Builder) {
4600 CmpPredicate SrcPred;
4601 Value *X;
4602 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4603 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4604 if (!match(&I, m_c_ICmp(SrcPred,
4605 m_OneUse(m_AShr(m_Shl(m_Value(X), m_APInt(C0)),
4606 m_APInt(C1))),
4607 m_Deferred(X))))
4608 return nullptr;
4610 // Potential handling of non-splats: for each element:
4611 // * if both are undef, replace with constant 0.
4612 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4613 // * if both are not undef, and are different, bailout.
4614 // * else, only one is undef, then pick the non-undef one.
4616 // The shift amount must be equal.
4617 if (*C0 != *C1)
4618 return nullptr;
4619 const APInt &MaskedBits = *C0;
4620 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4622 ICmpInst::Predicate DstPred;
4623 switch (SrcPred) {
4624 case ICmpInst::Predicate::ICMP_EQ:
4625 // ((%x << MaskedBits) a>> MaskedBits) == %x
4626 // =>
4627 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4628 DstPred = ICmpInst::Predicate::ICMP_ULT;
4629 break;
4630 case ICmpInst::Predicate::ICMP_NE:
4631 // ((%x << MaskedBits) a>> MaskedBits) != %x
4632 // =>
4633 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4634 DstPred = ICmpInst::Predicate::ICMP_UGE;
4635 break;
4636 // FIXME: are more folds possible?
4637 default:
4638 return nullptr;
4641 auto *XType = X->getType();
4642 const unsigned XBitWidth = XType->getScalarSizeInBits();
4643 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4644 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4646 // KeptBits = bitwidth(%x) - MaskedBits
4647 const APInt KeptBits = BitWidth - MaskedBits;
4648 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4649 // ICmpCst = (1 << KeptBits)
4650 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
4651 assert(ICmpCst.isPowerOf2());
4652 // AddCst = (1 << (KeptBits-1))
4653 const APInt AddCst = ICmpCst.lshr(1);
4654 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4656 // T0 = add %x, AddCst
4657 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
4658 // T1 = T0 DstPred ICmpCst
4659 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
4661 return T1;
4664 // Given pattern:
4665 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4666 // we should move shifts to the same hand of 'and', i.e. rewrite as
4667 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4668 // We are only interested in opposite logical shifts here.
4669 // One of the shifts can be truncated.
4670 // If we can, we want to end up creating 'lshr' shift.
4671 static Value *
4672 foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ,
4673 InstCombiner::BuilderTy &Builder) {
4674 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
4675 !I.getOperand(0)->hasOneUse())
4676 return nullptr;
4678 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
4680 // Look for an 'and' of two logical shifts, one of which may be truncated.
4681 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4682 Instruction *XShift, *MaybeTruncation, *YShift;
4683 if (!match(
4684 I.getOperand(0),
4685 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
4686 m_CombineAnd(m_TruncOrSelf(m_CombineAnd(
4687 m_AnyLogicalShift, m_Instruction(YShift))),
4688 m_Instruction(MaybeTruncation)))))
4689 return nullptr;
4691 // We potentially looked past 'trunc', but only when matching YShift,
4692 // therefore YShift must have the widest type.
4693 Instruction *WidestShift = YShift;
4694 // Therefore XShift must have the shallowest type.
4695 // Or they both have identical types if there was no truncation.
4696 Instruction *NarrowestShift = XShift;
4698 Type *WidestTy = WidestShift->getType();
4699 Type *NarrowestTy = NarrowestShift->getType();
4700 assert(NarrowestTy == I.getOperand(0)->getType() &&
4701 "We did not look past any shifts while matching XShift though.");
4702 bool HadTrunc = WidestTy != I.getOperand(0)->getType();
4704 // If YShift is a 'lshr', swap the shifts around.
4705 if (match(YShift, m_LShr(m_Value(), m_Value())))
4706 std::swap(XShift, YShift);
4708 // The shifts must be in opposite directions.
4709 auto XShiftOpcode = XShift->getOpcode();
4710 if (XShiftOpcode == YShift->getOpcode())
4711 return nullptr; // Do not care about same-direction shifts here.
4713 Value *X, *XShAmt, *Y, *YShAmt;
4714 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
4715 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
4717 // If one of the values being shifted is a constant, then we will end with
4718 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4719 // however, we will need to ensure that we won't increase instruction count.
4720 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
4721 // At least one of the hands of the 'and' should be one-use shift.
4722 if (!match(I.getOperand(0),
4723 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
4724 return nullptr;
4725 if (HadTrunc) {
4726 // Due to the 'trunc', we will need to widen X. For that either the old
4727 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4728 if (!MaybeTruncation->hasOneUse() &&
4729 !NarrowestShift->getOperand(1)->hasOneUse())
4730 return nullptr;
4734 // We have two shift amounts from two different shifts. The types of those
4735 // shift amounts may not match. If that's the case let's bailout now.
4736 if (XShAmt->getType() != YShAmt->getType())
4737 return nullptr;
4739 // As input, we have the following pattern:
4740 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4741 // We want to rewrite that as:
4742 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4743 // While we know that originally (Q+K) would not overflow
4744 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
4745 // shift amounts. so it may now overflow in smaller bitwidth.
4746 // To ensure that does not happen, we need to ensure that the total maximal
4747 // shift amount is still representable in that smaller bit width.
4748 unsigned MaximalPossibleTotalShiftAmount =
4749 (WidestTy->getScalarSizeInBits() - 1) +
4750 (NarrowestTy->getScalarSizeInBits() - 1);
4751 APInt MaximalRepresentableShiftAmount =
4752 APInt::getAllOnes(XShAmt->getType()->getScalarSizeInBits());
4753 if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
4754 return nullptr;
4756 // Can we fold (XShAmt+YShAmt) ?
4757 auto *NewShAmt = dyn_cast_or_null<Constant>(
4758 simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
4759 /*isNUW=*/false, SQ.getWithInstruction(&I)));
4760 if (!NewShAmt)
4761 return nullptr;
4762 if (NewShAmt->getType() != WidestTy) {
4763 NewShAmt =
4764 ConstantFoldCastOperand(Instruction::ZExt, NewShAmt, WidestTy, SQ.DL);
4765 if (!NewShAmt)
4766 return nullptr;
4768 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
4770 // Is the new shift amount smaller than the bit width?
4771 // FIXME: could also rely on ConstantRange.
4772 if (!match(NewShAmt,
4773 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT,
4774 APInt(WidestBitWidth, WidestBitWidth))))
4775 return nullptr;
4777 // An extra legality check is needed if we had trunc-of-lshr.
4778 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
4779 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
4780 WidestShift]() {
4781 // It isn't obvious whether it's worth it to analyze non-constants here.
4782 // Also, let's basically give up on non-splat cases, pessimizing vectors.
4783 // If *any* of these preconditions matches we can perform the fold.
4784 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
4785 ? NewShAmt->getSplatValue()
4786 : NewShAmt;
4787 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
4788 if (NewShAmtSplat &&
4789 (NewShAmtSplat->isNullValue() ||
4790 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
4791 return true;
4792 // We consider *min* leading zeros so a single outlier
4793 // blocks the transform as opposed to allowing it.
4794 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
4795 KnownBits Known = computeKnownBits(C, SQ.DL);
4796 unsigned MinLeadZero = Known.countMinLeadingZeros();
4797 // If the value being shifted has at most lowest bit set we can fold.
4798 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4799 if (MaxActiveBits <= 1)
4800 return true;
4801 // Precondition: NewShAmt u<= countLeadingZeros(C)
4802 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
4803 return true;
4805 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
4806 KnownBits Known = computeKnownBits(C, SQ.DL);
4807 unsigned MinLeadZero = Known.countMinLeadingZeros();
4808 // If the value being shifted has at most lowest bit set we can fold.
4809 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4810 if (MaxActiveBits <= 1)
4811 return true;
4812 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
4813 if (NewShAmtSplat) {
4814 APInt AdjNewShAmt =
4815 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
4816 if (AdjNewShAmt.ule(MinLeadZero))
4817 return true;
4820 return false; // Can't tell if it's ok.
4822 if (!CanFold())
4823 return nullptr;
4826 // All good, we can do this fold.
4827 X = Builder.CreateZExt(X, WidestTy);
4828 Y = Builder.CreateZExt(Y, WidestTy);
4829 // The shift is the same that was for X.
4830 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
4831 ? Builder.CreateLShr(X, NewShAmt)
4832 : Builder.CreateShl(X, NewShAmt);
4833 Value *T1 = Builder.CreateAnd(T0, Y);
4834 return Builder.CreateICmp(I.getPredicate(), T1,
4835 Constant::getNullValue(WidestTy));
4838 /// Fold
4839 /// (-1 u/ x) u< y
4840 /// ((x * y) ?/ x) != y
4841 /// to
4842 /// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
4843 /// Note that the comparison is commutative, while inverted (u>=, ==) predicate
4844 /// will mean that we are looking for the opposite answer.
4845 Value *InstCombinerImpl::foldMultiplicationOverflowCheck(ICmpInst &I) {
4846 CmpPredicate Pred;
4847 Value *X, *Y;
4848 Instruction *Mul;
4849 Instruction *Div;
4850 bool NeedNegation;
4851 // Look for: (-1 u/ x) u</u>= y
4852 if (!I.isEquality() &&
4853 match(&I, m_c_ICmp(Pred,
4854 m_CombineAnd(m_OneUse(m_UDiv(m_AllOnes(), m_Value(X))),
4855 m_Instruction(Div)),
4856 m_Value(Y)))) {
4857 Mul = nullptr;
4859 // Are we checking that overflow does not happen, or does happen?
4860 switch (Pred) {
4861 case ICmpInst::Predicate::ICMP_ULT:
4862 NeedNegation = false;
4863 break; // OK
4864 case ICmpInst::Predicate::ICMP_UGE:
4865 NeedNegation = true;
4866 break; // OK
4867 default:
4868 return nullptr; // Wrong predicate.
4870 } else // Look for: ((x * y) / x) !=/== y
4871 if (I.isEquality() &&
4872 match(&I, m_c_ICmp(Pred, m_Value(Y),
4873 m_CombineAnd(m_OneUse(m_IDiv(
4874 m_CombineAnd(m_c_Mul(m_Deferred(Y),
4875 m_Value(X)),
4876 m_Instruction(Mul)),
4877 m_Deferred(X))),
4878 m_Instruction(Div))))) {
4879 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
4880 } else
4881 return nullptr;
4883 BuilderTy::InsertPointGuard Guard(Builder);
4884 // If the pattern included (x * y), we'll want to insert new instructions
4885 // right before that original multiplication so that we can replace it.
4886 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
4887 if (MulHadOtherUses)
4888 Builder.SetInsertPoint(Mul);
4890 CallInst *Call = Builder.CreateIntrinsic(
4891 Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
4892 : Intrinsic::smul_with_overflow,
4893 X->getType(), {X, Y}, /*FMFSource=*/nullptr, "mul");
4895 // If the multiplication was used elsewhere, to ensure that we don't leave
4896 // "duplicate" instructions, replace uses of that original multiplication
4897 // with the multiplication result from the with.overflow intrinsic.
4898 if (MulHadOtherUses)
4899 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
4901 Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
4902 if (NeedNegation) // This technically increases instruction count.
4903 Res = Builder.CreateNot(Res, "mul.not.ov");
4905 // If we replaced the mul, erase it. Do this after all uses of Builder,
4906 // as the mul is used as insertion point.
4907 if (MulHadOtherUses)
4908 eraseInstFromFunction(*Mul);
4910 return Res;
4913 static Instruction *foldICmpXNegX(ICmpInst &I,
4914 InstCombiner::BuilderTy &Builder) {
4915 CmpPredicate Pred;
4916 Value *X;
4917 if (match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) {
4919 if (ICmpInst::isSigned(Pred))
4920 Pred = ICmpInst::getSwappedPredicate(Pred);
4921 else if (ICmpInst::isUnsigned(Pred))
4922 Pred = ICmpInst::getSignedPredicate(Pred);
4923 // else for equality-comparisons just keep the predicate.
4925 return ICmpInst::Create(Instruction::ICmp, Pred, X,
4926 Constant::getNullValue(X->getType()), I.getName());
4929 // A value is not equal to its negation unless that value is 0 or
4930 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
4931 if (match(&I, m_c_ICmp(Pred, m_OneUse(m_Neg(m_Value(X))), m_Deferred(X))) &&
4932 ICmpInst::isEquality(Pred)) {
4933 Type *Ty = X->getType();
4934 uint32_t BitWidth = Ty->getScalarSizeInBits();
4935 Constant *MaxSignedVal =
4936 ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
4937 Value *And = Builder.CreateAnd(X, MaxSignedVal);
4938 Constant *Zero = Constant::getNullValue(Ty);
4939 return CmpInst::Create(Instruction::ICmp, Pred, And, Zero);
4942 return nullptr;
4945 static Instruction *foldICmpAndXX(ICmpInst &I, const SimplifyQuery &Q,
4946 InstCombinerImpl &IC) {
4947 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
4948 // Normalize and operand as operand 0.
4949 CmpInst::Predicate Pred = I.getPredicate();
4950 if (match(Op1, m_c_And(m_Specific(Op0), m_Value()))) {
4951 std::swap(Op0, Op1);
4952 Pred = ICmpInst::getSwappedPredicate(Pred);
4955 if (!match(Op0, m_c_And(m_Specific(Op1), m_Value(A))))
4956 return nullptr;
4958 // (icmp (X & Y) u< X --> (X & Y) != X
4959 if (Pred == ICmpInst::ICMP_ULT)
4960 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4962 // (icmp (X & Y) u>= X --> (X & Y) == X
4963 if (Pred == ICmpInst::ICMP_UGE)
4964 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4966 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
4967 // icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and
4968 // Y is non-constant. If Y is constant the `X & C == C` form is preferable
4969 // so don't do this fold.
4970 if (!match(Op1, m_ImmConstant()))
4971 if (auto *NotOp1 =
4972 IC.getFreelyInverted(Op1, !Op1->hasNUsesOrMore(3), &IC.Builder))
4973 return new ICmpInst(Pred, IC.Builder.CreateOr(A, NotOp1),
4974 Constant::getAllOnesValue(Op1->getType()));
4975 // icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.
4976 if (auto *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
4977 return new ICmpInst(Pred, IC.Builder.CreateAnd(Op1, NotA),
4978 Constant::getNullValue(Op1->getType()));
4981 if (!ICmpInst::isSigned(Pred))
4982 return nullptr;
4984 KnownBits KnownY = IC.computeKnownBits(A, /*Depth=*/0, &I);
4985 // (X & NegY) spred X --> (X & NegY) upred X
4986 if (KnownY.isNegative())
4987 return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);
4989 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGT)
4990 return nullptr;
4992 if (KnownY.isNonNegative())
4993 // (X & PosY) s<= X --> X s>= 0
4994 // (X & PosY) s> X --> X s< 0
4995 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
4996 Constant::getNullValue(Op1->getType()));
4998 if (isKnownNegative(Op1, IC.getSimplifyQuery().getWithInstruction(&I)))
4999 // (NegX & Y) s<= NegX --> Y s< 0
5000 // (NegX & Y) s> NegX --> Y s>= 0
5001 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(Pred), A,
5002 Constant::getNullValue(A->getType()));
5004 return nullptr;
5007 static Instruction *foldICmpOrXX(ICmpInst &I, const SimplifyQuery &Q,
5008 InstCombinerImpl &IC) {
5009 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5011 // Normalize or operand as operand 0.
5012 CmpInst::Predicate Pred = I.getPredicate();
5013 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value(A)))) {
5014 std::swap(Op0, Op1);
5015 Pred = ICmpInst::getSwappedPredicate(Pred);
5016 } else if (!match(Op0, m_c_Or(m_Specific(Op1), m_Value(A)))) {
5017 return nullptr;
5020 // icmp (X | Y) u<= X --> (X | Y) == X
5021 if (Pred == ICmpInst::ICMP_ULE)
5022 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5024 // icmp (X | Y) u> X --> (X | Y) != X
5025 if (Pred == ICmpInst::ICMP_UGT)
5026 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5028 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5029 // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
5030 if (Value *NotOp1 =
5031 IC.getFreelyInverted(Op1, !Op1->hasNUsesOrMore(3), &IC.Builder))
5032 return new ICmpInst(Pred, IC.Builder.CreateAnd(A, NotOp1),
5033 Constant::getNullValue(Op1->getType()));
5034 // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.
5035 if (Value *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5036 return new ICmpInst(Pred, IC.Builder.CreateOr(Op1, NotA),
5037 Constant::getAllOnesValue(Op1->getType()));
5039 return nullptr;
5042 static Instruction *foldICmpXorXX(ICmpInst &I, const SimplifyQuery &Q,
5043 InstCombinerImpl &IC) {
5044 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5045 // Normalize xor operand as operand 0.
5046 CmpInst::Predicate Pred = I.getPredicate();
5047 if (match(Op1, m_c_Xor(m_Specific(Op0), m_Value()))) {
5048 std::swap(Op0, Op1);
5049 Pred = ICmpInst::getSwappedPredicate(Pred);
5051 if (!match(Op0, m_c_Xor(m_Specific(Op1), m_Value(A))))
5052 return nullptr;
5054 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
5055 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
5056 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
5057 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
5058 CmpInst::Predicate PredOut = CmpInst::getStrictPredicate(Pred);
5059 if (PredOut != Pred && isKnownNonZero(A, Q))
5060 return new ICmpInst(PredOut, Op0, Op1);
5062 return nullptr;
5065 /// Try to fold icmp (binop), X or icmp X, (binop).
5066 /// TODO: A large part of this logic is duplicated in InstSimplify's
5067 /// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
5068 /// duplication.
5069 Instruction *InstCombinerImpl::foldICmpBinOp(ICmpInst &I,
5070 const SimplifyQuery &SQ) {
5071 const SimplifyQuery Q = SQ.getWithInstruction(&I);
5072 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5074 // Special logic for binary operators.
5075 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
5076 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
5077 if (!BO0 && !BO1)
5078 return nullptr;
5080 if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
5081 return NewICmp;
5083 const CmpInst::Predicate Pred = I.getPredicate();
5084 Value *X;
5086 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
5087 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
5088 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
5089 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5090 return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
5091 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
5092 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
5093 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5094 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
5097 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
5098 Constant *C;
5099 if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
5100 m_ImmConstant(C)))) &&
5101 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
5102 Constant *C2 = ConstantExpr::getNot(C);
5103 return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
5105 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
5106 if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
5107 m_ImmConstant(C)))) &&
5108 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
5109 Constant *C2 = ConstantExpr::getNot(C);
5110 return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
5114 // (icmp eq/ne (X, -P2), INT_MIN)
5115 // -> (icmp slt/sge X, INT_MIN + P2)
5116 if (ICmpInst::isEquality(Pred) && BO0 &&
5117 match(I.getOperand(1), m_SignMask()) &&
5118 match(BO0, m_And(m_Value(), m_NegatedPower2OrZero()))) {
5119 // Will Constant fold.
5120 Value *NewC = Builder.CreateSub(I.getOperand(1), BO0->getOperand(1));
5121 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SLT
5122 : ICmpInst::ICMP_SGE,
5123 BO0->getOperand(0), NewC);
5127 // Similar to above: an unsigned overflow comparison may use offset + mask:
5128 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
5129 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
5130 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
5131 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
5132 BinaryOperator *BO;
5133 const APInt *C;
5134 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
5135 match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5136 match(BO, m_Add(m_Specific(Op1), m_SpecificIntAllowPoison(*C)))) {
5137 CmpInst::Predicate NewPred =
5138 Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
5139 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5140 return new ICmpInst(NewPred, Op1, Zero);
5143 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5144 match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5145 match(BO, m_Add(m_Specific(Op0), m_SpecificIntAllowPoison(*C)))) {
5146 CmpInst::Predicate NewPred =
5147 Pred == ICmpInst::ICMP_UGT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
5148 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5149 return new ICmpInst(NewPred, Op0, Zero);
5153 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
5154 bool Op0HasNUW = false, Op1HasNUW = false;
5155 bool Op0HasNSW = false, Op1HasNSW = false;
5156 // Analyze the case when either Op0 or Op1 is an add instruction.
5157 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
5158 auto hasNoWrapProblem = [](const BinaryOperator &BO, CmpInst::Predicate Pred,
5159 bool &HasNSW, bool &HasNUW) -> bool {
5160 if (isa<OverflowingBinaryOperator>(BO)) {
5161 HasNUW = BO.hasNoUnsignedWrap();
5162 HasNSW = BO.hasNoSignedWrap();
5163 return ICmpInst::isEquality(Pred) ||
5164 (CmpInst::isUnsigned(Pred) && HasNUW) ||
5165 (CmpInst::isSigned(Pred) && HasNSW);
5166 } else if (BO.getOpcode() == Instruction::Or) {
5167 HasNUW = true;
5168 HasNSW = true;
5169 return true;
5170 } else {
5171 return false;
5174 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5176 if (BO0) {
5177 match(BO0, m_AddLike(m_Value(A), m_Value(B)));
5178 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5180 if (BO1) {
5181 match(BO1, m_AddLike(m_Value(C), m_Value(D)));
5182 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5185 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5186 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5187 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5188 return new ICmpInst(Pred, A == Op1 ? B : A,
5189 Constant::getNullValue(Op1->getType()));
5191 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5192 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5193 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5194 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
5195 C == Op0 ? D : C);
5197 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
5198 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
5199 NoOp1WrapProblem) {
5200 // Determine Y and Z in the form icmp (X+Y), (X+Z).
5201 Value *Y, *Z;
5202 if (A == C) {
5203 // C + B == C + D -> B == D
5204 Y = B;
5205 Z = D;
5206 } else if (A == D) {
5207 // D + B == C + D -> B == C
5208 Y = B;
5209 Z = C;
5210 } else if (B == C) {
5211 // A + C == C + D -> A == D
5212 Y = A;
5213 Z = D;
5214 } else {
5215 assert(B == D);
5216 // A + D == C + D -> A == C
5217 Y = A;
5218 Z = C;
5220 return new ICmpInst(Pred, Y, Z);
5223 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5224 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
5225 match(B, m_AllOnes()))
5226 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
5228 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5229 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
5230 match(B, m_AllOnes()))
5231 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
5233 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5234 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One()))
5235 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
5237 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5238 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One()))
5239 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
5241 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5242 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
5243 match(D, m_AllOnes()))
5244 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
5246 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5247 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
5248 match(D, m_AllOnes()))
5249 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
5251 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5252 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One()))
5253 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
5255 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5256 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One()))
5257 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
5259 // TODO: The subtraction-related identities shown below also hold, but
5260 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
5261 // wouldn't happen even if they were implemented.
5263 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5264 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5265 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5266 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5268 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5269 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One()))
5270 return new ICmpInst(CmpInst::ICMP_ULT, A, Op1);
5272 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5273 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One()))
5274 return new ICmpInst(CmpInst::ICMP_UGE, A, Op1);
5276 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5277 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One()))
5278 return new ICmpInst(CmpInst::ICMP_UGT, Op0, C);
5280 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5281 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One()))
5282 return new ICmpInst(CmpInst::ICMP_ULE, Op0, C);
5284 // if C1 has greater magnitude than C2:
5285 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5286 // s.t. C3 = C1 - C2
5288 // if C2 has greater magnitude than C1:
5289 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5290 // s.t. C3 = C2 - C1
5291 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5292 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5293 const APInt *AP1, *AP2;
5294 // TODO: Support non-uniform vectors.
5295 // TODO: Allow poison passthrough if B or D's element is poison.
5296 if (match(B, m_APIntAllowPoison(AP1)) &&
5297 match(D, m_APIntAllowPoison(AP2)) &&
5298 AP1->isNegative() == AP2->isNegative()) {
5299 APInt AP1Abs = AP1->abs();
5300 APInt AP2Abs = AP2->abs();
5301 if (AP1Abs.uge(AP2Abs)) {
5302 APInt Diff = *AP1 - *AP2;
5303 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5304 Value *NewAdd = Builder.CreateAdd(
5305 A, C3, "", Op0HasNUW && Diff.ule(*AP1), Op0HasNSW);
5306 return new ICmpInst(Pred, NewAdd, C);
5307 } else {
5308 APInt Diff = *AP2 - *AP1;
5309 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5310 Value *NewAdd = Builder.CreateAdd(
5311 C, C3, "", Op1HasNUW && Diff.ule(*AP2), Op1HasNSW);
5312 return new ICmpInst(Pred, A, NewAdd);
5315 Constant *Cst1, *Cst2;
5316 if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
5317 ICmpInst::isEquality(Pred)) {
5318 Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
5319 Value *NewAdd = Builder.CreateAdd(C, Diff);
5320 return new ICmpInst(Pred, A, NewAdd);
5324 // Analyze the case when either Op0 or Op1 is a sub instruction.
5325 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5326 A = nullptr;
5327 B = nullptr;
5328 C = nullptr;
5329 D = nullptr;
5330 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5331 A = BO0->getOperand(0);
5332 B = BO0->getOperand(1);
5334 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5335 C = BO1->getOperand(0);
5336 D = BO1->getOperand(1);
5339 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5340 if (A == Op1 && NoOp0WrapProblem)
5341 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
5342 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5343 if (C == Op0 && NoOp1WrapProblem)
5344 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
5346 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5347 // (A - B) u>/u<= A --> B u>/u<= A
5348 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5349 return new ICmpInst(Pred, B, A);
5350 // C u</u>= (C - D) --> C u</u>= D
5351 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5352 return new ICmpInst(Pred, C, D);
5353 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5354 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5355 isKnownNonZero(B, Q))
5356 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), B, A);
5357 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5358 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5359 isKnownNonZero(D, Q))
5360 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), C, D);
5362 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
5363 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
5364 return new ICmpInst(Pred, A, C);
5366 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
5367 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
5368 return new ICmpInst(Pred, D, B);
5370 // icmp (0-X) < cst --> x > -cst
5371 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
5372 Value *X;
5373 if (match(BO0, m_Neg(m_Value(X))))
5374 if (Constant *RHSC = dyn_cast<Constant>(Op1))
5375 if (RHSC->isNotMinSignedValue())
5376 return new ICmpInst(I.getSwappedPredicate(), X,
5377 ConstantExpr::getNeg(RHSC));
5380 if (Instruction *R = foldICmpXorXX(I, Q, *this))
5381 return R;
5382 if (Instruction *R = foldICmpOrXX(I, Q, *this))
5383 return R;
5386 // Try to remove shared multiplier from comparison:
5387 // X * Z pred Y * Z
5388 Value *X, *Y, *Z;
5389 if ((match(Op0, m_Mul(m_Value(X), m_Value(Z))) &&
5390 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))) ||
5391 (match(Op0, m_Mul(m_Value(Z), m_Value(X))) &&
5392 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y))))) {
5393 if (ICmpInst::isSigned(Pred)) {
5394 if (Op0HasNSW && Op1HasNSW) {
5395 KnownBits ZKnown = computeKnownBits(Z, 0, &I);
5396 if (ZKnown.isStrictlyPositive())
5397 return new ICmpInst(Pred, X, Y);
5398 if (ZKnown.isNegative())
5399 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), X, Y);
5400 Value *LessThan = simplifyICmpInst(ICmpInst::ICMP_SLT, X, Y,
5401 SQ.getWithInstruction(&I));
5402 if (LessThan && match(LessThan, m_One()))
5403 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Z,
5404 Constant::getNullValue(Z->getType()));
5405 Value *GreaterThan = simplifyICmpInst(ICmpInst::ICMP_SGT, X, Y,
5406 SQ.getWithInstruction(&I));
5407 if (GreaterThan && match(GreaterThan, m_One()))
5408 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5410 } else {
5411 bool NonZero;
5412 if (ICmpInst::isEquality(Pred)) {
5413 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5414 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5415 isKnownNonEqual(X, Y, SQ))
5416 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5418 KnownBits ZKnown = computeKnownBits(Z, 0, &I);
5419 // if Z % 2 != 0
5420 // X * Z eq/ne Y * Z -> X eq/ne Y
5421 if (ZKnown.countMaxTrailingZeros() == 0)
5422 return new ICmpInst(Pred, X, Y);
5423 NonZero = !ZKnown.One.isZero() || isKnownNonZero(Z, Q);
5424 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5425 // X * Z eq/ne Y * Z -> X eq/ne Y
5426 if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)
5427 return new ICmpInst(Pred, X, Y);
5428 } else
5429 NonZero = isKnownNonZero(Z, Q);
5431 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5432 // X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
5433 if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)
5434 return new ICmpInst(Pred, X, Y);
5439 BinaryOperator *SRem = nullptr;
5440 // icmp (srem X, Y), Y
5441 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
5442 SRem = BO0;
5443 // icmp Y, (srem X, Y)
5444 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5445 Op0 == BO1->getOperand(1))
5446 SRem = BO1;
5447 if (SRem) {
5448 // We don't check hasOneUse to avoid increasing register pressure because
5449 // the value we use is the same value this instruction was already using.
5450 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
5451 default:
5452 break;
5453 case ICmpInst::ICMP_EQ:
5454 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5455 case ICmpInst::ICMP_NE:
5456 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5457 case ICmpInst::ICMP_SGT:
5458 case ICmpInst::ICMP_SGE:
5459 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
5460 Constant::getAllOnesValue(SRem->getType()));
5461 case ICmpInst::ICMP_SLT:
5462 case ICmpInst::ICMP_SLE:
5463 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
5464 Constant::getNullValue(SRem->getType()));
5468 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5469 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5470 BO0->getOperand(1) == BO1->getOperand(1)) {
5471 switch (BO0->getOpcode()) {
5472 default:
5473 break;
5474 case Instruction::Add:
5475 case Instruction::Sub:
5476 case Instruction::Xor: {
5477 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5478 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5480 const APInt *C;
5481 if (match(BO0->getOperand(1), m_APInt(C))) {
5482 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5483 if (C->isSignMask()) {
5484 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5485 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5488 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5489 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5490 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5491 NewPred = I.getSwappedPredicate(NewPred);
5492 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5495 break;
5497 case Instruction::Mul: {
5498 if (!I.isEquality())
5499 break;
5501 const APInt *C;
5502 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
5503 !C->isOne()) {
5504 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5505 // Mask = -1 >> count-trailing-zeros(C).
5506 if (unsigned TZs = C->countr_zero()) {
5507 Constant *Mask = ConstantInt::get(
5508 BO0->getType(),
5509 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
5510 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
5511 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
5512 return new ICmpInst(Pred, And1, And2);
5515 break;
5517 case Instruction::UDiv:
5518 case Instruction::LShr:
5519 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
5520 break;
5521 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5523 case Instruction::SDiv:
5524 if (!(I.isEquality() || match(BO0->getOperand(1), m_NonNegative())) ||
5525 !BO0->isExact() || !BO1->isExact())
5526 break;
5527 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5529 case Instruction::AShr:
5530 if (!BO0->isExact() || !BO1->isExact())
5531 break;
5532 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5534 case Instruction::Shl: {
5535 bool NUW = Op0HasNUW && Op1HasNUW;
5536 bool NSW = Op0HasNSW && Op1HasNSW;
5537 if (!NUW && !NSW)
5538 break;
5539 if (!NSW && I.isSigned())
5540 break;
5541 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5546 if (BO0) {
5547 // Transform A & (L - 1) `ult` L --> L != 0
5548 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
5549 auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
5551 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5552 auto *Zero = Constant::getNullValue(BO0->getType());
5553 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5557 // For unsigned predicates / eq / ne:
5558 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5559 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5560 if (!ICmpInst::isSigned(Pred)) {
5561 if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
5562 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5563 Constant::getNullValue(Op1->getType()));
5564 else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
5565 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5566 Constant::getNullValue(Op0->getType()), Op0);
5569 if (Value *V = foldMultiplicationOverflowCheck(I))
5570 return replaceInstUsesWith(I, V);
5572 if (Instruction *R = foldICmpAndXX(I, Q, *this))
5573 return R;
5575 if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder))
5576 return replaceInstUsesWith(I, V);
5578 if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder))
5579 return replaceInstUsesWith(I, V);
5581 return nullptr;
5584 /// Fold icmp Pred min|max(X, Y), Z.
5585 Instruction *InstCombinerImpl::foldICmpWithMinMax(Instruction &I,
5586 MinMaxIntrinsic *MinMax,
5587 Value *Z, CmpPredicate Pred) {
5588 Value *X = MinMax->getLHS();
5589 Value *Y = MinMax->getRHS();
5590 if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5591 return nullptr;
5592 if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {
5593 // Revert the transform signed pred -> unsigned pred
5594 // TODO: We can flip the signedness of predicate if both operands of icmp
5595 // are negative.
5596 if (isKnownNonNegative(Z, SQ.getWithInstruction(&I)) &&
5597 isKnownNonNegative(MinMax, SQ.getWithInstruction(&I))) {
5598 Pred = ICmpInst::getFlippedSignednessPredicate(Pred);
5599 } else
5600 return nullptr;
5602 SimplifyQuery Q = SQ.getWithInstruction(&I);
5603 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5604 if (!Val)
5605 return std::nullopt;
5606 if (match(Val, m_One()))
5607 return true;
5608 if (match(Val, m_Zero()))
5609 return false;
5610 return std::nullopt;
5612 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, X, Z, Q));
5613 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, Y, Z, Q));
5614 if (!CmpXZ.has_value() && !CmpYZ.has_value())
5615 return nullptr;
5616 if (!CmpXZ.has_value()) {
5617 std::swap(X, Y);
5618 std::swap(CmpXZ, CmpYZ);
5621 auto FoldIntoCmpYZ = [&]() -> Instruction * {
5622 if (CmpYZ.has_value())
5623 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *CmpYZ));
5624 return ICmpInst::Create(Instruction::ICmp, Pred, Y, Z);
5627 switch (Pred) {
5628 case ICmpInst::ICMP_EQ:
5629 case ICmpInst::ICMP_NE: {
5630 // If X == Z:
5631 // Expr Result
5632 // min(X, Y) == Z X <= Y
5633 // max(X, Y) == Z X >= Y
5634 // min(X, Y) != Z X > Y
5635 // max(X, Y) != Z X < Y
5636 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5637 ICmpInst::Predicate NewPred =
5638 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
5639 if (Pred == ICmpInst::ICMP_NE)
5640 NewPred = ICmpInst::getInversePredicate(NewPred);
5641 return ICmpInst::Create(Instruction::ICmp, NewPred, X, Y);
5643 // Otherwise (X != Z):
5644 ICmpInst::Predicate NewPred = MinMax->getPredicate();
5645 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5646 if (!MinMaxCmpXZ.has_value()) {
5647 std::swap(X, Y);
5648 std::swap(CmpXZ, CmpYZ);
5649 // Re-check pre-condition X != Z
5650 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5651 break;
5652 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5654 if (!MinMaxCmpXZ.has_value())
5655 break;
5656 if (*MinMaxCmpXZ) {
5657 // Expr Fact Result
5658 // min(X, Y) == Z X < Z false
5659 // max(X, Y) == Z X > Z false
5660 // min(X, Y) != Z X < Z true
5661 // max(X, Y) != Z X > Z true
5662 return replaceInstUsesWith(
5663 I, ConstantInt::getBool(I.getType(), Pred == ICmpInst::ICMP_NE));
5664 } else {
5665 // Expr Fact Result
5666 // min(X, Y) == Z X > Z Y == Z
5667 // max(X, Y) == Z X < Z Y == Z
5668 // min(X, Y) != Z X > Z Y != Z
5669 // max(X, Y) != Z X < Z Y != Z
5670 return FoldIntoCmpYZ();
5672 break;
5674 case ICmpInst::ICMP_SLT:
5675 case ICmpInst::ICMP_ULT:
5676 case ICmpInst::ICMP_SLE:
5677 case ICmpInst::ICMP_ULE:
5678 case ICmpInst::ICMP_SGT:
5679 case ICmpInst::ICMP_UGT:
5680 case ICmpInst::ICMP_SGE:
5681 case ICmpInst::ICMP_UGE: {
5682 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(Pred);
5683 if (*CmpXZ) {
5684 if (IsSame) {
5685 // Expr Fact Result
5686 // min(X, Y) < Z X < Z true
5687 // min(X, Y) <= Z X <= Z true
5688 // max(X, Y) > Z X > Z true
5689 // max(X, Y) >= Z X >= Z true
5690 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5691 } else {
5692 // Expr Fact Result
5693 // max(X, Y) < Z X < Z Y < Z
5694 // max(X, Y) <= Z X <= Z Y <= Z
5695 // min(X, Y) > Z X > Z Y > Z
5696 // min(X, Y) >= Z X >= Z Y >= Z
5697 return FoldIntoCmpYZ();
5699 } else {
5700 if (IsSame) {
5701 // Expr Fact Result
5702 // min(X, Y) < Z X >= Z Y < Z
5703 // min(X, Y) <= Z X > Z Y <= Z
5704 // max(X, Y) > Z X <= Z Y > Z
5705 // max(X, Y) >= Z X < Z Y >= Z
5706 return FoldIntoCmpYZ();
5707 } else {
5708 // Expr Fact Result
5709 // max(X, Y) < Z X >= Z false
5710 // max(X, Y) <= Z X > Z false
5711 // min(X, Y) > Z X <= Z false
5712 // min(X, Y) >= Z X < Z false
5713 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5716 break;
5718 default:
5719 break;
5722 return nullptr;
5725 // Canonicalize checking for a power-of-2-or-zero value:
5726 static Instruction *foldICmpPow2Test(ICmpInst &I,
5727 InstCombiner::BuilderTy &Builder) {
5728 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5729 const CmpInst::Predicate Pred = I.getPredicate();
5730 Value *A = nullptr;
5731 bool CheckIs;
5732 if (I.isEquality()) {
5733 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
5734 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
5735 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
5736 m_Deferred(A)))) ||
5737 !match(Op1, m_ZeroInt()))
5738 A = nullptr;
5740 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
5741 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
5742 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
5743 A = Op1;
5744 else if (match(Op1,
5745 m_OneUse(m_c_And(m_Neg(m_Specific(Op0)), m_Specific(Op0)))))
5746 A = Op0;
5748 CheckIs = Pred == ICmpInst::ICMP_EQ;
5749 } else if (ICmpInst::isUnsigned(Pred)) {
5750 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
5751 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
5753 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5754 match(Op0, m_OneUse(m_c_Xor(m_Add(m_Specific(Op1), m_AllOnes()),
5755 m_Specific(Op1))))) {
5756 A = Op1;
5757 CheckIs = Pred == ICmpInst::ICMP_UGE;
5758 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5759 match(Op1, m_OneUse(m_c_Xor(m_Add(m_Specific(Op0), m_AllOnes()),
5760 m_Specific(Op0))))) {
5761 A = Op0;
5762 CheckIs = Pred == ICmpInst::ICMP_ULE;
5766 if (A) {
5767 Type *Ty = A->getType();
5768 CallInst *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
5769 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
5770 ConstantInt::get(Ty, 2))
5771 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
5772 ConstantInt::get(Ty, 1));
5775 return nullptr;
5778 Instruction *InstCombinerImpl::foldICmpEquality(ICmpInst &I) {
5779 if (!I.isEquality())
5780 return nullptr;
5782 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5783 const CmpInst::Predicate Pred = I.getPredicate();
5784 Value *A, *B, *C, *D;
5785 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5786 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5787 Value *OtherVal = A == Op1 ? B : A;
5788 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
5791 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5792 // A^c1 == C^c2 --> A == C^(c1^c2)
5793 ConstantInt *C1, *C2;
5794 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
5795 Op1->hasOneUse()) {
5796 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
5797 Value *Xor = Builder.CreateXor(C, NC);
5798 return new ICmpInst(Pred, A, Xor);
5801 // A^B == A^D -> B == D
5802 if (A == C)
5803 return new ICmpInst(Pred, B, D);
5804 if (A == D)
5805 return new ICmpInst(Pred, B, C);
5806 if (B == C)
5807 return new ICmpInst(Pred, A, D);
5808 if (B == D)
5809 return new ICmpInst(Pred, A, C);
5813 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
5814 // A == (A^B) -> B == 0
5815 Value *OtherVal = A == Op0 ? B : A;
5816 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
5819 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5820 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
5821 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5822 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
5824 if (A == C) {
5825 X = B;
5826 Y = D;
5827 Z = A;
5828 } else if (A == D) {
5829 X = B;
5830 Y = C;
5831 Z = A;
5832 } else if (B == C) {
5833 X = A;
5834 Y = D;
5835 Z = B;
5836 } else if (B == D) {
5837 X = A;
5838 Y = C;
5839 Z = B;
5842 if (X) {
5843 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
5844 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
5845 // instructions.
5846 const APInt *C0, *C1;
5847 bool XorIsNegP2 = match(X, m_APInt(C0)) && match(Y, m_APInt(C1)) &&
5848 (*C0 ^ *C1).isNegatedPowerOf2();
5850 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
5851 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
5852 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
5853 int UseCnt =
5854 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
5855 (int(match(X, m_ImmConstant()) && match(Y, m_ImmConstant())));
5856 if (XorIsNegP2 || UseCnt >= 2) {
5857 // Build (X^Y) & Z
5858 Op1 = Builder.CreateXor(X, Y);
5859 Op1 = Builder.CreateAnd(Op1, Z);
5860 return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
5866 // Similar to above, but specialized for constant because invert is needed:
5867 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
5868 Value *X, *Y;
5869 Constant *C;
5870 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
5871 match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
5872 Value *Xor = Builder.CreateXor(X, Y);
5873 Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
5874 return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
5878 if (match(Op1, m_ZExt(m_Value(A))) &&
5879 (Op0->hasOneUse() || Op1->hasOneUse())) {
5880 // (B & (Pow2C-1)) == zext A --> A == trunc B
5881 // (B & (Pow2C-1)) != zext A --> A != trunc B
5882 const APInt *MaskC;
5883 if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
5884 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
5885 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
5888 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
5889 // For lshr and ashr pairs.
5890 const APInt *AP1, *AP2;
5891 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
5892 match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowPoison(AP2))))) ||
5893 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
5894 match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowPoison(AP2)))))) {
5895 if (AP1 != AP2)
5896 return nullptr;
5897 unsigned TypeBits = AP1->getBitWidth();
5898 unsigned ShAmt = AP1->getLimitedValue(TypeBits);
5899 if (ShAmt < TypeBits && ShAmt != 0) {
5900 ICmpInst::Predicate NewPred =
5901 Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5902 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
5903 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
5904 return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
5908 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
5909 ConstantInt *Cst1;
5910 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
5911 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
5912 unsigned TypeBits = Cst1->getBitWidth();
5913 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
5914 if (ShAmt < TypeBits && ShAmt != 0) {
5915 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
5916 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
5917 Value *And =
5918 Builder.CreateAnd(Xor, Builder.getInt(AndVal), I.getName() + ".mask");
5919 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
5923 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
5924 // "icmp (and X, mask), cst"
5925 uint64_t ShAmt = 0;
5926 if (Op0->hasOneUse() &&
5927 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
5928 match(Op1, m_ConstantInt(Cst1)) &&
5929 // Only do this when A has multiple uses. This is most important to do
5930 // when it exposes other optimizations.
5931 !A->hasOneUse()) {
5932 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
5934 if (ShAmt < ASize) {
5935 APInt MaskV =
5936 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
5937 MaskV <<= ShAmt;
5939 APInt CmpV = Cst1->getValue().zext(ASize);
5940 CmpV <<= ShAmt;
5942 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
5943 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
5947 if (Instruction *ICmp = foldICmpIntrinsicWithIntrinsic(I, Builder))
5948 return ICmp;
5950 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
5951 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
5952 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
5953 // few steps of instcombine.
5954 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
5955 if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
5956 match(Op1, m_Trunc(m_LShr(m_Specific(A), m_SpecificInt(BitWidth)))) &&
5957 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
5958 (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
5959 APInt C = APInt::getOneBitSet(BitWidth * 2, BitWidth - 1);
5960 Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
5961 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
5962 : ICmpInst::ICMP_UGE,
5963 Add, ConstantInt::get(A->getType(), C.shl(1)));
5966 // Canonicalize:
5967 // Assume B_Pow2 != 0
5968 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
5969 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
5970 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
5971 isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, 0, &I))
5972 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
5973 ConstantInt::getNullValue(Op0->getType()));
5975 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
5976 isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, 0, &I))
5977 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
5978 ConstantInt::getNullValue(Op1->getType()));
5980 // Canonicalize:
5981 // icmp eq/ne X, OneUse(rotate-right(X))
5982 // -> icmp eq/ne X, rotate-left(X)
5983 // We generally try to convert rotate-right -> rotate-left, this just
5984 // canonicalizes another case.
5985 if (match(&I, m_c_ICmp(m_Value(A),
5986 m_OneUse(m_Intrinsic<Intrinsic::fshr>(
5987 m_Deferred(A), m_Deferred(A), m_Value(B))))))
5988 return new ICmpInst(
5989 Pred, A,
5990 Builder.CreateIntrinsic(Op0->getType(), Intrinsic::fshl, {A, A, B}));
5992 // Canonicalize:
5993 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
5994 Constant *Cst;
5995 if (match(&I, m_c_ICmp(m_OneUse(m_Xor(m_Value(A), m_ImmConstant(Cst))),
5996 m_CombineAnd(m_Value(B), m_Unless(m_ImmConstant())))))
5997 return new ICmpInst(Pred, Builder.CreateXor(A, B), Cst);
6000 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6001 auto m_Matcher =
6002 m_CombineOr(m_CombineOr(m_c_Add(m_Value(B), m_Deferred(A)),
6003 m_c_Xor(m_Value(B), m_Deferred(A))),
6004 m_Sub(m_Value(B), m_Deferred(A)));
6005 std::optional<bool> IsZero = std::nullopt;
6006 if (match(&I, m_c_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)),
6007 m_Deferred(A))))
6008 IsZero = false;
6009 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6010 else if (match(&I,
6011 m_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)), m_Zero())))
6012 IsZero = true;
6014 if (IsZero && isKnownToBeAPowerOfTwo(A, /* OrZero */ true, /*Depth*/ 0, &I))
6015 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6016 // -> (icmp eq/ne (and X, P2), 0)
6017 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6018 // -> (icmp eq/ne (and X, P2), P2)
6019 return new ICmpInst(Pred, Builder.CreateAnd(B, A),
6020 *IsZero ? A
6021 : ConstantInt::getNullValue(A->getType()));
6024 return nullptr;
6027 Instruction *InstCombinerImpl::foldICmpWithTrunc(ICmpInst &ICmp) {
6028 ICmpInst::Predicate Pred = ICmp.getPredicate();
6029 Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
6031 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6032 // The trunc masks high bits while the compare may effectively mask low bits.
6033 Value *X;
6034 const APInt *C;
6035 if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
6036 return nullptr;
6038 // This matches patterns corresponding to tests of the signbit as well as:
6039 // (trunc X) pred C2 --> (X & Mask) == C
6040 if (auto Res = decomposeBitTestICmp(Op0, Op1, Pred, /*WithTrunc=*/true,
6041 /*AllowNonZeroC=*/true)) {
6042 Value *And = Builder.CreateAnd(Res->X, Res->Mask);
6043 Constant *C = ConstantInt::get(Res->X->getType(), Res->C);
6044 return new ICmpInst(Res->Pred, And, C);
6047 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6048 if (auto *II = dyn_cast<IntrinsicInst>(X)) {
6049 if (II->getIntrinsicID() == Intrinsic::cttz ||
6050 II->getIntrinsicID() == Intrinsic::ctlz) {
6051 unsigned MaxRet = SrcBits;
6052 // If the "is_zero_poison" argument is set, then we know at least
6053 // one bit is set in the input, so the result is always at least one
6054 // less than the full bitwidth of that input.
6055 if (match(II->getArgOperand(1), m_One()))
6056 MaxRet--;
6058 // Make sure the destination is wide enough to hold the largest output of
6059 // the intrinsic.
6060 if (llvm::Log2_32(MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6061 if (Instruction *I =
6062 foldICmpIntrinsicWithConstant(ICmp, II, C->zext(SrcBits)))
6063 return I;
6067 return nullptr;
6070 Instruction *InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst &ICmp) {
6071 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6072 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
6073 Value *X;
6074 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
6075 return nullptr;
6077 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6078 bool IsSignedCmp = ICmp.isSigned();
6080 // icmp Pred (ext X), (ext Y)
6081 Value *Y;
6082 if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
6083 bool IsZext0 = isa<ZExtInst>(ICmp.getOperand(0));
6084 bool IsZext1 = isa<ZExtInst>(ICmp.getOperand(1));
6086 if (IsZext0 != IsZext1) {
6087 // If X and Y and both i1
6088 // (icmp eq/ne (zext X) (sext Y))
6089 // eq -> (icmp eq (or X, Y), 0)
6090 // ne -> (icmp ne (or X, Y), 0)
6091 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(1) &&
6092 Y->getType()->isIntOrIntVectorTy(1))
6093 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
6094 Constant::getNullValue(X->getType()));
6096 // If we have mismatched casts and zext has the nneg flag, we can
6097 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6099 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(0));
6100 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(1));
6102 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6103 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6105 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6106 IsSignedExt = true;
6107 else
6108 return nullptr;
6111 // Not an extension from the same type?
6112 Type *XTy = X->getType(), *YTy = Y->getType();
6113 if (XTy != YTy) {
6114 // One of the casts must have one use because we are creating a new cast.
6115 if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
6116 return nullptr;
6117 // Extend the narrower operand to the type of the wider operand.
6118 CastInst::CastOps CastOpcode =
6119 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6120 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6121 X = Builder.CreateCast(CastOpcode, X, YTy);
6122 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6123 Y = Builder.CreateCast(CastOpcode, Y, XTy);
6124 else
6125 return nullptr;
6128 // (zext X) == (zext Y) --> X == Y
6129 // (sext X) == (sext Y) --> X == Y
6130 if (ICmp.isEquality())
6131 return new ICmpInst(ICmp.getPredicate(), X, Y);
6133 // A signed comparison of sign extended values simplifies into a
6134 // signed comparison.
6135 if (IsSignedCmp && IsSignedExt)
6136 return new ICmpInst(ICmp.getPredicate(), X, Y);
6138 // The other three cases all fold into an unsigned comparison.
6139 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6142 // Below here, we are only folding a compare with constant.
6143 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
6144 if (!C)
6145 return nullptr;
6147 // If a lossless truncate is possible...
6148 Type *SrcTy = CastOp0->getSrcTy();
6149 Constant *Res = getLosslessTrunc(C, SrcTy, CastOp0->getOpcode());
6150 if (Res) {
6151 if (ICmp.isEquality())
6152 return new ICmpInst(ICmp.getPredicate(), X, Res);
6154 // A signed comparison of sign extended values simplifies into a
6155 // signed comparison.
6156 if (IsSignedExt && IsSignedCmp)
6157 return new ICmpInst(ICmp.getPredicate(), X, Res);
6159 // The other three cases all fold into an unsigned comparison.
6160 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6163 // The re-extended constant changed, partly changed (in the case of a vector),
6164 // or could not be determined to be equal (in the case of a constant
6165 // expression), so the constant cannot be represented in the shorter type.
6166 // All the cases that fold to true or false will have already been handled
6167 // by simplifyICmpInst, so only deal with the tricky case.
6168 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
6169 return nullptr;
6171 // Is source op positive?
6172 // icmp ult (sext X), C --> icmp sgt X, -1
6173 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6174 return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(SrcTy));
6176 // Is source op negative?
6177 // icmp ugt (sext X), C --> icmp slt X, 0
6178 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6179 return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(SrcTy));
6182 /// Handle icmp (cast x), (cast or constant).
6183 Instruction *InstCombinerImpl::foldICmpWithCastOp(ICmpInst &ICmp) {
6184 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6185 // icmp compares only pointer's value.
6186 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6187 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
6188 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
6189 if (SimplifiedOp0 || SimplifiedOp1)
6190 return new ICmpInst(ICmp.getPredicate(),
6191 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
6192 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
6194 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
6195 if (!CastOp0)
6196 return nullptr;
6197 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
6198 return nullptr;
6200 Value *Op0Src = CastOp0->getOperand(0);
6201 Type *SrcTy = CastOp0->getSrcTy();
6202 Type *DestTy = CastOp0->getDestTy();
6204 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6205 // integer type is the same size as the pointer type.
6206 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6207 if (isa<VectorType>(PtrTy)) {
6208 PtrTy = cast<VectorType>(PtrTy)->getElementType();
6209 IntTy = cast<VectorType>(IntTy)->getElementType();
6211 return DL.getPointerTypeSizeInBits(PtrTy) == IntTy->getIntegerBitWidth();
6213 if (CastOp0->getOpcode() == Instruction::PtrToInt &&
6214 CompatibleSizes(SrcTy, DestTy)) {
6215 Value *NewOp1 = nullptr;
6216 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
6217 Value *PtrSrc = PtrToIntOp1->getOperand(0);
6218 if (PtrSrc->getType() == Op0Src->getType())
6219 NewOp1 = PtrToIntOp1->getOperand(0);
6220 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
6221 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6224 if (NewOp1)
6225 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6228 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6229 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6230 CompatibleSizes(DestTy, SrcTy)) {
6231 Value *NewOp1 = nullptr;
6232 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(ICmp.getOperand(1))) {
6233 Value *IntSrc = IntToPtrOp1->getOperand(0);
6234 if (IntSrc->getType() == Op0Src->getType())
6235 NewOp1 = IntToPtrOp1->getOperand(0);
6236 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
6237 NewOp1 = ConstantFoldConstant(ConstantExpr::getPtrToInt(RHSC, SrcTy), DL);
6240 if (NewOp1)
6241 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6244 if (Instruction *R = foldICmpWithTrunc(ICmp))
6245 return R;
6247 return foldICmpWithZextOrSext(ICmp);
6250 static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS,
6251 bool IsSigned) {
6252 switch (BinaryOp) {
6253 default:
6254 llvm_unreachable("Unsupported binary op");
6255 case Instruction::Add:
6256 case Instruction::Sub:
6257 return match(RHS, m_Zero());
6258 case Instruction::Mul:
6259 return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
6260 match(RHS, m_One());
6264 OverflowResult
6265 InstCombinerImpl::computeOverflow(Instruction::BinaryOps BinaryOp,
6266 bool IsSigned, Value *LHS, Value *RHS,
6267 Instruction *CxtI) const {
6268 switch (BinaryOp) {
6269 default:
6270 llvm_unreachable("Unsupported binary op");
6271 case Instruction::Add:
6272 if (IsSigned)
6273 return computeOverflowForSignedAdd(LHS, RHS, CxtI);
6274 else
6275 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
6276 case Instruction::Sub:
6277 if (IsSigned)
6278 return computeOverflowForSignedSub(LHS, RHS, CxtI);
6279 else
6280 return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
6281 case Instruction::Mul:
6282 if (IsSigned)
6283 return computeOverflowForSignedMul(LHS, RHS, CxtI);
6284 else
6285 return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
6289 bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6290 bool IsSigned, Value *LHS,
6291 Value *RHS, Instruction &OrigI,
6292 Value *&Result,
6293 Constant *&Overflow) {
6294 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
6295 std::swap(LHS, RHS);
6297 // If the overflow check was an add followed by a compare, the insertion point
6298 // may be pointing to the compare. We want to insert the new instructions
6299 // before the add in case there are uses of the add between the add and the
6300 // compare.
6301 Builder.SetInsertPoint(&OrigI);
6303 Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
6304 if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
6305 OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
6307 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6308 Result = LHS;
6309 Overflow = ConstantInt::getFalse(OverflowTy);
6310 return true;
6313 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
6314 case OverflowResult::MayOverflow:
6315 return false;
6316 case OverflowResult::AlwaysOverflowsLow:
6317 case OverflowResult::AlwaysOverflowsHigh:
6318 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6319 Result->takeName(&OrigI);
6320 Overflow = ConstantInt::getTrue(OverflowTy);
6321 return true;
6322 case OverflowResult::NeverOverflows:
6323 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6324 Result->takeName(&OrigI);
6325 Overflow = ConstantInt::getFalse(OverflowTy);
6326 if (auto *Inst = dyn_cast<Instruction>(Result)) {
6327 if (IsSigned)
6328 Inst->setHasNoSignedWrap();
6329 else
6330 Inst->setHasNoUnsignedWrap();
6332 return true;
6335 llvm_unreachable("Unexpected overflow result");
6338 /// Recognize and process idiom involving test for multiplication
6339 /// overflow.
6341 /// The caller has matched a pattern of the form:
6342 /// I = cmp u (mul(zext A, zext B), V
6343 /// The function checks if this is a test for overflow and if so replaces
6344 /// multiplication with call to 'mul.with.overflow' intrinsic.
6346 /// \param I Compare instruction.
6347 /// \param MulVal Result of 'mult' instruction. It is one of the arguments of
6348 /// the compare instruction. Must be of integer type.
6349 /// \param OtherVal The other argument of compare instruction.
6350 /// \returns Instruction which must replace the compare instruction, NULL if no
6351 /// replacement required.
6352 static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,
6353 const APInt *OtherVal,
6354 InstCombinerImpl &IC) {
6355 // Don't bother doing this transformation for pointers, don't do it for
6356 // vectors.
6357 if (!isa<IntegerType>(MulVal->getType()))
6358 return nullptr;
6360 auto *MulInstr = dyn_cast<Instruction>(MulVal);
6361 if (!MulInstr)
6362 return nullptr;
6363 assert(MulInstr->getOpcode() == Instruction::Mul);
6365 auto *LHS = cast<ZExtInst>(MulInstr->getOperand(0)),
6366 *RHS = cast<ZExtInst>(MulInstr->getOperand(1));
6367 assert(LHS->getOpcode() == Instruction::ZExt);
6368 assert(RHS->getOpcode() == Instruction::ZExt);
6369 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
6371 // Calculate type and width of the result produced by mul.with.overflow.
6372 Type *TyA = A->getType(), *TyB = B->getType();
6373 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6374 WidthB = TyB->getPrimitiveSizeInBits();
6375 unsigned MulWidth;
6376 Type *MulType;
6377 if (WidthB > WidthA) {
6378 MulWidth = WidthB;
6379 MulType = TyB;
6380 } else {
6381 MulWidth = WidthA;
6382 MulType = TyA;
6385 // In order to replace the original mul with a narrower mul.with.overflow,
6386 // all uses must ignore upper bits of the product. The number of used low
6387 // bits must be not greater than the width of mul.with.overflow.
6388 if (MulVal->hasNUsesOrMore(2))
6389 for (User *U : MulVal->users()) {
6390 if (U == &I)
6391 continue;
6392 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6393 // Check if truncation ignores bits above MulWidth.
6394 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
6395 if (TruncWidth > MulWidth)
6396 return nullptr;
6397 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6398 // Check if AND ignores bits above MulWidth.
6399 if (BO->getOpcode() != Instruction::And)
6400 return nullptr;
6401 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6402 const APInt &CVal = CI->getValue();
6403 if (CVal.getBitWidth() - CVal.countl_zero() > MulWidth)
6404 return nullptr;
6405 } else {
6406 // In this case we could have the operand of the binary operation
6407 // being defined in another block, and performing the replacement
6408 // could break the dominance relation.
6409 return nullptr;
6411 } else {
6412 // Other uses prohibit this transformation.
6413 return nullptr;
6417 // Recognize patterns
6418 switch (I.getPredicate()) {
6419 case ICmpInst::ICMP_UGT: {
6420 // Recognize pattern:
6421 // mulval = mul(zext A, zext B)
6422 // cmp ugt mulval, max
6423 APInt MaxVal = APInt::getMaxValue(MulWidth);
6424 MaxVal = MaxVal.zext(OtherVal->getBitWidth());
6425 if (MaxVal.eq(*OtherVal))
6426 break; // Recognized
6427 return nullptr;
6430 case ICmpInst::ICMP_ULT: {
6431 // Recognize pattern:
6432 // mulval = mul(zext A, zext B)
6433 // cmp ule mulval, max + 1
6434 APInt MaxVal = APInt::getOneBitSet(OtherVal->getBitWidth(), MulWidth);
6435 if (MaxVal.eq(*OtherVal))
6436 break; // Recognized
6437 return nullptr;
6440 default:
6441 return nullptr;
6444 InstCombiner::BuilderTy &Builder = IC.Builder;
6445 Builder.SetInsertPoint(MulInstr);
6447 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
6448 Value *MulA = A, *MulB = B;
6449 if (WidthA < MulWidth)
6450 MulA = Builder.CreateZExt(A, MulType);
6451 if (WidthB < MulWidth)
6452 MulB = Builder.CreateZExt(B, MulType);
6453 CallInst *Call =
6454 Builder.CreateIntrinsic(Intrinsic::umul_with_overflow, MulType,
6455 {MulA, MulB}, /*FMFSource=*/nullptr, "umul");
6456 IC.addToWorklist(MulInstr);
6458 // If there are uses of mul result other than the comparison, we know that
6459 // they are truncation or binary AND. Change them to use result of
6460 // mul.with.overflow and adjust properly mask/size.
6461 if (MulVal->hasNUsesOrMore(2)) {
6462 Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value");
6463 for (User *U : make_early_inc_range(MulVal->users())) {
6464 if (U == &I)
6465 continue;
6466 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6467 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
6468 IC.replaceInstUsesWith(*TI, Mul);
6469 else
6470 TI->setOperand(0, Mul);
6471 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6472 assert(BO->getOpcode() == Instruction::And);
6473 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
6474 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
6475 APInt ShortMask = CI->getValue().trunc(MulWidth);
6476 Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask);
6477 Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
6478 IC.replaceInstUsesWith(*BO, Zext);
6479 } else {
6480 llvm_unreachable("Unexpected Binary operation");
6482 IC.addToWorklist(cast<Instruction>(U));
6486 // The original icmp gets replaced with the overflow value, maybe inverted
6487 // depending on predicate.
6488 if (I.getPredicate() == ICmpInst::ICMP_ULT) {
6489 Value *Res = Builder.CreateExtractValue(Call, 1);
6490 return BinaryOperator::CreateNot(Res);
6493 return ExtractValueInst::Create(Call, 1);
6496 /// When performing a comparison against a constant, it is possible that not all
6497 /// the bits in the LHS are demanded. This helper method computes the mask that
6498 /// IS demanded.
6499 static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) {
6500 const APInt *RHS;
6501 if (!match(I.getOperand(1), m_APInt(RHS)))
6502 return APInt::getAllOnes(BitWidth);
6504 // If this is a normal comparison, it demands all bits. If it is a sign bit
6505 // comparison, it only demands the sign bit.
6506 bool UnusedBit;
6507 if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
6508 return APInt::getSignMask(BitWidth);
6510 switch (I.getPredicate()) {
6511 // For a UGT comparison, we don't care about any bits that
6512 // correspond to the trailing ones of the comparand. The value of these
6513 // bits doesn't impact the outcome of the comparison, because any value
6514 // greater than the RHS must differ in a bit higher than these due to carry.
6515 case ICmpInst::ICMP_UGT:
6516 return APInt::getBitsSetFrom(BitWidth, RHS->countr_one());
6518 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
6519 // Any value less than the RHS must differ in a higher bit because of carries.
6520 case ICmpInst::ICMP_ULT:
6521 return APInt::getBitsSetFrom(BitWidth, RHS->countr_zero());
6523 default:
6524 return APInt::getAllOnes(BitWidth);
6528 /// Check that one use is in the same block as the definition and all
6529 /// other uses are in blocks dominated by a given block.
6531 /// \param DI Definition
6532 /// \param UI Use
6533 /// \param DB Block that must dominate all uses of \p DI outside
6534 /// the parent block
6535 /// \return true when \p UI is the only use of \p DI in the parent block
6536 /// and all other uses of \p DI are in blocks dominated by \p DB.
6538 bool InstCombinerImpl::dominatesAllUses(const Instruction *DI,
6539 const Instruction *UI,
6540 const BasicBlock *DB) const {
6541 assert(DI && UI && "Instruction not defined\n");
6542 // Ignore incomplete definitions.
6543 if (!DI->getParent())
6544 return false;
6545 // DI and UI must be in the same block.
6546 if (DI->getParent() != UI->getParent())
6547 return false;
6548 // Protect from self-referencing blocks.
6549 if (DI->getParent() == DB)
6550 return false;
6551 for (const User *U : DI->users()) {
6552 auto *Usr = cast<Instruction>(U);
6553 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
6554 return false;
6556 return true;
6559 /// Return true when the instruction sequence within a block is select-cmp-br.
6560 static bool isChainSelectCmpBranch(const SelectInst *SI) {
6561 const BasicBlock *BB = SI->getParent();
6562 if (!BB)
6563 return false;
6564 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
6565 if (!BI || BI->getNumSuccessors() != 2)
6566 return false;
6567 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
6568 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
6569 return false;
6570 return true;
6573 /// True when a select result is replaced by one of its operands
6574 /// in select-icmp sequence. This will eventually result in the elimination
6575 /// of the select.
6577 /// \param SI Select instruction
6578 /// \param Icmp Compare instruction
6579 /// \param SIOpd Operand that replaces the select
6581 /// Notes:
6582 /// - The replacement is global and requires dominator information
6583 /// - The caller is responsible for the actual replacement
6585 /// Example:
6587 /// entry:
6588 /// %4 = select i1 %3, %C* %0, %C* null
6589 /// %5 = icmp eq %C* %4, null
6590 /// br i1 %5, label %9, label %7
6591 /// ...
6592 /// ; <label>:7 ; preds = %entry
6593 /// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
6594 /// ...
6596 /// can be transformed to
6598 /// %5 = icmp eq %C* %0, null
6599 /// %6 = select i1 %3, i1 %5, i1 true
6600 /// br i1 %6, label %9, label %7
6601 /// ...
6602 /// ; <label>:7 ; preds = %entry
6603 /// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
6605 /// Similar when the first operand of the select is a constant or/and
6606 /// the compare is for not equal rather than equal.
6608 /// NOTE: The function is only called when the select and compare constants
6609 /// are equal, the optimization can work only for EQ predicates. This is not a
6610 /// major restriction since a NE compare should be 'normalized' to an equal
6611 /// compare, which usually happens in the combiner and test case
6612 /// select-cmp-br.ll checks for it.
6613 bool InstCombinerImpl::replacedSelectWithOperand(SelectInst *SI,
6614 const ICmpInst *Icmp,
6615 const unsigned SIOpd) {
6616 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
6617 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
6618 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
6619 // The check for the single predecessor is not the best that can be
6620 // done. But it protects efficiently against cases like when SI's
6621 // home block has two successors, Succ and Succ1, and Succ1 predecessor
6622 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
6623 // replaced can be reached on either path. So the uniqueness check
6624 // guarantees that the path all uses of SI (outside SI's parent) are on
6625 // is disjoint from all other paths out of SI. But that information
6626 // is more expensive to compute, and the trade-off here is in favor
6627 // of compile-time. It should also be noticed that we check for a single
6628 // predecessor and not only uniqueness. This to handle the situation when
6629 // Succ and Succ1 points to the same basic block.
6630 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
6631 NumSel++;
6632 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
6633 return true;
6636 return false;
6639 /// Try to fold the comparison based on range information we can get by checking
6640 /// whether bits are known to be zero or one in the inputs.
6641 Instruction *InstCombinerImpl::foldICmpUsingKnownBits(ICmpInst &I) {
6642 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6643 Type *Ty = Op0->getType();
6644 ICmpInst::Predicate Pred = I.getPredicate();
6646 // Get scalar or pointer size.
6647 unsigned BitWidth = Ty->isIntOrIntVectorTy()
6648 ? Ty->getScalarSizeInBits()
6649 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
6651 if (!BitWidth)
6652 return nullptr;
6654 KnownBits Op0Known(BitWidth);
6655 KnownBits Op1Known(BitWidth);
6658 // Don't use dominating conditions when folding icmp using known bits. This
6659 // may convert signed into unsigned predicates in ways that other passes
6660 // (especially IndVarSimplify) may not be able to reliably undo.
6661 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(&I);
6662 if (SimplifyDemandedBits(&I, 0, getDemandedBitsLHSMask(I, BitWidth),
6663 Op0Known, /*Depth=*/0, Q))
6664 return &I;
6666 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known,
6667 /*Depth=*/0, Q))
6668 return &I;
6671 if (!isa<Constant>(Op0) && Op0Known.isConstant())
6672 return new ICmpInst(
6673 Pred, ConstantExpr::getIntegerValue(Ty, Op0Known.getConstant()), Op1);
6674 if (!isa<Constant>(Op1) && Op1Known.isConstant())
6675 return new ICmpInst(
6676 Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Known.getConstant()));
6678 if (std::optional<bool> Res = ICmpInst::compare(Op0Known, Op1Known, Pred))
6679 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *Res));
6681 // Given the known and unknown bits, compute a range that the LHS could be
6682 // in. Compute the Min, Max and RHS values based on the known bits. For the
6683 // EQ and NE we use unsigned values.
6684 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6685 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6686 if (I.isSigned()) {
6687 Op0Min = Op0Known.getSignedMinValue();
6688 Op0Max = Op0Known.getSignedMaxValue();
6689 Op1Min = Op1Known.getSignedMinValue();
6690 Op1Max = Op1Known.getSignedMaxValue();
6691 } else {
6692 Op0Min = Op0Known.getMinValue();
6693 Op0Max = Op0Known.getMaxValue();
6694 Op1Min = Op1Known.getMinValue();
6695 Op1Max = Op1Known.getMaxValue();
6698 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
6699 // min/max canonical compare with some other compare. That could lead to
6700 // conflict with select canonicalization and infinite looping.
6701 // FIXME: This constraint may go away if min/max intrinsics are canonical.
6702 auto isMinMaxCmp = [&](Instruction &Cmp) {
6703 if (!Cmp.hasOneUse())
6704 return false;
6705 Value *A, *B;
6706 SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
6707 if (!SelectPatternResult::isMinOrMax(SPF))
6708 return false;
6709 return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
6710 match(Op1, m_MaxOrMin(m_Value(), m_Value()));
6712 if (!isMinMaxCmp(I)) {
6713 switch (Pred) {
6714 default:
6715 break;
6716 case ICmpInst::ICMP_ULT: {
6717 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6718 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6719 const APInt *CmpC;
6720 if (match(Op1, m_APInt(CmpC))) {
6721 // A <u C -> A == C-1 if min(A)+1 == C
6722 if (*CmpC == Op0Min + 1)
6723 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6724 ConstantInt::get(Op1->getType(), *CmpC - 1));
6725 // X <u C --> X == 0, if the number of zero bits in the bottom of X
6726 // exceeds the log2 of C.
6727 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
6728 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6729 Constant::getNullValue(Op1->getType()));
6731 break;
6733 case ICmpInst::ICMP_UGT: {
6734 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6735 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6736 const APInt *CmpC;
6737 if (match(Op1, m_APInt(CmpC))) {
6738 // A >u C -> A == C+1 if max(a)-1 == C
6739 if (*CmpC == Op0Max - 1)
6740 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6741 ConstantInt::get(Op1->getType(), *CmpC + 1));
6742 // X >u C --> X != 0, if the number of zero bits in the bottom of X
6743 // exceeds the log2 of C.
6744 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
6745 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
6746 Constant::getNullValue(Op1->getType()));
6748 break;
6750 case ICmpInst::ICMP_SLT: {
6751 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6752 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6753 const APInt *CmpC;
6754 if (match(Op1, m_APInt(CmpC))) {
6755 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
6756 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6757 ConstantInt::get(Op1->getType(), *CmpC - 1));
6759 break;
6761 case ICmpInst::ICMP_SGT: {
6762 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6763 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6764 const APInt *CmpC;
6765 if (match(Op1, m_APInt(CmpC))) {
6766 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
6767 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6768 ConstantInt::get(Op1->getType(), *CmpC + 1));
6770 break;
6775 // Based on the range information we know about the LHS, see if we can
6776 // simplify this comparison. For example, (x&4) < 8 is always true.
6777 switch (Pred) {
6778 default:
6779 break;
6780 case ICmpInst::ICMP_EQ:
6781 case ICmpInst::ICMP_NE: {
6782 // If all bits are known zero except for one, then we know at most one bit
6783 // is set. If the comparison is against zero, then this is a check to see if
6784 // *that* bit is set.
6785 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
6786 if (Op1Known.isZero()) {
6787 // If the LHS is an AND with the same constant, look through it.
6788 Value *LHS = nullptr;
6789 const APInt *LHSC;
6790 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
6791 *LHSC != Op0KnownZeroInverted)
6792 LHS = Op0;
6794 Value *X;
6795 const APInt *C1;
6796 if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
6797 Type *XTy = X->getType();
6798 unsigned Log2C1 = C1->countr_zero();
6799 APInt C2 = Op0KnownZeroInverted;
6800 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
6801 if (C2Pow2.isPowerOf2()) {
6802 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
6803 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
6804 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
6805 unsigned Log2C2 = C2Pow2.countr_zero();
6806 auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
6807 auto NewPred =
6808 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
6809 return new ICmpInst(NewPred, X, CmpC);
6814 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
6815 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
6816 (Op0Known & Op1Known) == Op0Known)
6817 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
6818 ConstantInt::getNullValue(Op1->getType()));
6819 break;
6821 case ICmpInst::ICMP_SGE:
6822 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
6823 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6824 break;
6825 case ICmpInst::ICMP_SLE:
6826 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
6827 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6828 break;
6829 case ICmpInst::ICMP_UGE:
6830 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
6831 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6832 break;
6833 case ICmpInst::ICMP_ULE:
6834 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
6835 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6836 break;
6839 // Turn a signed comparison into an unsigned one if both operands are known to
6840 // have the same sign. Set samesign if possible (except for equality
6841 // predicates).
6842 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
6843 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
6844 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
6845 I.setPredicate(I.getUnsignedPredicate());
6846 I.setSameSign();
6847 return &I;
6850 return nullptr;
6853 /// If one operand of an icmp is effectively a bool (value range of {0,1}),
6854 /// then try to reduce patterns based on that limit.
6855 Instruction *InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst &I) {
6856 Value *X, *Y;
6857 CmpPredicate Pred;
6859 // X must be 0 and bool must be true for "ULT":
6860 // X <u (zext i1 Y) --> (X == 0) & Y
6861 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
6862 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
6863 return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
6865 // X must be 0 or bool must be true for "ULE":
6866 // X <=u (sext i1 Y) --> (X == 0) | Y
6867 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
6868 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
6869 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
6871 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
6872 CmpPredicate Pred1, Pred2;
6873 const APInt *C;
6874 Instruction *ExtI;
6875 if (match(&I, m_c_ICmp(Pred1, m_Value(X),
6876 m_CombineAnd(m_Instruction(ExtI),
6877 m_ZExtOrSExt(m_ICmp(Pred2, m_Deferred(X),
6878 m_APInt(C)))))) &&
6879 ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
6880 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
6881 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(0)->hasOneUse();
6882 auto CreateRangeCheck = [&] {
6883 Value *CmpV1 =
6884 Builder.CreateICmp(Pred1, X, Constant::getNullValue(X->getType()));
6885 Value *CmpV2 = Builder.CreateICmp(
6886 Pred1, X, ConstantInt::getSigned(X->getType(), IsSExt ? -1 : 1));
6887 return BinaryOperator::Create(
6888 Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
6889 CmpV1, CmpV2);
6891 if (C->isZero()) {
6892 if (Pred2 == ICmpInst::ICMP_EQ) {
6893 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
6894 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
6895 return replaceInstUsesWith(
6896 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
6897 } else if (!IsSExt || HasOneUse) {
6898 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
6899 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
6900 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
6901 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X == -1
6902 return CreateRangeCheck();
6904 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
6905 if (Pred2 == ICmpInst::ICMP_NE) {
6906 // icmp eq X, (zext (icmp ne X, 1)) --> false
6907 // icmp ne X, (zext (icmp ne X, 1)) --> true
6908 // icmp eq X, (sext (icmp ne X, -1)) --> false
6909 // icmp ne X, (sext (icmp ne X, -1)) --> true
6910 return replaceInstUsesWith(
6911 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
6912 } else if (!IsSExt || HasOneUse) {
6913 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
6914 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
6915 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
6916 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
6917 return CreateRangeCheck();
6919 } else {
6920 // when C != 0 && C != 1:
6921 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
6922 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
6923 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
6924 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
6925 // when C != 0 && C != -1:
6926 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
6927 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
6928 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
6929 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
6930 return ICmpInst::Create(
6931 Instruction::ICmp, Pred1, X,
6932 ConstantInt::getSigned(X->getType(), Pred2 == ICmpInst::ICMP_NE
6933 ? (IsSExt ? -1 : 1)
6934 : 0));
6938 return nullptr;
6941 /// If we have an icmp le or icmp ge instruction with a constant operand, turn
6942 /// it into the appropriate icmp lt or icmp gt instruction. This transform
6943 /// allows them to be folded in visitICmpInst.
6944 static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
6945 ICmpInst::Predicate Pred = I.getPredicate();
6946 if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
6947 InstCombiner::isCanonicalPredicate(Pred))
6948 return nullptr;
6950 Value *Op0 = I.getOperand(0);
6951 Value *Op1 = I.getOperand(1);
6952 auto *Op1C = dyn_cast<Constant>(Op1);
6953 if (!Op1C)
6954 return nullptr;
6956 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
6957 if (!FlippedStrictness)
6958 return nullptr;
6960 return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
6963 /// If we have a comparison with a non-canonical predicate, if we can update
6964 /// all the users, invert the predicate and adjust all the users.
6965 CmpInst *InstCombinerImpl::canonicalizeICmpPredicate(CmpInst &I) {
6966 // Is the predicate already canonical?
6967 CmpInst::Predicate Pred = I.getPredicate();
6968 if (InstCombiner::isCanonicalPredicate(Pred))
6969 return nullptr;
6971 // Can all users be adjusted to predicate inversion?
6972 if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
6973 return nullptr;
6975 // Ok, we can canonicalize comparison!
6976 // Let's first invert the comparison's predicate.
6977 I.setPredicate(CmpInst::getInversePredicate(Pred));
6978 I.setName(I.getName() + ".not");
6980 // And, adapt users.
6981 freelyInvertAllUsersOf(&I);
6983 return &I;
6986 /// Integer compare with boolean values can always be turned into bitwise ops.
6987 static Instruction *canonicalizeICmpBool(ICmpInst &I,
6988 InstCombiner::BuilderTy &Builder) {
6989 Value *A = I.getOperand(0), *B = I.getOperand(1);
6990 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
6992 // A boolean compared to true/false can be simplified to Op0/true/false in
6993 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
6994 // Cases not handled by InstSimplify are always 'not' of Op0.
6995 if (match(B, m_Zero())) {
6996 switch (I.getPredicate()) {
6997 case CmpInst::ICMP_EQ: // A == 0 -> !A
6998 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
6999 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7000 return BinaryOperator::CreateNot(A);
7001 default:
7002 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7004 } else if (match(B, m_One())) {
7005 switch (I.getPredicate()) {
7006 case CmpInst::ICMP_NE: // A != 1 -> !A
7007 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7008 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7009 return BinaryOperator::CreateNot(A);
7010 default:
7011 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7015 switch (I.getPredicate()) {
7016 default:
7017 llvm_unreachable("Invalid icmp instruction!");
7018 case ICmpInst::ICMP_EQ:
7019 // icmp eq i1 A, B -> ~(A ^ B)
7020 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
7022 case ICmpInst::ICMP_NE:
7023 // icmp ne i1 A, B -> A ^ B
7024 return BinaryOperator::CreateXor(A, B);
7026 case ICmpInst::ICMP_UGT:
7027 // icmp ugt -> icmp ult
7028 std::swap(A, B);
7029 [[fallthrough]];
7030 case ICmpInst::ICMP_ULT:
7031 // icmp ult i1 A, B -> ~A & B
7032 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
7034 case ICmpInst::ICMP_SGT:
7035 // icmp sgt -> icmp slt
7036 std::swap(A, B);
7037 [[fallthrough]];
7038 case ICmpInst::ICMP_SLT:
7039 // icmp slt i1 A, B -> A & ~B
7040 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
7042 case ICmpInst::ICMP_UGE:
7043 // icmp uge -> icmp ule
7044 std::swap(A, B);
7045 [[fallthrough]];
7046 case ICmpInst::ICMP_ULE:
7047 // icmp ule i1 A, B -> ~A | B
7048 return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
7050 case ICmpInst::ICMP_SGE:
7051 // icmp sge -> icmp sle
7052 std::swap(A, B);
7053 [[fallthrough]];
7054 case ICmpInst::ICMP_SLE:
7055 // icmp sle i1 A, B -> A | ~B
7056 return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
7060 // Transform pattern like:
7061 // (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7062 // (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7063 // Into:
7064 // (X l>> Y) != 0
7065 // (X l>> Y) == 0
7066 static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp,
7067 InstCombiner::BuilderTy &Builder) {
7068 CmpPredicate Pred, NewPred;
7069 Value *X, *Y;
7070 if (match(&Cmp,
7071 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
7072 switch (Pred) {
7073 case ICmpInst::ICMP_ULE:
7074 NewPred = ICmpInst::ICMP_NE;
7075 break;
7076 case ICmpInst::ICMP_UGT:
7077 NewPred = ICmpInst::ICMP_EQ;
7078 break;
7079 default:
7080 return nullptr;
7082 } else if (match(&Cmp, m_c_ICmp(Pred,
7083 m_OneUse(m_CombineOr(
7084 m_Not(m_Shl(m_AllOnes(), m_Value(Y))),
7085 m_Add(m_Shl(m_One(), m_Value(Y)),
7086 m_AllOnes()))),
7087 m_Value(X)))) {
7088 // The variant with 'add' is not canonical, (the variant with 'not' is)
7089 // we only get it because it has extra uses, and can't be canonicalized,
7091 switch (Pred) {
7092 case ICmpInst::ICMP_ULT:
7093 NewPred = ICmpInst::ICMP_NE;
7094 break;
7095 case ICmpInst::ICMP_UGE:
7096 NewPred = ICmpInst::ICMP_EQ;
7097 break;
7098 default:
7099 return nullptr;
7101 } else
7102 return nullptr;
7104 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
7105 Constant *Zero = Constant::getNullValue(NewX->getType());
7106 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
7109 static Instruction *foldVectorCmp(CmpInst &Cmp,
7110 InstCombiner::BuilderTy &Builder) {
7111 const CmpInst::Predicate Pred = Cmp.getPredicate();
7112 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
7113 Value *V1, *V2;
7115 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7116 Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
7117 if (auto *I = dyn_cast<Instruction>(V))
7118 I->copyIRFlags(&Cmp);
7119 Module *M = Cmp.getModule();
7120 Function *F = Intrinsic::getOrInsertDeclaration(
7121 M, Intrinsic::vector_reverse, V->getType());
7122 return CallInst::Create(F, V);
7125 if (match(LHS, m_VecReverse(m_Value(V1)))) {
7126 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7127 if (match(RHS, m_VecReverse(m_Value(V2))) &&
7128 (LHS->hasOneUse() || RHS->hasOneUse()))
7129 return createCmpReverse(Pred, V1, V2);
7131 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7132 if (LHS->hasOneUse() && isSplatValue(RHS))
7133 return createCmpReverse(Pred, V1, RHS);
7135 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7136 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
7137 return createCmpReverse(Pred, LHS, V2);
7139 ArrayRef<int> M;
7140 if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
7141 return nullptr;
7143 // If both arguments of the cmp are shuffles that use the same mask and
7144 // shuffle within a single vector, move the shuffle after the cmp:
7145 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7146 Type *V1Ty = V1->getType();
7147 if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
7148 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7149 Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
7150 return new ShuffleVectorInst(NewCmp, M);
7153 // Try to canonicalize compare with splatted operand and splat constant.
7154 // TODO: We could generalize this for more than splats. See/use the code in
7155 // InstCombiner::foldVectorBinop().
7156 Constant *C;
7157 if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
7158 return nullptr;
7160 // Length-changing splats are ok, so adjust the constants as needed:
7161 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7162 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7163 int MaskSplatIndex;
7164 if (ScalarC && match(M, m_SplatOrPoisonMask(MaskSplatIndex))) {
7165 // We allow poison in matching, but this transform removes it for safety.
7166 // Demanded elements analysis should be able to recover some/all of that.
7167 C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
7168 ScalarC);
7169 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7170 Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
7171 return new ShuffleVectorInst(NewCmp, NewM);
7174 return nullptr;
7177 // extract(uadd.with.overflow(A, B), 0) ult A
7178 // -> extract(uadd.with.overflow(A, B), 1)
7179 static Instruction *foldICmpOfUAddOv(ICmpInst &I) {
7180 CmpInst::Predicate Pred = I.getPredicate();
7181 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7183 Value *UAddOv;
7184 Value *A, *B;
7185 auto UAddOvResultPat = m_ExtractValue<0>(
7186 m_Intrinsic<Intrinsic::uadd_with_overflow>(m_Value(A), m_Value(B)));
7187 if (match(Op0, UAddOvResultPat) &&
7188 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7189 (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
7190 (match(A, m_One()) || match(B, m_One()))) ||
7191 (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
7192 (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
7193 // extract(uadd.with.overflow(A, B), 0) < A
7194 // extract(uadd.with.overflow(A, 1), 0) == 0
7195 // extract(uadd.with.overflow(A, -1), 0) != -1
7196 UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
7197 else if (match(Op1, UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7198 (Op0 == A || Op0 == B))
7199 // A > extract(uadd.with.overflow(A, B), 0)
7200 UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
7201 else
7202 return nullptr;
7204 return ExtractValueInst::Create(UAddOv, 1);
7207 static Instruction *foldICmpInvariantGroup(ICmpInst &I) {
7208 if (!I.getOperand(0)->getType()->isPointerTy() ||
7209 NullPointerIsDefined(
7210 I.getParent()->getParent(),
7211 I.getOperand(0)->getType()->getPointerAddressSpace())) {
7212 return nullptr;
7214 Instruction *Op;
7215 if (match(I.getOperand(0), m_Instruction(Op)) &&
7216 match(I.getOperand(1), m_Zero()) &&
7217 Op->isLaunderOrStripInvariantGroup()) {
7218 return ICmpInst::Create(Instruction::ICmp, I.getPredicate(),
7219 Op->getOperand(0), I.getOperand(1));
7221 return nullptr;
7224 /// This function folds patterns produced by lowering of reduce idioms, such as
7225 /// llvm.vector.reduce.and which are lowered into instruction chains. This code
7226 /// attempts to generate fewer number of scalar comparisons instead of vector
7227 /// comparisons when possible.
7228 static Instruction *foldReductionIdiom(ICmpInst &I,
7229 InstCombiner::BuilderTy &Builder,
7230 const DataLayout &DL) {
7231 if (I.getType()->isVectorTy())
7232 return nullptr;
7233 CmpPredicate OuterPred, InnerPred;
7234 Value *LHS, *RHS;
7236 // Match lowering of @llvm.vector.reduce.and. Turn
7237 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7238 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7239 /// %res = icmp <pred> i8 %scalar_ne, 0
7241 /// into
7243 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7244 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7245 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7247 /// for <pred> in {ne, eq}.
7248 if (!match(&I, m_ICmp(OuterPred,
7249 m_OneUse(m_BitCast(m_OneUse(
7250 m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
7251 m_Zero())))
7252 return nullptr;
7253 auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
7254 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7255 return nullptr;
7256 unsigned NumBits =
7257 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7258 // TODO: Relax this to "not wider than max legal integer type"?
7259 if (!DL.isLegalInteger(NumBits))
7260 return nullptr;
7262 if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7263 auto *ScalarTy = Builder.getIntNTy(NumBits);
7264 LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
7265 RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
7266 return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
7267 I.getName());
7270 return nullptr;
7273 // This helper will be called with icmp operands in both orders.
7274 Instruction *InstCombinerImpl::foldICmpCommutative(CmpPredicate Pred,
7275 Value *Op0, Value *Op1,
7276 ICmpInst &CxtI) {
7277 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7278 if (auto *GEP = dyn_cast<GEPOperator>(Op0))
7279 if (Instruction *NI = foldGEPICmp(GEP, Op1, Pred, CxtI))
7280 return NI;
7282 if (auto *SI = dyn_cast<SelectInst>(Op0))
7283 if (Instruction *NI = foldSelectICmp(Pred, SI, Op1, CxtI))
7284 return NI;
7286 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op0))
7287 if (Instruction *Res = foldICmpWithMinMax(CxtI, MinMax, Op1, Pred))
7288 return Res;
7291 Value *X;
7292 const APInt *C;
7293 // icmp X+Cst, X
7294 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
7295 return foldICmpAddOpConst(X, *C, Pred);
7298 // abs(X) >= X --> true
7299 // abs(X) u<= X --> true
7300 // abs(X) < X --> false
7301 // abs(X) u> X --> false
7302 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7303 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7304 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7305 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7306 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7307 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7309 Value *X;
7310 Constant *C;
7311 if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X), m_Constant(C))) &&
7312 match(Op1, m_Specific(X))) {
7313 Value *NullValue = Constant::getNullValue(X->getType());
7314 Value *AllOnesValue = Constant::getAllOnesValue(X->getType());
7315 const APInt SMin =
7316 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits());
7317 bool IsIntMinPosion = C->isAllOnesValue();
7318 switch (Pred) {
7319 case CmpInst::ICMP_ULE:
7320 case CmpInst::ICMP_SGE:
7321 return replaceInstUsesWith(CxtI, ConstantInt::getTrue(CxtI.getType()));
7322 case CmpInst::ICMP_UGT:
7323 case CmpInst::ICMP_SLT:
7324 return replaceInstUsesWith(CxtI, ConstantInt::getFalse(CxtI.getType()));
7325 case CmpInst::ICMP_UGE:
7326 case CmpInst::ICMP_SLE:
7327 case CmpInst::ICMP_EQ: {
7328 return replaceInstUsesWith(
7329 CxtI, IsIntMinPosion
7330 ? Builder.CreateICmpSGT(X, AllOnesValue)
7331 : Builder.CreateICmpULT(
7332 X, ConstantInt::get(X->getType(), SMin + 1)));
7334 case CmpInst::ICMP_ULT:
7335 case CmpInst::ICMP_SGT:
7336 case CmpInst::ICMP_NE: {
7337 return replaceInstUsesWith(
7338 CxtI, IsIntMinPosion
7339 ? Builder.CreateICmpSLT(X, NullValue)
7340 : Builder.CreateICmpUGT(
7341 X, ConstantInt::get(X->getType(), SMin)));
7343 default:
7344 llvm_unreachable("Invalid predicate!");
7349 const SimplifyQuery Q = SQ.getWithInstruction(&CxtI);
7350 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, *this))
7351 return replaceInstUsesWith(CxtI, V);
7353 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
7354 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(1); };
7356 if (match(Op0, m_UDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7357 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7358 Constant::getNullValue(Op1->getType()));
7361 if (!ICmpInst::isUnsigned(Pred) &&
7362 match(Op0, m_SDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7363 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7364 Constant::getNullValue(Op1->getType()));
7368 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
7369 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
7371 if (match(Op0, m_LShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7372 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7373 Constant::getNullValue(Op1->getType()));
7376 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
7377 match(Op0, m_AShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7378 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7379 Constant::getNullValue(Op1->getType()));
7383 return nullptr;
7386 Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {
7387 bool Changed = false;
7388 const SimplifyQuery Q = SQ.getWithInstruction(&I);
7389 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7390 unsigned Op0Cplxity = getComplexity(Op0);
7391 unsigned Op1Cplxity = getComplexity(Op1);
7393 /// Orders the operands of the compare so that they are listed from most
7394 /// complex to least complex. This puts constants before unary operators,
7395 /// before binary operators.
7396 if (Op0Cplxity < Op1Cplxity) {
7397 I.swapOperands();
7398 std::swap(Op0, Op1);
7399 Changed = true;
7402 if (Value *V = simplifyICmpInst(I.getCmpPredicate(), Op0, Op1, Q))
7403 return replaceInstUsesWith(I, V);
7405 // Comparing -val or val with non-zero is the same as just comparing val
7406 // ie, abs(val) != 0 -> val != 0
7407 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
7408 Value *Cond, *SelectTrue, *SelectFalse;
7409 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
7410 m_Value(SelectFalse)))) {
7411 if (Value *V = dyn_castNegVal(SelectTrue)) {
7412 if (V == SelectFalse)
7413 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
7414 } else if (Value *V = dyn_castNegVal(SelectFalse)) {
7415 if (V == SelectTrue)
7416 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
7421 if (Op0->getType()->isIntOrIntVectorTy(1))
7422 if (Instruction *Res = canonicalizeICmpBool(I, Builder))
7423 return Res;
7425 if (Instruction *Res = canonicalizeCmpWithConstant(I))
7426 return Res;
7428 if (Instruction *Res = canonicalizeICmpPredicate(I))
7429 return Res;
7431 if (Instruction *Res = foldICmpWithConstant(I))
7432 return Res;
7434 if (Instruction *Res = foldICmpWithDominatingICmp(I))
7435 return Res;
7437 if (Instruction *Res = foldICmpUsingBoolRange(I))
7438 return Res;
7440 if (Instruction *Res = foldICmpUsingKnownBits(I))
7441 return Res;
7443 if (Instruction *Res = foldICmpTruncWithTruncOrExt(I, Q))
7444 return Res;
7446 // Test if the ICmpInst instruction is used exclusively by a select as
7447 // part of a minimum or maximum operation. If so, refrain from doing
7448 // any other folding. This helps out other analyses which understand
7449 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
7450 // and CodeGen. And in this case, at least one of the comparison
7451 // operands has at least one user besides the compare (the select),
7452 // which would often largely negate the benefit of folding anyway.
7454 // Do the same for the other patterns recognized by matchSelectPattern.
7455 if (I.hasOneUse())
7456 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
7457 Value *A, *B;
7458 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
7459 if (SPR.Flavor != SPF_UNKNOWN)
7460 return nullptr;
7463 // Do this after checking for min/max to prevent infinite looping.
7464 if (Instruction *Res = foldICmpWithZero(I))
7465 return Res;
7467 // FIXME: We only do this after checking for min/max to prevent infinite
7468 // looping caused by a reverse canonicalization of these patterns for min/max.
7469 // FIXME: The organization of folds is a mess. These would naturally go into
7470 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
7471 // down here after the min/max restriction.
7472 ICmpInst::Predicate Pred = I.getPredicate();
7473 const APInt *C;
7474 if (match(Op1, m_APInt(C))) {
7475 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
7476 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
7477 Constant *Zero = Constant::getNullValue(Op0->getType());
7478 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
7481 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
7482 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
7483 Constant *AllOnes = Constant::getAllOnesValue(Op0->getType());
7484 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
7488 // The folds in here may rely on wrapping flags and special constants, so
7489 // they can break up min/max idioms in some cases but not seemingly similar
7490 // patterns.
7491 // FIXME: It may be possible to enhance select folding to make this
7492 // unnecessary. It may also be moot if we canonicalize to min/max
7493 // intrinsics.
7494 if (Instruction *Res = foldICmpBinOp(I, Q))
7495 return Res;
7497 if (Instruction *Res = foldICmpInstWithConstant(I))
7498 return Res;
7500 // Try to match comparison as a sign bit test. Intentionally do this after
7501 // foldICmpInstWithConstant() to potentially let other folds to happen first.
7502 if (Instruction *New = foldSignBitTest(I))
7503 return New;
7505 if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
7506 return Res;
7508 if (Instruction *Res = foldICmpCommutative(I.getCmpPredicate(), Op0, Op1, I))
7509 return Res;
7510 if (Instruction *Res =
7511 foldICmpCommutative(I.getSwappedCmpPredicate(), Op1, Op0, I))
7512 return Res;
7514 if (I.isCommutative()) {
7515 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
7516 replaceOperand(I, 0, Pair->first);
7517 replaceOperand(I, 1, Pair->second);
7518 return &I;
7522 // In case of a comparison with two select instructions having the same
7523 // condition, check whether one of the resulting branches can be simplified.
7524 // If so, just compare the other branch and select the appropriate result.
7525 // For example:
7526 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
7527 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
7528 // %cmp2 = icmp slt i32 %tmp2, %tmp1
7529 // The icmp will result false for the false value of selects and the result
7530 // will depend upon the comparison of true values of selects if %cmp is
7531 // true. Thus, transform this into:
7532 // %cmp = icmp slt i32 %y, %z
7533 // %sel = select i1 %cond, i1 %cmp, i1 false
7534 // This handles similar cases to transform.
7536 Value *Cond, *A, *B, *C, *D;
7537 if (match(Op0, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
7538 match(Op1, m_Select(m_Specific(Cond), m_Value(C), m_Value(D))) &&
7539 (Op0->hasOneUse() || Op1->hasOneUse())) {
7540 // Check whether comparison of TrueValues can be simplified
7541 if (Value *Res = simplifyICmpInst(Pred, A, C, SQ)) {
7542 Value *NewICMP = Builder.CreateICmp(Pred, B, D);
7543 return SelectInst::Create(Cond, Res, NewICMP);
7545 // Check whether comparison of FalseValues can be simplified
7546 if (Value *Res = simplifyICmpInst(Pred, B, D, SQ)) {
7547 Value *NewICMP = Builder.CreateICmp(Pred, A, C);
7548 return SelectInst::Create(Cond, NewICMP, Res);
7553 // Try to optimize equality comparisons against alloca-based pointers.
7554 if (Op0->getType()->isPointerTy() && I.isEquality()) {
7555 assert(Op1->getType()->isPointerTy() &&
7556 "Comparing pointer with non-pointer?");
7557 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
7558 if (foldAllocaCmp(Alloca))
7559 return nullptr;
7560 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
7561 if (foldAllocaCmp(Alloca))
7562 return nullptr;
7565 if (Instruction *Res = foldICmpBitCast(I))
7566 return Res;
7568 // TODO: Hoist this above the min/max bailout.
7569 if (Instruction *R = foldICmpWithCastOp(I))
7570 return R;
7573 Value *X, *Y;
7574 // Transform (X & ~Y) == 0 --> (X & Y) != 0
7575 // and (X & ~Y) != 0 --> (X & Y) == 0
7576 // if A is a power of 2.
7577 if (match(Op0, m_And(m_Value(X), m_Not(m_Value(Y)))) &&
7578 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(X, false, 0, &I) &&
7579 I.isEquality())
7580 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(X, Y),
7581 Op1);
7583 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
7584 if (Op0->getType()->isIntOrIntVectorTy()) {
7585 bool ConsumesOp0, ConsumesOp1;
7586 if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
7587 isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
7588 (ConsumesOp0 || ConsumesOp1)) {
7589 Value *InvOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
7590 Value *InvOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
7591 assert(InvOp0 && InvOp1 &&
7592 "Mismatch between isFreeToInvert and getFreelyInverted");
7593 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
7597 Instruction *AddI = nullptr;
7598 if (match(&I, m_UAddWithOverflow(m_Value(X), m_Value(Y),
7599 m_Instruction(AddI))) &&
7600 isa<IntegerType>(X->getType())) {
7601 Value *Result;
7602 Constant *Overflow;
7603 // m_UAddWithOverflow can match patterns that do not include an explicit
7604 // "add" instruction, so check the opcode of the matched op.
7605 if (AddI->getOpcode() == Instruction::Add &&
7606 OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, X, Y, *AddI,
7607 Result, Overflow)) {
7608 replaceInstUsesWith(*AddI, Result);
7609 eraseInstFromFunction(*AddI);
7610 return replaceInstUsesWith(I, Overflow);
7614 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
7615 if (match(Op0, m_NUWMul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) &&
7616 match(Op1, m_APInt(C))) {
7617 if (Instruction *R = processUMulZExtIdiom(I, Op0, C, *this))
7618 return R;
7621 // Signbit test folds
7622 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
7623 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
7624 Instruction *ExtI;
7625 if ((I.isUnsigned() || I.isEquality()) &&
7626 match(Op1,
7627 m_CombineAnd(m_Instruction(ExtI), m_ZExtOrSExt(m_Value(Y)))) &&
7628 Y->getType()->getScalarSizeInBits() == 1 &&
7629 (Op0->hasOneUse() || Op1->hasOneUse())) {
7630 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
7631 Instruction *ShiftI;
7632 if (match(Op0, m_CombineAnd(m_Instruction(ShiftI),
7633 m_Shr(m_Value(X), m_SpecificIntAllowPoison(
7634 OpWidth - 1))))) {
7635 unsigned ExtOpc = ExtI->getOpcode();
7636 unsigned ShiftOpc = ShiftI->getOpcode();
7637 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
7638 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
7639 Value *SLTZero =
7640 Builder.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
7641 Value *Cmp = Builder.CreateICmp(Pred, SLTZero, Y, I.getName());
7642 return replaceInstUsesWith(I, Cmp);
7648 if (Instruction *Res = foldICmpEquality(I))
7649 return Res;
7651 if (Instruction *Res = foldICmpPow2Test(I, Builder))
7652 return Res;
7654 if (Instruction *Res = foldICmpOfUAddOv(I))
7655 return Res;
7657 // The 'cmpxchg' instruction returns an aggregate containing the old value and
7658 // an i1 which indicates whether or not we successfully did the swap.
7660 // Replace comparisons between the old value and the expected value with the
7661 // indicator that 'cmpxchg' returns.
7663 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
7664 // spuriously fail. In those cases, the old value may equal the expected
7665 // value but it is possible for the swap to not occur.
7666 if (I.getPredicate() == ICmpInst::ICMP_EQ)
7667 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
7668 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
7669 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
7670 !ACXI->isWeak())
7671 return ExtractValueInst::Create(ACXI, 1);
7673 if (Instruction *Res = foldICmpWithHighBitMask(I, Builder))
7674 return Res;
7676 if (I.getType()->isVectorTy())
7677 if (Instruction *Res = foldVectorCmp(I, Builder))
7678 return Res;
7680 if (Instruction *Res = foldICmpInvariantGroup(I))
7681 return Res;
7683 if (Instruction *Res = foldReductionIdiom(I, Builder, DL))
7684 return Res;
7687 Value *A;
7688 const APInt *C1, *C2;
7689 ICmpInst::Predicate Pred = I.getPredicate();
7690 if (ICmpInst::isEquality(Pred)) {
7691 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
7692 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
7693 if (match(Op0, m_And(m_SExt(m_Value(A)), m_APInt(C1))) &&
7694 match(Op1, m_APInt(C2))) {
7695 Type *InputTy = A->getType();
7696 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
7697 // c2 must be non-negative at the bitwidth of a.
7698 if (C2->getActiveBits() < InputBitWidth) {
7699 APInt TruncC1 = C1->trunc(InputBitWidth);
7700 // Check if there are 1s in C1 high bits of size InputBitWidth.
7701 if (C1->uge(APInt::getOneBitSet(C1->getBitWidth(), InputBitWidth)))
7702 TruncC1.setBit(InputBitWidth - 1);
7703 Value *AndInst = Builder.CreateAnd(A, TruncC1);
7704 return new ICmpInst(
7705 Pred, AndInst,
7706 ConstantInt::get(InputTy, C2->trunc(InputBitWidth)));
7712 return Changed ? &I : nullptr;
7715 /// Fold fcmp ([us]itofp x, cst) if possible.
7716 Instruction *InstCombinerImpl::foldFCmpIntToFPConst(FCmpInst &I,
7717 Instruction *LHSI,
7718 Constant *RHSC) {
7719 const APFloat *RHS;
7720 if (!match(RHSC, m_APFloat(RHS)))
7721 return nullptr;
7723 // Get the width of the mantissa. We don't want to hack on conversions that
7724 // might lose information from the integer, e.g. "i64 -> float"
7725 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
7726 if (MantissaWidth == -1)
7727 return nullptr; // Unknown.
7729 Type *IntTy = LHSI->getOperand(0)->getType();
7730 unsigned IntWidth = IntTy->getScalarSizeInBits();
7731 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
7733 if (I.isEquality()) {
7734 FCmpInst::Predicate P = I.getPredicate();
7735 bool IsExact = false;
7736 APSInt RHSCvt(IntWidth, LHSUnsigned);
7737 RHS->convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
7739 // If the floating point constant isn't an integer value, we know if we will
7740 // ever compare equal / not equal to it.
7741 if (!IsExact) {
7742 // TODO: Can never be -0.0 and other non-representable values
7743 APFloat RHSRoundInt(*RHS);
7744 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
7745 if (*RHS != RHSRoundInt) {
7746 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
7747 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
7749 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
7750 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
7754 // TODO: If the constant is exactly representable, is it always OK to do
7755 // equality compares as integer?
7758 // Check to see that the input is converted from an integer type that is small
7759 // enough that preserves all bits. TODO: check here for "known" sign bits.
7760 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
7762 // Following test does NOT adjust IntWidth downwards for signed inputs,
7763 // because the most negative value still requires all the mantissa bits
7764 // to distinguish it from one less than that value.
7765 if ((int)IntWidth > MantissaWidth) {
7766 // Conversion would lose accuracy. Check if loss can impact comparison.
7767 int Exp = ilogb(*RHS);
7768 if (Exp == APFloat::IEK_Inf) {
7769 int MaxExponent = ilogb(APFloat::getLargest(RHS->getSemantics()));
7770 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
7771 // Conversion could create infinity.
7772 return nullptr;
7773 } else {
7774 // Note that if RHS is zero or NaN, then Exp is negative
7775 // and first condition is trivially false.
7776 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
7777 // Conversion could affect comparison.
7778 return nullptr;
7782 // Otherwise, we can potentially simplify the comparison. We know that it
7783 // will always come through as an integer value and we know the constant is
7784 // not a NAN (it would have been previously simplified).
7785 assert(!RHS->isNaN() && "NaN comparison not already folded!");
7787 ICmpInst::Predicate Pred;
7788 switch (I.getPredicate()) {
7789 default:
7790 llvm_unreachable("Unexpected predicate!");
7791 case FCmpInst::FCMP_UEQ:
7792 case FCmpInst::FCMP_OEQ:
7793 Pred = ICmpInst::ICMP_EQ;
7794 break;
7795 case FCmpInst::FCMP_UGT:
7796 case FCmpInst::FCMP_OGT:
7797 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
7798 break;
7799 case FCmpInst::FCMP_UGE:
7800 case FCmpInst::FCMP_OGE:
7801 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
7802 break;
7803 case FCmpInst::FCMP_ULT:
7804 case FCmpInst::FCMP_OLT:
7805 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
7806 break;
7807 case FCmpInst::FCMP_ULE:
7808 case FCmpInst::FCMP_OLE:
7809 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
7810 break;
7811 case FCmpInst::FCMP_UNE:
7812 case FCmpInst::FCMP_ONE:
7813 Pred = ICmpInst::ICMP_NE;
7814 break;
7815 case FCmpInst::FCMP_ORD:
7816 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
7817 case FCmpInst::FCMP_UNO:
7818 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
7821 // Now we know that the APFloat is a normal number, zero or inf.
7823 // See if the FP constant is too large for the integer. For example,
7824 // comparing an i8 to 300.0.
7825 if (!LHSUnsigned) {
7826 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
7827 // and large values.
7828 APFloat SMax(RHS->getSemantics());
7829 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
7830 APFloat::rmNearestTiesToEven);
7831 if (SMax < *RHS) { // smax < 13123.0
7832 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
7833 Pred == ICmpInst::ICMP_SLE)
7834 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
7835 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
7837 } else {
7838 // If the RHS value is > UnsignedMax, fold the comparison. This handles
7839 // +INF and large values.
7840 APFloat UMax(RHS->getSemantics());
7841 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
7842 APFloat::rmNearestTiesToEven);
7843 if (UMax < *RHS) { // umax < 13123.0
7844 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
7845 Pred == ICmpInst::ICMP_ULE)
7846 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
7847 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
7851 if (!LHSUnsigned) {
7852 // See if the RHS value is < SignedMin.
7853 APFloat SMin(RHS->getSemantics());
7854 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
7855 APFloat::rmNearestTiesToEven);
7856 if (SMin > *RHS) { // smin > 12312.0
7857 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
7858 Pred == ICmpInst::ICMP_SGE)
7859 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
7860 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
7862 } else {
7863 // See if the RHS value is < UnsignedMin.
7864 APFloat UMin(RHS->getSemantics());
7865 UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
7866 APFloat::rmNearestTiesToEven);
7867 if (UMin > *RHS) { // umin > 12312.0
7868 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
7869 Pred == ICmpInst::ICMP_UGE)
7870 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
7871 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
7875 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
7876 // [0, UMAX], but it may still be fractional. Check whether this is the case
7877 // using the IsExact flag.
7878 // Don't do this for zero, because -0.0 is not fractional.
7879 APSInt RHSInt(IntWidth, LHSUnsigned);
7880 bool IsExact;
7881 RHS->convertToInteger(RHSInt, APFloat::rmTowardZero, &IsExact);
7882 if (!RHS->isZero()) {
7883 if (!IsExact) {
7884 // If we had a comparison against a fractional value, we have to adjust
7885 // the compare predicate and sometimes the value. RHSC is rounded towards
7886 // zero at this point.
7887 switch (Pred) {
7888 default:
7889 llvm_unreachable("Unexpected integer comparison!");
7890 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
7891 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
7892 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
7893 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
7894 case ICmpInst::ICMP_ULE:
7895 // (float)int <= 4.4 --> int <= 4
7896 // (float)int <= -4.4 --> false
7897 if (RHS->isNegative())
7898 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
7899 break;
7900 case ICmpInst::ICMP_SLE:
7901 // (float)int <= 4.4 --> int <= 4
7902 // (float)int <= -4.4 --> int < -4
7903 if (RHS->isNegative())
7904 Pred = ICmpInst::ICMP_SLT;
7905 break;
7906 case ICmpInst::ICMP_ULT:
7907 // (float)int < -4.4 --> false
7908 // (float)int < 4.4 --> int <= 4
7909 if (RHS->isNegative())
7910 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
7911 Pred = ICmpInst::ICMP_ULE;
7912 break;
7913 case ICmpInst::ICMP_SLT:
7914 // (float)int < -4.4 --> int < -4
7915 // (float)int < 4.4 --> int <= 4
7916 if (!RHS->isNegative())
7917 Pred = ICmpInst::ICMP_SLE;
7918 break;
7919 case ICmpInst::ICMP_UGT:
7920 // (float)int > 4.4 --> int > 4
7921 // (float)int > -4.4 --> true
7922 if (RHS->isNegative())
7923 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
7924 break;
7925 case ICmpInst::ICMP_SGT:
7926 // (float)int > 4.4 --> int > 4
7927 // (float)int > -4.4 --> int >= -4
7928 if (RHS->isNegative())
7929 Pred = ICmpInst::ICMP_SGE;
7930 break;
7931 case ICmpInst::ICMP_UGE:
7932 // (float)int >= -4.4 --> true
7933 // (float)int >= 4.4 --> int > 4
7934 if (RHS->isNegative())
7935 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
7936 Pred = ICmpInst::ICMP_UGT;
7937 break;
7938 case ICmpInst::ICMP_SGE:
7939 // (float)int >= -4.4 --> int >= -4
7940 // (float)int >= 4.4 --> int > 4
7941 if (!RHS->isNegative())
7942 Pred = ICmpInst::ICMP_SGT;
7943 break;
7948 // Lower this FP comparison into an appropriate integer version of the
7949 // comparison.
7950 return new ICmpInst(Pred, LHSI->getOperand(0),
7951 ConstantInt::get(LHSI->getOperand(0)->getType(), RHSInt));
7954 /// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
7955 static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI,
7956 Constant *RHSC) {
7957 // When C is not 0.0 and infinities are not allowed:
7958 // (C / X) < 0.0 is a sign-bit test of X
7959 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
7960 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
7962 // Proof:
7963 // Multiply (C / X) < 0.0 by X * X / C.
7964 // - X is non zero, if it is the flag 'ninf' is violated.
7965 // - C defines the sign of X * X * C. Thus it also defines whether to swap
7966 // the predicate. C is also non zero by definition.
7968 // Thus X * X / C is non zero and the transformation is valid. [qed]
7970 FCmpInst::Predicate Pred = I.getPredicate();
7972 // Check that predicates are valid.
7973 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
7974 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
7975 return nullptr;
7977 // Check that RHS operand is zero.
7978 if (!match(RHSC, m_AnyZeroFP()))
7979 return nullptr;
7981 // Check fastmath flags ('ninf').
7982 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
7983 return nullptr;
7985 // Check the properties of the dividend. It must not be zero to avoid a
7986 // division by zero (see Proof).
7987 const APFloat *C;
7988 if (!match(LHSI->getOperand(0), m_APFloat(C)))
7989 return nullptr;
7991 if (C->isZero())
7992 return nullptr;
7994 // Get swapped predicate if necessary.
7995 if (C->isNegative())
7996 Pred = I.getSwappedPredicate();
7998 return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
8001 /// Optimize fabs(X) compared with zero.
8002 static Instruction *foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
8003 Value *X;
8004 if (!match(I.getOperand(0), m_FAbs(m_Value(X))))
8005 return nullptr;
8007 const APFloat *C;
8008 if (!match(I.getOperand(1), m_APFloat(C)))
8009 return nullptr;
8011 if (!C->isPosZero()) {
8012 if (!C->isSmallestNormalized())
8013 return nullptr;
8015 const Function *F = I.getFunction();
8016 DenormalMode Mode = F->getDenormalMode(C->getSemantics());
8017 if (Mode.Input == DenormalMode::PreserveSign ||
8018 Mode.Input == DenormalMode::PositiveZero) {
8020 auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8021 Constant *Zero = ConstantFP::getZero(X->getType());
8022 return new FCmpInst(P, X, Zero, "", I);
8025 switch (I.getPredicate()) {
8026 case FCmpInst::FCMP_OLT:
8027 // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
8028 return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
8029 case FCmpInst::FCMP_UGE:
8030 // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
8031 return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
8032 case FCmpInst::FCMP_OGE:
8033 // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
8034 return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
8035 case FCmpInst::FCMP_ULT:
8036 // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
8037 return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
8038 default:
8039 break;
8043 return nullptr;
8046 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8047 I->setPredicate(P);
8048 return IC.replaceOperand(*I, 0, X);
8051 switch (I.getPredicate()) {
8052 case FCmpInst::FCMP_UGE:
8053 case FCmpInst::FCMP_OLT:
8054 // fabs(X) >= 0.0 --> true
8055 // fabs(X) < 0.0 --> false
8056 llvm_unreachable("fcmp should have simplified");
8058 case FCmpInst::FCMP_OGT:
8059 // fabs(X) > 0.0 --> X != 0.0
8060 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
8062 case FCmpInst::FCMP_UGT:
8063 // fabs(X) u> 0.0 --> X u!= 0.0
8064 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
8066 case FCmpInst::FCMP_OLE:
8067 // fabs(X) <= 0.0 --> X == 0.0
8068 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
8070 case FCmpInst::FCMP_ULE:
8071 // fabs(X) u<= 0.0 --> X u== 0.0
8072 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
8074 case FCmpInst::FCMP_OGE:
8075 // fabs(X) >= 0.0 --> !isnan(X)
8076 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8077 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
8079 case FCmpInst::FCMP_ULT:
8080 // fabs(X) u< 0.0 --> isnan(X)
8081 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8082 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
8084 case FCmpInst::FCMP_OEQ:
8085 case FCmpInst::FCMP_UEQ:
8086 case FCmpInst::FCMP_ONE:
8087 case FCmpInst::FCMP_UNE:
8088 case FCmpInst::FCMP_ORD:
8089 case FCmpInst::FCMP_UNO:
8090 // Look through the fabs() because it doesn't change anything but the sign.
8091 // fabs(X) == 0.0 --> X == 0.0,
8092 // fabs(X) != 0.0 --> X != 0.0
8093 // isnan(fabs(X)) --> isnan(X)
8094 // !isnan(fabs(X) --> !isnan(X)
8095 return replacePredAndOp0(&I, I.getPredicate(), X);
8097 default:
8098 return nullptr;
8102 /// Optimize sqrt(X) compared with zero.
8103 static Instruction *foldSqrtWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
8104 Value *X;
8105 if (!match(I.getOperand(0), m_Sqrt(m_Value(X))))
8106 return nullptr;
8108 if (!match(I.getOperand(1), m_PosZeroFP()))
8109 return nullptr;
8111 auto ReplacePredAndOp0 = [&](FCmpInst::Predicate P) {
8112 I.setPredicate(P);
8113 return IC.replaceOperand(I, 0, X);
8116 // Clear ninf flag if sqrt doesn't have it.
8117 if (!cast<Instruction>(I.getOperand(0))->hasNoInfs())
8118 I.setHasNoInfs(false);
8120 switch (I.getPredicate()) {
8121 case FCmpInst::FCMP_OLT:
8122 case FCmpInst::FCMP_UGE:
8123 // sqrt(X) < 0.0 --> false
8124 // sqrt(X) u>= 0.0 --> true
8125 llvm_unreachable("fcmp should have simplified");
8126 case FCmpInst::FCMP_ULT:
8127 case FCmpInst::FCMP_ULE:
8128 case FCmpInst::FCMP_OGT:
8129 case FCmpInst::FCMP_OGE:
8130 case FCmpInst::FCMP_OEQ:
8131 case FCmpInst::FCMP_UNE:
8132 // sqrt(X) u< 0.0 --> X u< 0.0
8133 // sqrt(X) u<= 0.0 --> X u<= 0.0
8134 // sqrt(X) > 0.0 --> X > 0.0
8135 // sqrt(X) >= 0.0 --> X >= 0.0
8136 // sqrt(X) == 0.0 --> X == 0.0
8137 // sqrt(X) u!= 0.0 --> X u!= 0.0
8138 return IC.replaceOperand(I, 0, X);
8140 case FCmpInst::FCMP_OLE:
8141 // sqrt(X) <= 0.0 --> X == 0.0
8142 return ReplacePredAndOp0(FCmpInst::FCMP_OEQ);
8143 case FCmpInst::FCMP_UGT:
8144 // sqrt(X) u> 0.0 --> X u!= 0.0
8145 return ReplacePredAndOp0(FCmpInst::FCMP_UNE);
8146 case FCmpInst::FCMP_UEQ:
8147 // sqrt(X) u== 0.0 --> X u<= 0.0
8148 return ReplacePredAndOp0(FCmpInst::FCMP_ULE);
8149 case FCmpInst::FCMP_ONE:
8150 // sqrt(X) != 0.0 --> X > 0.0
8151 return ReplacePredAndOp0(FCmpInst::FCMP_OGT);
8152 case FCmpInst::FCMP_ORD:
8153 // !isnan(sqrt(X)) --> X >= 0.0
8154 return ReplacePredAndOp0(FCmpInst::FCMP_OGE);
8155 case FCmpInst::FCMP_UNO:
8156 // isnan(sqrt(X)) --> X u< 0.0
8157 return ReplacePredAndOp0(FCmpInst::FCMP_ULT);
8158 default:
8159 llvm_unreachable("Unexpected predicate!");
8163 static Instruction *foldFCmpFNegCommonOp(FCmpInst &I) {
8164 CmpInst::Predicate Pred = I.getPredicate();
8165 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8167 // Canonicalize fneg as Op1.
8168 if (match(Op0, m_FNeg(m_Value())) && !match(Op1, m_FNeg(m_Value()))) {
8169 std::swap(Op0, Op1);
8170 Pred = I.getSwappedPredicate();
8173 if (!match(Op1, m_FNeg(m_Specific(Op0))))
8174 return nullptr;
8176 // Replace the negated operand with 0.0:
8177 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
8178 Constant *Zero = ConstantFP::getZero(Op0->getType());
8179 return new FCmpInst(Pred, Op0, Zero, "", &I);
8182 static Instruction *foldFCmpFSubIntoFCmp(FCmpInst &I, Instruction *LHSI,
8183 Constant *RHSC, InstCombinerImpl &CI) {
8184 const CmpInst::Predicate Pred = I.getPredicate();
8185 Value *X = LHSI->getOperand(0);
8186 Value *Y = LHSI->getOperand(1);
8187 switch (Pred) {
8188 default:
8189 break;
8190 case FCmpInst::FCMP_UGT:
8191 case FCmpInst::FCMP_ULT:
8192 case FCmpInst::FCMP_UNE:
8193 case FCmpInst::FCMP_OEQ:
8194 case FCmpInst::FCMP_OGE:
8195 case FCmpInst::FCMP_OLE:
8196 // The optimization is not valid if X and Y are infinities of the same
8197 // sign, i.e. the inf - inf = nan case. If the fsub has the ninf or nnan
8198 // flag then we can assume we do not have that case. Otherwise we might be
8199 // able to prove that either X or Y is not infinity.
8200 if (!LHSI->hasNoNaNs() && !LHSI->hasNoInfs() &&
8201 !isKnownNeverInfinity(Y, /*Depth=*/0,
8202 CI.getSimplifyQuery().getWithInstruction(&I)) &&
8203 !isKnownNeverInfinity(X, /*Depth=*/0,
8204 CI.getSimplifyQuery().getWithInstruction(&I)))
8205 break;
8207 [[fallthrough]];
8208 case FCmpInst::FCMP_OGT:
8209 case FCmpInst::FCMP_OLT:
8210 case FCmpInst::FCMP_ONE:
8211 case FCmpInst::FCMP_UEQ:
8212 case FCmpInst::FCMP_UGE:
8213 case FCmpInst::FCMP_ULE:
8214 // fcmp pred (x - y), 0 --> fcmp pred x, y
8215 if (match(RHSC, m_AnyZeroFP()) &&
8216 I.getFunction()->getDenormalMode(
8217 LHSI->getType()->getScalarType()->getFltSemantics()) ==
8218 DenormalMode::getIEEE()) {
8219 CI.replaceOperand(I, 0, X);
8220 CI.replaceOperand(I, 1, Y);
8221 return &I;
8223 break;
8226 return nullptr;
8229 static Instruction *foldFCmpWithFloorAndCeil(FCmpInst &I,
8230 InstCombinerImpl &IC) {
8231 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
8232 Type *OpType = LHS->getType();
8233 CmpInst::Predicate Pred = I.getPredicate();
8235 bool FloorX = match(LHS, m_Intrinsic<Intrinsic::floor>(m_Specific(RHS)));
8236 bool CeilX = match(LHS, m_Intrinsic<Intrinsic::ceil>(m_Specific(RHS)));
8238 if (!FloorX && !CeilX) {
8239 if ((FloorX = match(RHS, m_Intrinsic<Intrinsic::floor>(m_Specific(LHS)))) ||
8240 (CeilX = match(RHS, m_Intrinsic<Intrinsic::ceil>(m_Specific(LHS))))) {
8241 std::swap(LHS, RHS);
8242 Pred = I.getSwappedPredicate();
8246 switch (Pred) {
8247 case FCmpInst::FCMP_OLE:
8248 // fcmp ole floor(x), x => fcmp ord x, 0
8249 if (FloorX)
8250 return new FCmpInst(FCmpInst::FCMP_ORD, RHS, ConstantFP::getZero(OpType),
8251 "", &I);
8252 break;
8253 case FCmpInst::FCMP_OGT:
8254 // fcmp ogt floor(x), x => false
8255 if (FloorX)
8256 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8257 break;
8258 case FCmpInst::FCMP_OGE:
8259 // fcmp oge ceil(x), x => fcmp ord x, 0
8260 if (CeilX)
8261 return new FCmpInst(FCmpInst::FCMP_ORD, RHS, ConstantFP::getZero(OpType),
8262 "", &I);
8263 break;
8264 case FCmpInst::FCMP_OLT:
8265 // fcmp olt ceil(x), x => false
8266 if (CeilX)
8267 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8268 break;
8269 case FCmpInst::FCMP_ULE:
8270 // fcmp ule floor(x), x => true
8271 if (FloorX)
8272 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8273 break;
8274 case FCmpInst::FCMP_UGT:
8275 // fcmp ugt floor(x), x => fcmp uno x, 0
8276 if (FloorX)
8277 return new FCmpInst(FCmpInst::FCMP_UNO, RHS, ConstantFP::getZero(OpType),
8278 "", &I);
8279 break;
8280 case FCmpInst::FCMP_UGE:
8281 // fcmp uge ceil(x), x => true
8282 if (CeilX)
8283 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8284 break;
8285 case FCmpInst::FCMP_ULT:
8286 // fcmp ult ceil(x), x => fcmp uno x, 0
8287 if (CeilX)
8288 return new FCmpInst(FCmpInst::FCMP_UNO, RHS, ConstantFP::getZero(OpType),
8289 "", &I);
8290 break;
8291 default:
8292 break;
8295 return nullptr;
8298 Instruction *InstCombinerImpl::visitFCmpInst(FCmpInst &I) {
8299 bool Changed = false;
8301 /// Orders the operands of the compare so that they are listed from most
8302 /// complex to least complex. This puts constants before unary operators,
8303 /// before binary operators.
8304 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
8305 I.swapOperands();
8306 Changed = true;
8309 const CmpInst::Predicate Pred = I.getPredicate();
8310 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8311 if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
8312 SQ.getWithInstruction(&I)))
8313 return replaceInstUsesWith(I, V);
8315 // Simplify 'fcmp pred X, X'
8316 Type *OpType = Op0->getType();
8317 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
8318 if (Op0 == Op1) {
8319 switch (Pred) {
8320 default:
8321 break;
8322 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
8323 case FCmpInst::FCMP_ULT: // True if unordered or less than
8324 case FCmpInst::FCMP_UGT: // True if unordered or greater than
8325 case FCmpInst::FCMP_UNE: // True if unordered or not equal
8326 // Canonicalize these to be 'fcmp uno %X, 0.0'.
8327 I.setPredicate(FCmpInst::FCMP_UNO);
8328 I.setOperand(1, Constant::getNullValue(OpType));
8329 return &I;
8331 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
8332 case FCmpInst::FCMP_OEQ: // True if ordered and equal
8333 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
8334 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
8335 // Canonicalize these to be 'fcmp ord %X, 0.0'.
8336 I.setPredicate(FCmpInst::FCMP_ORD);
8337 I.setOperand(1, Constant::getNullValue(OpType));
8338 return &I;
8342 if (I.isCommutative()) {
8343 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
8344 replaceOperand(I, 0, Pair->first);
8345 replaceOperand(I, 1, Pair->second);
8346 return &I;
8350 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
8351 // then canonicalize the operand to 0.0.
8352 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
8353 if (!match(Op0, m_PosZeroFP()) &&
8354 isKnownNeverNaN(Op0, 0, getSimplifyQuery().getWithInstruction(&I)))
8355 return replaceOperand(I, 0, ConstantFP::getZero(OpType));
8357 if (!match(Op1, m_PosZeroFP()) &&
8358 isKnownNeverNaN(Op1, 0, getSimplifyQuery().getWithInstruction(&I)))
8359 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
8362 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
8363 Value *X, *Y;
8364 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
8365 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
8367 if (Instruction *R = foldFCmpFNegCommonOp(I))
8368 return R;
8370 // Test if the FCmpInst instruction is used exclusively by a select as
8371 // part of a minimum or maximum operation. If so, refrain from doing
8372 // any other folding. This helps out other analyses which understand
8373 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
8374 // and CodeGen. And in this case, at least one of the comparison
8375 // operands has at least one user besides the compare (the select),
8376 // which would often largely negate the benefit of folding anyway.
8377 if (I.hasOneUse())
8378 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
8379 Value *A, *B;
8380 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
8381 if (SPR.Flavor != SPF_UNKNOWN)
8382 return nullptr;
8385 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
8386 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
8387 if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP()))
8388 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
8390 // Canonicalize:
8391 // fcmp olt X, +inf -> fcmp one X, +inf
8392 // fcmp ole X, +inf -> fcmp ord X, 0
8393 // fcmp ogt X, +inf -> false
8394 // fcmp oge X, +inf -> fcmp oeq X, +inf
8395 // fcmp ult X, +inf -> fcmp une X, +inf
8396 // fcmp ule X, +inf -> true
8397 // fcmp ugt X, +inf -> fcmp uno X, 0
8398 // fcmp uge X, +inf -> fcmp ueq X, +inf
8399 // fcmp olt X, -inf -> false
8400 // fcmp ole X, -inf -> fcmp oeq X, -inf
8401 // fcmp ogt X, -inf -> fcmp one X, -inf
8402 // fcmp oge X, -inf -> fcmp ord X, 0
8403 // fcmp ult X, -inf -> fcmp uno X, 0
8404 // fcmp ule X, -inf -> fcmp ueq X, -inf
8405 // fcmp ugt X, -inf -> fcmp une X, -inf
8406 // fcmp uge X, -inf -> true
8407 const APFloat *C;
8408 if (match(Op1, m_APFloat(C)) && C->isInfinity()) {
8409 switch (C->isNegative() ? FCmpInst::getSwappedPredicate(Pred) : Pred) {
8410 default:
8411 break;
8412 case FCmpInst::FCMP_ORD:
8413 case FCmpInst::FCMP_UNO:
8414 case FCmpInst::FCMP_TRUE:
8415 case FCmpInst::FCMP_FALSE:
8416 case FCmpInst::FCMP_OGT:
8417 case FCmpInst::FCMP_ULE:
8418 llvm_unreachable("Should be simplified by InstSimplify");
8419 case FCmpInst::FCMP_OLT:
8420 return new FCmpInst(FCmpInst::FCMP_ONE, Op0, Op1, "", &I);
8421 case FCmpInst::FCMP_OLE:
8422 return new FCmpInst(FCmpInst::FCMP_ORD, Op0, ConstantFP::getZero(OpType),
8423 "", &I);
8424 case FCmpInst::FCMP_OGE:
8425 return new FCmpInst(FCmpInst::FCMP_OEQ, Op0, Op1, "", &I);
8426 case FCmpInst::FCMP_ULT:
8427 return new FCmpInst(FCmpInst::FCMP_UNE, Op0, Op1, "", &I);
8428 case FCmpInst::FCMP_UGT:
8429 return new FCmpInst(FCmpInst::FCMP_UNO, Op0, ConstantFP::getZero(OpType),
8430 "", &I);
8431 case FCmpInst::FCMP_UGE:
8432 return new FCmpInst(FCmpInst::FCMP_UEQ, Op0, Op1, "", &I);
8436 // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
8437 // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
8438 if (match(Op1, m_PosZeroFP()) &&
8439 match(Op0, m_OneUse(m_ElementWiseBitCast(m_Value(X))))) {
8440 ICmpInst::Predicate IntPred = ICmpInst::BAD_ICMP_PREDICATE;
8441 if (Pred == FCmpInst::FCMP_OEQ)
8442 IntPred = ICmpInst::ICMP_EQ;
8443 else if (Pred == FCmpInst::FCMP_UNE)
8444 IntPred = ICmpInst::ICMP_NE;
8446 if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
8447 Type *IntTy = X->getType();
8448 const APInt &SignMask = ~APInt::getSignMask(IntTy->getScalarSizeInBits());
8449 Value *MaskX = Builder.CreateAnd(X, ConstantInt::get(IntTy, SignMask));
8450 return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(IntTy));
8454 // Handle fcmp with instruction LHS and constant RHS.
8455 Instruction *LHSI;
8456 Constant *RHSC;
8457 if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
8458 switch (LHSI->getOpcode()) {
8459 case Instruction::Select:
8460 // fcmp eq (cond ? x : -x), 0 --> fcmp eq x, 0
8461 if (FCmpInst::isEquality(Pred) && match(RHSC, m_AnyZeroFP()) &&
8462 match(LHSI, m_c_Select(m_FNeg(m_Value(X)), m_Deferred(X))))
8463 return replaceOperand(I, 0, X);
8464 if (Instruction *NV = FoldOpIntoSelect(I, cast<SelectInst>(LHSI)))
8465 return NV;
8466 break;
8467 case Instruction::FSub:
8468 if (LHSI->hasOneUse())
8469 if (Instruction *NV = foldFCmpFSubIntoFCmp(I, LHSI, RHSC, *this))
8470 return NV;
8471 break;
8472 case Instruction::PHI:
8473 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
8474 return NV;
8475 break;
8476 case Instruction::SIToFP:
8477 case Instruction::UIToFP:
8478 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
8479 return NV;
8480 break;
8481 case Instruction::FDiv:
8482 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
8483 return NV;
8484 break;
8485 case Instruction::Load:
8486 if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
8487 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
8488 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(
8489 cast<LoadInst>(LHSI), GEP, GV, I))
8490 return Res;
8491 break;
8495 if (Instruction *R = foldFabsWithFcmpZero(I, *this))
8496 return R;
8498 if (Instruction *R = foldSqrtWithFcmpZero(I, *this))
8499 return R;
8501 if (Instruction *R = foldFCmpWithFloorAndCeil(I, *this))
8502 return R;
8504 if (match(Op0, m_FNeg(m_Value(X)))) {
8505 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
8506 Constant *C;
8507 if (match(Op1, m_Constant(C)))
8508 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
8509 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
8512 // fcmp (fadd X, 0.0), Y --> fcmp X, Y
8513 if (match(Op0, m_FAdd(m_Value(X), m_AnyZeroFP())))
8514 return new FCmpInst(Pred, X, Op1, "", &I);
8516 // fcmp X, (fadd Y, 0.0) --> fcmp X, Y
8517 if (match(Op1, m_FAdd(m_Value(Y), m_AnyZeroFP())))
8518 return new FCmpInst(Pred, Op0, Y, "", &I);
8520 if (match(Op0, m_FPExt(m_Value(X)))) {
8521 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
8522 if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
8523 return new FCmpInst(Pred, X, Y, "", &I);
8525 const APFloat *C;
8526 if (match(Op1, m_APFloat(C))) {
8527 const fltSemantics &FPSem =
8528 X->getType()->getScalarType()->getFltSemantics();
8529 bool Lossy;
8530 APFloat TruncC = *C;
8531 TruncC.convert(FPSem, APFloat::rmNearestTiesToEven, &Lossy);
8533 if (Lossy) {
8534 // X can't possibly equal the higher-precision constant, so reduce any
8535 // equality comparison.
8536 // TODO: Other predicates can be handled via getFCmpCode().
8537 switch (Pred) {
8538 case FCmpInst::FCMP_OEQ:
8539 // X is ordered and equal to an impossible constant --> false
8540 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8541 case FCmpInst::FCMP_ONE:
8542 // X is ordered and not equal to an impossible constant --> ordered
8543 return new FCmpInst(FCmpInst::FCMP_ORD, X,
8544 ConstantFP::getZero(X->getType()));
8545 case FCmpInst::FCMP_UEQ:
8546 // X is unordered or equal to an impossible constant --> unordered
8547 return new FCmpInst(FCmpInst::FCMP_UNO, X,
8548 ConstantFP::getZero(X->getType()));
8549 case FCmpInst::FCMP_UNE:
8550 // X is unordered or not equal to an impossible constant --> true
8551 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8552 default:
8553 break;
8557 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
8558 // Avoid lossy conversions and denormals.
8559 // Zero is a special case that's OK to convert.
8560 APFloat Fabs = TruncC;
8561 Fabs.clearSign();
8562 if (!Lossy &&
8563 (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(FPSem)))) {
8564 Constant *NewC = ConstantFP::get(X->getType(), TruncC);
8565 return new FCmpInst(Pred, X, NewC, "", &I);
8570 // Convert a sign-bit test of an FP value into a cast and integer compare.
8571 // TODO: Simplify if the copysign constant is 0.0 or NaN.
8572 // TODO: Handle non-zero compare constants.
8573 // TODO: Handle other predicates.
8574 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::copysign>(m_APFloat(C),
8575 m_Value(X)))) &&
8576 match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
8577 Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits());
8578 if (auto *VecTy = dyn_cast<VectorType>(OpType))
8579 IntType = VectorType::get(IntType, VecTy->getElementCount());
8581 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
8582 if (Pred == FCmpInst::FCMP_OLT) {
8583 Value *IntX = Builder.CreateBitCast(X, IntType);
8584 return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
8585 ConstantInt::getNullValue(IntType));
8590 Value *CanonLHS = nullptr, *CanonRHS = nullptr;
8591 match(Op0, m_Intrinsic<Intrinsic::canonicalize>(m_Value(CanonLHS)));
8592 match(Op1, m_Intrinsic<Intrinsic::canonicalize>(m_Value(CanonRHS)));
8594 // (canonicalize(x) == x) => (x == x)
8595 if (CanonLHS == Op1)
8596 return new FCmpInst(Pred, Op1, Op1, "", &I);
8598 // (x == canonicalize(x)) => (x == x)
8599 if (CanonRHS == Op0)
8600 return new FCmpInst(Pred, Op0, Op0, "", &I);
8602 // (canonicalize(x) == canonicalize(y)) => (x == y)
8603 if (CanonLHS && CanonRHS)
8604 return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
8607 if (I.getType()->isVectorTy())
8608 if (Instruction *Res = foldVectorCmp(I, Builder))
8609 return Res;
8611 return Changed ? &I : nullptr;