LLVM 23.0.0git
InstCombineCompares.cpp
Go to the documentation of this file.
1//===- InstCombineCompares.cpp --------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visitICmp and visitFCmp functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APSInt.h"
16#include "llvm/ADT/SetVector.h"
17#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/Loads.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/InstrTypes.h"
34#include <bitset>
35
36using namespace llvm;
37using namespace PatternMatch;
38
39#define DEBUG_TYPE "instcombine"
40
41// How many times is a select replaced by one of its operands?
42STATISTIC(NumSel, "Number of select opts");
43
44namespace llvm {
46}
47
48/// Compute Result = In1+In2, returning true if the result overflowed for this
49/// type.
50static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
51 bool IsSigned = false) {
52 bool Overflow;
53 if (IsSigned)
54 Result = In1.sadd_ov(In2, Overflow);
55 else
56 Result = In1.uadd_ov(In2, Overflow);
57
58 return Overflow;
59}
60
61/// Compute Result = In1-In2, returning true if the result overflowed for this
62/// type.
63static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
64 bool IsSigned = false) {
65 bool Overflow;
66 if (IsSigned)
67 Result = In1.ssub_ov(In2, Overflow);
68 else
69 Result = In1.usub_ov(In2, Overflow);
70
71 return Overflow;
72}
73
74/// Given an icmp instruction, return true if any use of this comparison is a
75/// branch on sign bit comparison.
76static bool hasBranchUse(ICmpInst &I) {
77 for (auto *U : I.users())
78 if (isa<BranchInst>(U))
79 return true;
80 return false;
81}
82
83/// Returns true if the exploded icmp can be expressed as a signed comparison
84/// to zero and updates the predicate accordingly.
85/// The signedness of the comparison is preserved.
86/// TODO: Refactor with decomposeBitTestICmp()?
87static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
88 if (!ICmpInst::isSigned(Pred))
89 return false;
90
91 if (C.isZero())
92 return ICmpInst::isRelational(Pred);
93
94 if (C.isOne()) {
95 if (Pred == ICmpInst::ICMP_SLT) {
96 Pred = ICmpInst::ICMP_SLE;
97 return true;
98 }
99 } else if (C.isAllOnes()) {
100 if (Pred == ICmpInst::ICMP_SGT) {
101 Pred = ICmpInst::ICMP_SGE;
102 return true;
103 }
104 }
105
106 return false;
107}
108
109/// This is called when we see this pattern:
110/// cmp pred (load (gep GV, ...)), cmpcst
111/// where GV is a global variable with a constant initializer. Try to simplify
112/// this into some simple computation that does not need the load. For example
113/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
114///
115/// If AndCst is non-null, then the loaded value is masked with that constant
116/// before doing the comparison. This handles cases like "A[i]&4 == 0".
118 LoadInst *LI, GetElementPtrInst *GEP, CmpInst &ICI, ConstantInt *AndCst) {
120 if (LI->isVolatile() || !GV || !GV->isConstant() ||
121 !GV->hasDefinitiveInitializer())
122 return nullptr;
123
124 Type *EltTy = LI->getType();
125 TypeSize EltSize = DL.getTypeStoreSize(EltTy);
126 if (EltSize.isScalable())
127 return nullptr;
128
130 if (!Expr.Index || Expr.BasePtr != GV || Expr.Offset.getBitWidth() > 64)
131 return nullptr;
132
133 Constant *Init = GV->getInitializer();
134 TypeSize GlobalSize = DL.getTypeAllocSize(Init->getType());
135
136 Value *Idx = Expr.Index;
137 const APInt &Stride = Expr.Scale;
138 const APInt &ConstOffset = Expr.Offset;
139
140 // Allow an additional context offset, but only within the stride.
141 if (!ConstOffset.ult(Stride))
142 return nullptr;
143
144 // Don't handle overlapping loads for now.
145 if (!Stride.uge(EltSize.getFixedValue()))
146 return nullptr;
147
148 // Don't blow up on huge arrays.
149 uint64_t ArrayElementCount =
150 divideCeil((GlobalSize.getFixedValue() - ConstOffset.getZExtValue()),
151 Stride.getZExtValue());
152 if (ArrayElementCount > MaxArraySizeForCombine)
153 return nullptr;
154
155 enum { Overdefined = -3, Undefined = -2 };
156
157 // Variables for our state machines.
158
159 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
160 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
161 // and 87 is the second (and last) index. FirstTrueElement is -2 when
162 // undefined, otherwise set to the first true element. SecondTrueElement is
163 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
164 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
165
166 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
167 // form "i != 47 & i != 87". Same state transitions as for true elements.
168 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
169
170 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
171 /// define a state machine that triggers for ranges of values that the index
172 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
173 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
174 /// index in the range (inclusive). We use -2 for undefined here because we
175 /// use relative comparisons and don't want 0-1 to match -1.
176 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
177
178 // MagicBitvector - This is a magic bitvector where we set a bit if the
179 // comparison is true for element 'i'. If there are 64 elements or less in
180 // the array, this will fully represent all the comparison results.
181 uint64_t MagicBitvector = 0;
182
183 // Scan the array and see if one of our patterns matches.
184 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
185 APInt Offset = ConstOffset;
186 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i, Offset += Stride) {
188 if (!Elt)
189 return nullptr;
190
191 // If the element is masked, handle it.
192 if (AndCst) {
193 Elt = ConstantFoldBinaryOpOperands(Instruction::And, Elt, AndCst, DL);
194 if (!Elt)
195 return nullptr;
196 }
197
198 // Find out if the comparison would be true or false for the i'th element.
200 CompareRHS, DL, &TLI);
201 if (!C)
202 return nullptr;
203
204 // If the result is undef for this element, ignore it.
205 if (isa<UndefValue>(C)) {
206 // Extend range state machines to cover this element in case there is an
207 // undef in the middle of the range.
208 if (TrueRangeEnd == (int)i - 1)
209 TrueRangeEnd = i;
210 if (FalseRangeEnd == (int)i - 1)
211 FalseRangeEnd = i;
212 continue;
213 }
214
215 // If we can't compute the result for any of the elements, we have to give
216 // up evaluating the entire conditional.
217 if (!isa<ConstantInt>(C))
218 return nullptr;
219
220 // Otherwise, we know if the comparison is true or false for this element,
221 // update our state machines.
222 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
223
224 // State machine for single/double/range index comparison.
225 if (IsTrueForElt) {
226 // Update the TrueElement state machine.
227 if (FirstTrueElement == Undefined)
228 FirstTrueElement = TrueRangeEnd = i; // First true element.
229 else {
230 // Update double-compare state machine.
231 if (SecondTrueElement == Undefined)
232 SecondTrueElement = i;
233 else
234 SecondTrueElement = Overdefined;
235
236 // Update range state machine.
237 if (TrueRangeEnd == (int)i - 1)
238 TrueRangeEnd = i;
239 else
240 TrueRangeEnd = Overdefined;
241 }
242 } else {
243 // Update the FalseElement state machine.
244 if (FirstFalseElement == Undefined)
245 FirstFalseElement = FalseRangeEnd = i; // First false element.
246 else {
247 // Update double-compare state machine.
248 if (SecondFalseElement == Undefined)
249 SecondFalseElement = i;
250 else
251 SecondFalseElement = Overdefined;
252
253 // Update range state machine.
254 if (FalseRangeEnd == (int)i - 1)
255 FalseRangeEnd = i;
256 else
257 FalseRangeEnd = Overdefined;
258 }
259 }
260
261 // If this element is in range, update our magic bitvector.
262 if (i < 64 && IsTrueForElt)
263 MagicBitvector |= 1ULL << i;
264
265 // If all of our states become overdefined, bail out early. Since the
266 // predicate is expensive, only check it every 8 elements. This is only
267 // really useful for really huge arrays.
268 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
269 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
270 FalseRangeEnd == Overdefined)
271 return nullptr;
272 }
273
274 // Now that we've scanned the entire array, emit our new comparison(s). We
275 // order the state machines in complexity of the generated code.
276
277 // If inbounds keyword is not present, Idx * Stride can overflow.
278 // Let's assume that Stride is 2 and the wanted value is at offset 0.
279 // Then, there are two possible values for Idx to match offset 0:
280 // 0x00..00, 0x80..00.
281 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
282 // comparison is false if Idx was 0x80..00.
283 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
284 auto MaskIdx = [&](Value *Idx) {
285 if (!Expr.Flags.isInBounds() && Stride.countr_zero() != 0) {
287 Mask = Builder.CreateLShr(Mask, Stride.countr_zero());
288 Idx = Builder.CreateAnd(Idx, Mask);
289 }
290 return Idx;
291 };
292
293 // If the comparison is only true for one or two elements, emit direct
294 // comparisons.
295 if (SecondTrueElement != Overdefined) {
296 Idx = MaskIdx(Idx);
297 // None true -> false.
298 if (FirstTrueElement == Undefined)
299 return replaceInstUsesWith(ICI, Builder.getFalse());
300
301 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
302
303 // True for one element -> 'i == 47'.
304 if (SecondTrueElement == Undefined)
305 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
306
307 // True for two elements -> 'i == 47 | i == 72'.
308 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
309 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
310 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
311 return BinaryOperator::CreateOr(C1, C2);
312 }
313
314 // If the comparison is only false for one or two elements, emit direct
315 // comparisons.
316 if (SecondFalseElement != Overdefined) {
317 Idx = MaskIdx(Idx);
318 // None false -> true.
319 if (FirstFalseElement == Undefined)
320 return replaceInstUsesWith(ICI, Builder.getTrue());
321
322 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
323
324 // False for one element -> 'i != 47'.
325 if (SecondFalseElement == Undefined)
326 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
327
328 // False for two elements -> 'i != 47 & i != 72'.
329 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
330 Value *SecondFalseIdx =
331 ConstantInt::get(Idx->getType(), SecondFalseElement);
332 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
333 return BinaryOperator::CreateAnd(C1, C2);
334 }
335
336 // If the comparison can be replaced with a range comparison for the elements
337 // where it is true, emit the range check.
338 if (TrueRangeEnd != Overdefined) {
339 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
340 Idx = MaskIdx(Idx);
341
342 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
343 if (FirstTrueElement) {
344 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstTrueElement);
345 Idx = Builder.CreateAdd(Idx, Offs);
346 }
347
348 Value *End =
349 ConstantInt::get(Idx->getType(), TrueRangeEnd - FirstTrueElement + 1);
350 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
351 }
352
353 // False range check.
354 if (FalseRangeEnd != Overdefined) {
355 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
356 Idx = MaskIdx(Idx);
357 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
358 if (FirstFalseElement) {
359 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstFalseElement);
360 Idx = Builder.CreateAdd(Idx, Offs);
361 }
362
363 Value *End =
364 ConstantInt::get(Idx->getType(), FalseRangeEnd - FirstFalseElement);
365 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
366 }
367
368 // If a magic bitvector captures the entire comparison state
369 // of this load, replace it with computation that does:
370 // ((magic_cst >> i) & 1) != 0
371 {
372 Type *Ty = nullptr;
373
374 // Look for an appropriate type:
375 // - The type of Idx if the magic fits
376 // - The smallest fitting legal type
377 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
378 Ty = Idx->getType();
379 else
380 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
381
382 if (Ty) {
383 Idx = MaskIdx(Idx);
384 Value *V = Builder.CreateIntCast(Idx, Ty, false);
385 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
386 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
387 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
388 }
389 }
390
391 return nullptr;
392}
393
394/// Returns true if we can rewrite Start as a GEP with pointer Base
395/// and some integer offset. The nodes that need to be re-written
396/// for this transformation will be added to Explored.
398 const DataLayout &DL,
399 SetVector<Value *> &Explored) {
400 SmallVector<Value *, 16> WorkList(1, Start);
401 Explored.insert(Base);
402
403 // The following traversal gives us an order which can be used
404 // when doing the final transformation. Since in the final
405 // transformation we create the PHI replacement instructions first,
406 // we don't have to get them in any particular order.
407 //
408 // However, for other instructions we will have to traverse the
409 // operands of an instruction first, which means that we have to
410 // do a post-order traversal.
411 while (!WorkList.empty()) {
413
414 while (!WorkList.empty()) {
415 if (Explored.size() >= 100)
416 return false;
417
418 Value *V = WorkList.back();
419
420 if (Explored.contains(V)) {
421 WorkList.pop_back();
422 continue;
423 }
424
426 // We've found some value that we can't explore which is different from
427 // the base. Therefore we can't do this transformation.
428 return false;
429
430 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
431 // Only allow inbounds GEPs with at most one variable offset.
432 auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(V); };
433 if (!GEP->isInBounds() || count_if(GEP->indices(), IsNonConst) > 1)
434 return false;
435
436 NW = NW.intersectForOffsetAdd(GEP->getNoWrapFlags());
437 if (!Explored.contains(GEP->getOperand(0)))
438 WorkList.push_back(GEP->getOperand(0));
439 }
440
441 if (WorkList.back() == V) {
442 WorkList.pop_back();
443 // We've finished visiting this node, mark it as such.
444 Explored.insert(V);
445 }
446
447 if (auto *PN = dyn_cast<PHINode>(V)) {
448 // We cannot transform PHIs on unsplittable basic blocks.
449 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
450 return false;
451 Explored.insert(PN);
452 PHIs.insert(PN);
453 }
454 }
455
456 // Explore the PHI nodes further.
457 for (auto *PN : PHIs)
458 for (Value *Op : PN->incoming_values())
459 if (!Explored.contains(Op))
460 WorkList.push_back(Op);
461 }
462
463 // Make sure that we can do this. Since we can't insert GEPs in a basic
464 // block before a PHI node, we can't easily do this transformation if
465 // we have PHI node users of transformed instructions.
466 for (Value *Val : Explored) {
467 for (Value *Use : Val->uses()) {
468
469 auto *PHI = dyn_cast<PHINode>(Use);
470 auto *Inst = dyn_cast<Instruction>(Val);
471
472 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
473 !Explored.contains(PHI))
474 continue;
475
476 if (PHI->getParent() == Inst->getParent())
477 return false;
478 }
479 }
480 return true;
481}
482
483// Sets the appropriate insert point on Builder where we can add
484// a replacement Instruction for V (if that is possible).
485static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
486 bool Before = true) {
487 if (auto *PHI = dyn_cast<PHINode>(V)) {
488 BasicBlock *Parent = PHI->getParent();
489 Builder.SetInsertPoint(Parent, Parent->getFirstInsertionPt());
490 return;
491 }
492 if (auto *I = dyn_cast<Instruction>(V)) {
493 if (!Before)
494 I = &*std::next(I->getIterator());
495 Builder.SetInsertPoint(I);
496 return;
497 }
498 if (auto *A = dyn_cast<Argument>(V)) {
499 // Set the insertion point in the entry block.
500 BasicBlock &Entry = A->getParent()->getEntryBlock();
501 Builder.SetInsertPoint(&Entry, Entry.getFirstInsertionPt());
502 return;
503 }
504 // Otherwise, this is a constant and we don't need to set a new
505 // insertion point.
506 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
507}
508
509/// Returns a re-written value of Start as an indexed GEP using Base as a
510/// pointer.
512 const DataLayout &DL,
513 SetVector<Value *> &Explored,
514 InstCombiner &IC) {
515 // Perform all the substitutions. This is a bit tricky because we can
516 // have cycles in our use-def chains.
517 // 1. Create the PHI nodes without any incoming values.
518 // 2. Create all the other values.
519 // 3. Add the edges for the PHI nodes.
520 // 4. Emit GEPs to get the original pointers.
521 // 5. Remove the original instructions.
522 Type *IndexType = IntegerType::get(
523 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
524
526 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
527
528 // Create the new PHI nodes, without adding any incoming values.
529 for (Value *Val : Explored) {
530 if (Val == Base)
531 continue;
532 // Create empty phi nodes. This avoids cyclic dependencies when creating
533 // the remaining instructions.
534 if (auto *PHI = dyn_cast<PHINode>(Val))
535 NewInsts[PHI] =
536 PHINode::Create(IndexType, PHI->getNumIncomingValues(),
537 PHI->getName() + ".idx", PHI->getIterator());
538 }
539 IRBuilder<> Builder(Base->getContext());
540
541 // Create all the other instructions.
542 for (Value *Val : Explored) {
543 if (NewInsts.contains(Val))
544 continue;
545
546 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
547 setInsertionPoint(Builder, GEP);
548 Value *Op = NewInsts[GEP->getOperand(0)];
549 Value *OffsetV = emitGEPOffset(&Builder, DL, GEP);
551 NewInsts[GEP] = OffsetV;
552 else
553 NewInsts[GEP] = Builder.CreateAdd(
554 Op, OffsetV, GEP->getOperand(0)->getName() + ".add",
555 /*NUW=*/NW.hasNoUnsignedWrap(),
556 /*NSW=*/NW.hasNoUnsignedSignedWrap());
557 continue;
558 }
559 if (isa<PHINode>(Val))
560 continue;
561
562 llvm_unreachable("Unexpected instruction type");
563 }
564
565 // Add the incoming values to the PHI nodes.
566 for (Value *Val : Explored) {
567 if (Val == Base)
568 continue;
569 // All the instructions have been created, we can now add edges to the
570 // phi nodes.
571 if (auto *PHI = dyn_cast<PHINode>(Val)) {
572 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
573 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
574 Value *NewIncoming = PHI->getIncomingValue(I);
575
576 auto It = NewInsts.find(NewIncoming);
577 if (It != NewInsts.end())
578 NewIncoming = It->second;
579
580 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
581 }
582 }
583 }
584
585 for (Value *Val : Explored) {
586 if (Val == Base)
587 continue;
588
589 setInsertionPoint(Builder, Val, false);
590 // Create GEP for external users.
591 Value *NewVal = Builder.CreateGEP(Builder.getInt8Ty(), Base, NewInsts[Val],
592 Val->getName() + ".ptr", NW);
593 IC.replaceInstUsesWith(*cast<Instruction>(Val), NewVal);
594 // Add old instruction to worklist for DCE. We don't directly remove it
595 // here because the original compare is one of the users.
597 }
598
599 return NewInsts[Start];
600}
601
602/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
603/// We can look through PHIs, GEPs and casts in order to determine a common base
604/// between GEPLHS and RHS.
607 const DataLayout &DL,
608 InstCombiner &IC) {
609 // FIXME: Support vector of pointers.
610 if (GEPLHS->getType()->isVectorTy())
611 return nullptr;
612
613 if (!GEPLHS->hasAllConstantIndices())
614 return nullptr;
615
616 APInt Offset(DL.getIndexTypeSizeInBits(GEPLHS->getType()), 0);
617 Value *PtrBase =
619 /*AllowNonInbounds*/ false);
620
621 // Bail if we looked through addrspacecast.
622 if (PtrBase->getType() != GEPLHS->getType())
623 return nullptr;
624
625 // The set of nodes that will take part in this transformation.
626 SetVector<Value *> Nodes;
627 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags();
628 if (!canRewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes))
629 return nullptr;
630
631 // We know we can re-write this as
632 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
633 // Since we've only looked through inbouds GEPs we know that we
634 // can't have overflow on either side. We can therefore re-write
635 // this as:
636 // OFFSET1 cmp OFFSET2
637 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes, IC);
638
639 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
640 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
641 // offset. Since Index is the offset of LHS to the base pointer, we will now
642 // compare the offsets instead of comparing the pointers.
644 IC.Builder.getInt(Offset), NewRHS);
645}
646
647/// Fold comparisons between a GEP instruction and something else. At this point
648/// we know that the GEP is on the LHS of the comparison.
651 // Don't transform signed compares of GEPs into index compares. Even if the
652 // GEP is inbounds, the final add of the base pointer can have signed overflow
653 // and would change the result of the icmp.
654 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
655 // the maximum signed value for the pointer type.
657 return nullptr;
658
659 // Look through bitcasts and addrspacecasts. We do not however want to remove
660 // 0 GEPs.
661 if (!isa<GetElementPtrInst>(RHS))
662 RHS = RHS->stripPointerCasts();
663
664 auto CanFold = [Cond](GEPNoWrapFlags NW) {
666 return true;
667
668 // Unsigned predicates can be folded if the GEPs have *any* nowrap flags.
670 return NW != GEPNoWrapFlags::none();
671 };
672
673 auto NewICmp = [Cond](GEPNoWrapFlags NW, Value *Op1, Value *Op2) {
674 if (!NW.hasNoUnsignedWrap()) {
675 // Convert signed to unsigned comparison.
676 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Op1, Op2);
677 }
678
679 auto *I = new ICmpInst(Cond, Op1, Op2);
680 I->setSameSign(NW.hasNoUnsignedSignedWrap());
681 return I;
682 };
683
685 if (Base.Ptr == RHS && CanFold(Base.LHSNW) && !Base.isExpensive()) {
686 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
687 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
688 Value *Offset =
689 EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy, /*RewriteGEPs=*/true);
690 return NewICmp(Base.LHSNW, Offset,
691 Constant::getNullValue(Offset->getType()));
692 }
693
694 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
695 isa<Constant>(RHS) && cast<Constant>(RHS)->isNullValue() &&
696 !NullPointerIsDefined(I.getFunction(),
697 RHS->getType()->getPointerAddressSpace())) {
698 // For most address spaces, an allocation can't be placed at null, but null
699 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
700 // the only valid inbounds address derived from null, is null itself.
701 // Thus, we have four cases to consider:
702 // 1) Base == nullptr, Offset == 0 -> inbounds, null
703 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
704 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
705 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
706 //
707 // (Note if we're indexing a type of size 0, that simply collapses into one
708 // of the buckets above.)
709 //
710 // In general, we're allowed to make values less poison (i.e. remove
711 // sources of full UB), so in this case, we just select between the two
712 // non-poison cases (1 and 4 above).
713 //
714 // For vectors, we apply the same reasoning on a per-lane basis.
715 auto *Base = GEPLHS->getPointerOperand();
716 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
717 auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
718 Base = Builder.CreateVectorSplat(EC, Base);
719 }
720 return new ICmpInst(Cond, Base,
722 cast<Constant>(RHS), Base->getType()));
723 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
724 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags() & GEPRHS->getNoWrapFlags();
725
726 // If the base pointers are different, but the indices are the same, just
727 // compare the base pointer.
728 if (GEPLHS->getOperand(0) != GEPRHS->getOperand(0)) {
729 bool IndicesTheSame =
730 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
731 GEPLHS->getPointerOperand()->getType() ==
732 GEPRHS->getPointerOperand()->getType() &&
733 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
734 if (IndicesTheSame)
735 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
736 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
737 IndicesTheSame = false;
738 break;
739 }
740
741 // If all indices are the same, just compare the base pointers.
742 Type *BaseType = GEPLHS->getOperand(0)->getType();
743 if (IndicesTheSame &&
744 CmpInst::makeCmpResultType(BaseType) == I.getType() && CanFold(NW))
745 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
746
747 // If we're comparing GEPs with two base pointers that only differ in type
748 // and both GEPs have only constant indices or just one use, then fold
749 // the compare with the adjusted indices.
750 // FIXME: Support vector of pointers.
751 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
752 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
753 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
754 GEPLHS->getOperand(0)->stripPointerCasts() ==
755 GEPRHS->getOperand(0)->stripPointerCasts() &&
756 !GEPLHS->getType()->isVectorTy()) {
757 Value *LOffset = EmitGEPOffset(GEPLHS);
758 Value *ROffset = EmitGEPOffset(GEPRHS);
759
760 // If we looked through an addrspacecast between different sized address
761 // spaces, the LHS and RHS pointers are different sized
762 // integers. Truncate to the smaller one.
763 Type *LHSIndexTy = LOffset->getType();
764 Type *RHSIndexTy = ROffset->getType();
765 if (LHSIndexTy != RHSIndexTy) {
766 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
767 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
768 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
769 } else
770 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
771 }
772
774 LOffset, ROffset);
775 return replaceInstUsesWith(I, Cmp);
776 }
777 }
778
779 if (GEPLHS->getOperand(0) == GEPRHS->getOperand(0) &&
780 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
781 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
782 // If the GEPs only differ by one index, compare it.
783 unsigned NumDifferences = 0; // Keep track of # differences.
784 unsigned DiffOperand = 0; // The operand that differs.
785 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
786 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
787 Type *LHSType = GEPLHS->getOperand(i)->getType();
788 Type *RHSType = GEPRHS->getOperand(i)->getType();
789 // FIXME: Better support for vector of pointers.
790 if (LHSType->getPrimitiveSizeInBits() !=
791 RHSType->getPrimitiveSizeInBits() ||
792 (GEPLHS->getType()->isVectorTy() &&
793 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
794 // Irreconcilable differences.
795 NumDifferences = 2;
796 break;
797 }
798
799 if (NumDifferences++)
800 break;
801 DiffOperand = i;
802 }
803
804 if (NumDifferences == 0) // SAME GEP?
805 return replaceInstUsesWith(
806 I, // No comparison is needed here.
807 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
808 // If two GEPs only differ by an index, compare them.
809 // Note that nowrap flags are always needed when comparing two indices.
810 else if (NumDifferences == 1 && NW != GEPNoWrapFlags::none()) {
811 Value *LHSV = GEPLHS->getOperand(DiffOperand);
812 Value *RHSV = GEPRHS->getOperand(DiffOperand);
813 return NewICmp(NW, LHSV, RHSV);
814 }
815 }
816
817 if (Base.Ptr && CanFold(Base.LHSNW & Base.RHSNW) && !Base.isExpensive()) {
818 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
819 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
820 Value *L =
821 EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy, /*RewriteGEP=*/true);
822 Value *R =
823 EmitGEPOffsets(Base.RHSGEPs, Base.RHSNW, IdxTy, /*RewriteGEP=*/true);
824 return NewICmp(Base.LHSNW & Base.RHSNW, L, R);
825 }
826 }
827
828 // Try convert this to an indexed compare by looking through PHIs/casts as a
829 // last resort.
830 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
831}
832
834 // It would be tempting to fold away comparisons between allocas and any
835 // pointer not based on that alloca (e.g. an argument). However, even
836 // though such pointers cannot alias, they can still compare equal.
837 //
838 // But LLVM doesn't specify where allocas get their memory, so if the alloca
839 // doesn't escape we can argue that it's impossible to guess its value, and we
840 // can therefore act as if any such guesses are wrong.
841 //
842 // However, we need to ensure that this folding is consistent: We can't fold
843 // one comparison to false, and then leave a different comparison against the
844 // same value alone (as it might evaluate to true at runtime, leading to a
845 // contradiction). As such, this code ensures that all comparisons are folded
846 // at the same time, and there are no other escapes.
847
848 struct CmpCaptureTracker : public CaptureTracker {
849 AllocaInst *Alloca;
850 bool Captured = false;
851 /// The value of the map is a bit mask of which icmp operands the alloca is
852 /// used in.
854
855 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
856
857 void tooManyUses() override { Captured = true; }
858
859 Action captured(const Use *U, UseCaptureInfo CI) override {
860 // TODO(captures): Use UseCaptureInfo.
861 auto *ICmp = dyn_cast<ICmpInst>(U->getUser());
862 // We need to check that U is based *only* on the alloca, and doesn't
863 // have other contributions from a select/phi operand.
864 // TODO: We could check whether getUnderlyingObjects() reduces to one
865 // object, which would allow looking through phi nodes.
866 if (ICmp && ICmp->isEquality() && getUnderlyingObject(*U) == Alloca) {
867 // Collect equality icmps of the alloca, and don't treat them as
868 // captures.
869 ICmps[ICmp] |= 1u << U->getOperandNo();
870 return Continue;
871 }
872
873 Captured = true;
874 return Stop;
875 }
876 };
877
878 CmpCaptureTracker Tracker(Alloca);
879 PointerMayBeCaptured(Alloca, &Tracker);
880 if (Tracker.Captured)
881 return false;
882
883 bool Changed = false;
884 for (auto [ICmp, Operands] : Tracker.ICmps) {
885 switch (Operands) {
886 case 1:
887 case 2: {
888 // The alloca is only used in one icmp operand. Assume that the
889 // equality is false.
890 auto *Res = ConstantInt::get(ICmp->getType(),
891 ICmp->getPredicate() == ICmpInst::ICMP_NE);
892 replaceInstUsesWith(*ICmp, Res);
894 Changed = true;
895 break;
896 }
897 case 3:
898 // Both icmp operands are based on the alloca, so this is comparing
899 // pointer offsets, without leaking any information about the address
900 // of the alloca. Ignore such comparisons.
901 break;
902 default:
903 llvm_unreachable("Cannot happen");
904 }
905 }
906
907 return Changed;
908}
909
910/// Fold "icmp pred (X+C), X".
912 CmpPredicate Pred) {
913 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
914 // so the values can never be equal. Similarly for all other "or equals"
915 // operators.
916 assert(!!C && "C should not be zero!");
917
918 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
919 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
920 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
921 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
922 Constant *R =
923 ConstantInt::get(X->getType(), APInt::getMaxValue(C.getBitWidth()) - C);
924 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
925 }
926
927 // (X+1) >u X --> X <u (0-1) --> X != 255
928 // (X+2) >u X --> X <u (0-2) --> X <u 254
929 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
930 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
931 return new ICmpInst(ICmpInst::ICMP_ULT, X,
932 ConstantInt::get(X->getType(), -C));
933
934 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
935
936 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
937 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
938 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
939 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
940 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
941 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
942 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
943 return new ICmpInst(ICmpInst::ICMP_SGT, X,
944 ConstantInt::get(X->getType(), SMax - C));
945
946 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
947 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
948 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
949 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
950 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
951 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
952
953 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
954 return new ICmpInst(ICmpInst::ICMP_SLT, X,
955 ConstantInt::get(X->getType(), SMax - (C - 1)));
956}
957
958/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
959/// (icmp eq/ne A, Log2(AP2/AP1)) ->
960/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
962 const APInt &AP1,
963 const APInt &AP2) {
964 assert(I.isEquality() && "Cannot fold icmp gt/lt");
965
966 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
967 if (I.getPredicate() == I.ICMP_NE)
968 Pred = CmpInst::getInversePredicate(Pred);
969 return new ICmpInst(Pred, LHS, RHS);
970 };
971
972 // Don't bother doing any work for cases which InstSimplify handles.
973 if (AP2.isZero())
974 return nullptr;
975
976 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
977 if (IsAShr) {
978 if (AP2.isAllOnes())
979 return nullptr;
980 if (AP2.isNegative() != AP1.isNegative())
981 return nullptr;
982 if (AP2.sgt(AP1))
983 return nullptr;
984 }
985
986 if (!AP1)
987 // 'A' must be large enough to shift out the highest set bit.
988 return getICmp(I.ICMP_UGT, A,
989 ConstantInt::get(A->getType(), AP2.logBase2()));
990
991 if (AP1 == AP2)
992 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
993
994 int Shift;
995 if (IsAShr && AP1.isNegative())
996 Shift = AP1.countl_one() - AP2.countl_one();
997 else
998 Shift = AP1.countl_zero() - AP2.countl_zero();
999
1000 if (Shift > 0) {
1001 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1002 // There are multiple solutions if we are comparing against -1 and the LHS
1003 // of the ashr is not a power of two.
1004 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1005 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1006 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1007 } else if (AP1 == AP2.lshr(Shift)) {
1008 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1009 }
1010 }
1011
1012 // Shifting const2 will never be equal to const1.
1013 // FIXME: This should always be handled by InstSimplify?
1014 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1015 return replaceInstUsesWith(I, TorF);
1016}
1017
1018/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1019/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1021 const APInt &AP1,
1022 const APInt &AP2) {
1023 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1024
1025 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1026 if (I.getPredicate() == I.ICMP_NE)
1027 Pred = CmpInst::getInversePredicate(Pred);
1028 return new ICmpInst(Pred, LHS, RHS);
1029 };
1030
1031 // Don't bother doing any work for cases which InstSimplify handles.
1032 if (AP2.isZero())
1033 return nullptr;
1034
1035 unsigned AP2TrailingZeros = AP2.countr_zero();
1036
1037 if (!AP1 && AP2TrailingZeros != 0)
1038 return getICmp(
1039 I.ICMP_UGE, A,
1040 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1041
1042 if (AP1 == AP2)
1043 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1044
1045 // Get the distance between the lowest bits that are set.
1046 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1047
1048 if (Shift > 0 && AP2.shl(Shift) == AP1)
1049 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1050
1051 // Shifting const2 will never be equal to const1.
1052 // FIXME: This should always be handled by InstSimplify?
1053 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1054 return replaceInstUsesWith(I, TorF);
1055}
1056
1057/// The caller has matched a pattern of the form:
1058/// I = icmp ugt (add (add A, B), CI2), CI1
1059/// If this is of the form:
1060/// sum = a + b
1061/// if (sum+128 >u 255)
1062/// Then replace it with llvm.sadd.with.overflow.i8.
1063///
1065 ConstantInt *CI2, ConstantInt *CI1,
1066 InstCombinerImpl &IC) {
1067 // The transformation we're trying to do here is to transform this into an
1068 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1069 // with a narrower add, and discard the add-with-constant that is part of the
1070 // range check (if we can't eliminate it, this isn't profitable).
1071
1072 // In order to eliminate the add-with-constant, the compare can be its only
1073 // use.
1074 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1075 if (!AddWithCst->hasOneUse())
1076 return nullptr;
1077
1078 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1079 if (!CI2->getValue().isPowerOf2())
1080 return nullptr;
1081 unsigned NewWidth = CI2->getValue().countr_zero();
1082 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1083 return nullptr;
1084
1085 // The width of the new add formed is 1 more than the bias.
1086 ++NewWidth;
1087
1088 // Check to see that CI1 is an all-ones value with NewWidth bits.
1089 if (CI1->getBitWidth() == NewWidth ||
1090 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1091 return nullptr;
1092
1093 // This is only really a signed overflow check if the inputs have been
1094 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1095 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1096 if (IC.ComputeMaxSignificantBits(A, &I) > NewWidth ||
1097 IC.ComputeMaxSignificantBits(B, &I) > NewWidth)
1098 return nullptr;
1099
1100 // In order to replace the original add with a narrower
1101 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1102 // and truncates that discard the high bits of the add. Verify that this is
1103 // the case.
1104 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1105 for (User *U : OrigAdd->users()) {
1106 if (U == AddWithCst)
1107 continue;
1108
1109 // Only accept truncates for now. We would really like a nice recursive
1110 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1111 // chain to see which bits of a value are actually demanded. If the
1112 // original add had another add which was then immediately truncated, we
1113 // could still do the transformation.
1115 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1116 return nullptr;
1117 }
1118
1119 // If the pattern matches, truncate the inputs to the narrower type and
1120 // use the sadd_with_overflow intrinsic to efficiently compute both the
1121 // result and the overflow bit.
1122 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1124 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1125
1126 InstCombiner::BuilderTy &Builder = IC.Builder;
1127
1128 // Put the new code above the original add, in case there are any uses of the
1129 // add between the add and the compare.
1130 Builder.SetInsertPoint(OrigAdd);
1131
1132 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1133 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1134 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1135 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1136 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1137
1138 // The inner add was the result of the narrow add, zero extended to the
1139 // wider type. Replace it with the result computed by the intrinsic.
1140 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1141 IC.eraseInstFromFunction(*OrigAdd);
1142
1143 // The original icmp gets replaced with the overflow value.
1144 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1145}
1146
1147/// If we have:
1148/// icmp eq/ne (urem/srem %x, %y), 0
1149/// iff %y is a power-of-two, we can replace this with a bit test:
1150/// icmp eq/ne (and %x, (add %y, -1)), 0
1152 // This fold is only valid for equality predicates.
1153 if (!I.isEquality())
1154 return nullptr;
1155 CmpPredicate Pred;
1156 Value *X, *Y, *Zero;
1157 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1158 m_CombineAnd(m_Zero(), m_Value(Zero)))))
1159 return nullptr;
1160 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, &I))
1161 return nullptr;
1162 // This may increase instruction count, we don't enforce that Y is a constant.
1163 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1164 Value *Masked = Builder.CreateAnd(X, Mask);
1165 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1166}
1167
1168/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1169/// by one-less-than-bitwidth into a sign test on the original value.
1171 Instruction *Val;
1172 CmpPredicate Pred;
1173 if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1174 return nullptr;
1175
1176 Value *X;
1177 Type *XTy;
1178
1179 Constant *C;
1180 if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1181 XTy = X->getType();
1182 unsigned XBitWidth = XTy->getScalarSizeInBits();
1184 APInt(XBitWidth, XBitWidth - 1))))
1185 return nullptr;
1186 } else if (isa<BinaryOperator>(Val) &&
1188 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1189 /*AnalyzeForSignBitExtraction=*/true))) {
1190 XTy = X->getType();
1191 } else
1192 return nullptr;
1193
1194 return ICmpInst::Create(Instruction::ICmp,
1198}
1199
1200// Handle icmp pred X, 0
1202 CmpInst::Predicate Pred = Cmp.getPredicate();
1203 if (!match(Cmp.getOperand(1), m_Zero()))
1204 return nullptr;
1205
1206 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1207 if (Pred == ICmpInst::ICMP_SGT) {
1208 Value *A, *B;
1209 if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1210 if (isKnownPositive(A, SQ.getWithInstruction(&Cmp)))
1211 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1212 if (isKnownPositive(B, SQ.getWithInstruction(&Cmp)))
1213 return new ICmpInst(Pred, A, Cmp.getOperand(1));
1214 }
1215 }
1216
1218 return New;
1219
1220 // Given:
1221 // icmp eq/ne (urem %x, %y), 0
1222 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1223 // icmp eq/ne %x, 0
1224 Value *X, *Y;
1225 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1226 ICmpInst::isEquality(Pred)) {
1227 KnownBits XKnown = computeKnownBits(X, &Cmp);
1228 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1229 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1230 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1231 }
1232
1233 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1234 // odd/non-zero/there is no overflow.
1235 if (match(Cmp.getOperand(0), m_Mul(m_Value(X), m_Value(Y))) &&
1236 ICmpInst::isEquality(Pred)) {
1237
1238 KnownBits XKnown = computeKnownBits(X, &Cmp);
1239 // if X % 2 != 0
1240 // (icmp eq/ne Y)
1241 if (XKnown.countMaxTrailingZeros() == 0)
1242 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1243
1244 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1245 // if Y % 2 != 0
1246 // (icmp eq/ne X)
1247 if (YKnown.countMaxTrailingZeros() == 0)
1248 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1249
1250 auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1251 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1252 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
1253 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1254 // but to avoid unnecessary work, first just if this is an obvious case.
1255
1256 // if X non-zero and NoOverflow(X * Y)
1257 // (icmp eq/ne Y)
1258 if (!XKnown.One.isZero() || isKnownNonZero(X, Q))
1259 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1260
1261 // if Y non-zero and NoOverflow(X * Y)
1262 // (icmp eq/ne X)
1263 if (!YKnown.One.isZero() || isKnownNonZero(Y, Q))
1264 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1265 }
1266 // Note, we are skipping cases:
1267 // if Y % 2 != 0 AND X % 2 != 0
1268 // (false/true)
1269 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1270 // (false/true)
1271 // Those can be simplified later as we would have already replaced the (icmp
1272 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1273 // will fold to a constant elsewhere.
1274 }
1275
1276 // (icmp eq/ne f(X), 0) -> (icmp eq/ne X, 0)
1277 // where f(X) == 0 if and only if X == 0
1278 if (ICmpInst::isEquality(Pred))
1279 if (Value *Stripped = stripNullTest(Cmp.getOperand(0)))
1280 return new ICmpInst(Pred, Stripped,
1281 Constant::getNullValue(Stripped->getType()));
1282
1283 return nullptr;
1284}
1285
1286/// Fold icmp eq (num + mask) & ~mask, num
1287/// to
1288/// icmp eq (and num, mask), 0
1289/// Where mask is a low bit mask.
1291 Value *Num;
1292 CmpPredicate Pred;
1293 const APInt *Mask, *Neg;
1294
1295 if (!match(&Cmp,
1296 m_c_ICmp(Pred, m_Value(Num),
1298 m_LowBitMask(Mask))),
1299 m_APInt(Neg))))))
1300 return nullptr;
1301
1302 if (*Neg != ~*Mask)
1303 return nullptr;
1304
1305 if (!ICmpInst::isEquality(Pred))
1306 return nullptr;
1307
1308 // Create new icmp eq (num & mask), 0
1309 auto *NewAnd = Builder.CreateAnd(Num, *Mask);
1310 auto *Zero = Constant::getNullValue(Num->getType());
1311
1312 return new ICmpInst(Pred, NewAnd, Zero);
1313}
1314
1315/// Fold icmp Pred X, C.
1316/// TODO: This code structure does not make sense. The saturating add fold
1317/// should be moved to some other helper and extended as noted below (it is also
1318/// possible that code has been made unnecessary - do we canonicalize IR to
1319/// overflow/saturating intrinsics or not?).
1321 // Match the following pattern, which is a common idiom when writing
1322 // overflow-safe integer arithmetic functions. The source performs an addition
1323 // in wider type and explicitly checks for overflow using comparisons against
1324 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1325 //
1326 // TODO: This could probably be generalized to handle other overflow-safe
1327 // operations if we worked out the formulas to compute the appropriate magic
1328 // constants.
1329 //
1330 // sum = a + b
1331 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1332 CmpInst::Predicate Pred = Cmp.getPredicate();
1333 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1334 Value *A, *B;
1335 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1336 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1337 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1338 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1339 return Res;
1340
1341 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1343 if (!C)
1344 return nullptr;
1345
1346 if (auto *Phi = dyn_cast<PHINode>(Op0))
1347 if (all_of(Phi->operands(), IsaPred<Constant>)) {
1349 for (Value *V : Phi->incoming_values()) {
1350 Constant *Res =
1352 if (!Res)
1353 return nullptr;
1354 Ops.push_back(Res);
1355 }
1356 Builder.SetInsertPoint(Phi);
1357 PHINode *NewPhi = Builder.CreatePHI(Cmp.getType(), Phi->getNumOperands());
1358 for (auto [V, Pred] : zip(Ops, Phi->blocks()))
1359 NewPhi->addIncoming(V, Pred);
1360 return replaceInstUsesWith(Cmp, NewPhi);
1361 }
1362
1364 return R;
1365
1366 return nullptr;
1367}
1368
1369/// Canonicalize icmp instructions based on dominating conditions.
1371 // We already checked simple implication in InstSimplify, only handle complex
1372 // cases here.
1373 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1374 const APInt *C;
1375 if (!match(Y, m_APInt(C)))
1376 return nullptr;
1377
1378 CmpInst::Predicate Pred = Cmp.getPredicate();
1380
1381 auto handleDomCond = [&](ICmpInst::Predicate DomPred,
1382 const APInt *DomC) -> Instruction * {
1383 // We have 2 compares of a variable with constants. Calculate the constant
1384 // ranges of those compares to see if we can transform the 2nd compare:
1385 // DomBB:
1386 // DomCond = icmp DomPred X, DomC
1387 // br DomCond, CmpBB, FalseBB
1388 // CmpBB:
1389 // Cmp = icmp Pred X, C
1390 ConstantRange DominatingCR =
1391 ConstantRange::makeExactICmpRegion(DomPred, *DomC);
1392 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1393 ConstantRange Difference = DominatingCR.difference(CR);
1394 if (Intersection.isEmptySet())
1395 return replaceInstUsesWith(Cmp, Builder.getFalse());
1396 if (Difference.isEmptySet())
1397 return replaceInstUsesWith(Cmp, Builder.getTrue());
1398
1399 // Canonicalizing a sign bit comparison that gets used in a branch,
1400 // pessimizes codegen by generating branch on zero instruction instead
1401 // of a test and branch. So we avoid canonicalizing in such situations
1402 // because test and branch instruction has better branch displacement
1403 // than compare and branch instruction.
1404 bool UnusedBit;
1405 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1406 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1407 return nullptr;
1408
1409 // Avoid an infinite loop with min/max canonicalization.
1410 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1411 if (Cmp.hasOneUse() &&
1412 match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1413 return nullptr;
1414
1415 if (const APInt *EqC = Intersection.getSingleElement())
1416 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1417 if (const APInt *NeC = Difference.getSingleElement())
1418 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1419 return nullptr;
1420 };
1421
1422 for (BranchInst *BI : DC.conditionsFor(X)) {
1423 CmpPredicate DomPred;
1424 const APInt *DomC;
1425 if (!match(BI->getCondition(),
1426 m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))))
1427 continue;
1428
1429 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1430 if (DT.dominates(Edge0, Cmp.getParent())) {
1431 if (auto *V = handleDomCond(DomPred, DomC))
1432 return V;
1433 } else {
1434 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1435 if (DT.dominates(Edge1, Cmp.getParent()))
1436 if (auto *V =
1437 handleDomCond(CmpInst::getInversePredicate(DomPred), DomC))
1438 return V;
1439 }
1440 }
1441
1442 return nullptr;
1443}
1444
1445/// Fold icmp (trunc X), C.
1447 TruncInst *Trunc,
1448 const APInt &C) {
1449 ICmpInst::Predicate Pred = Cmp.getPredicate();
1450 Value *X = Trunc->getOperand(0);
1451 Type *SrcTy = X->getType();
1452 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1453 SrcBits = SrcTy->getScalarSizeInBits();
1454
1455 // Match (icmp pred (trunc nuw/nsw X), C)
1456 // Which we can convert to (icmp pred X, (sext/zext C))
1457 if (shouldChangeType(Trunc->getType(), SrcTy)) {
1458 if (Trunc->hasNoSignedWrap())
1459 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.sext(SrcBits)));
1460 if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())
1461 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.zext(SrcBits)));
1462 }
1463
1464 if (C.isOne() && C.getBitWidth() > 1) {
1465 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1466 Value *V = nullptr;
1467 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1468 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1469 ConstantInt::get(V->getType(), 1));
1470 }
1471
1472 // TODO: Handle non-equality predicates.
1473 Value *Y;
1474 const APInt *Pow2;
1475 if (Cmp.isEquality() && match(X, m_Shl(m_Power2(Pow2), m_Value(Y))) &&
1476 DstBits > Pow2->logBase2()) {
1477 // (trunc (Pow2 << Y) to iN) == 0 --> Y u>= N - log2(Pow2)
1478 // (trunc (Pow2 << Y) to iN) != 0 --> Y u< N - log2(Pow2)
1479 // iff N > log2(Pow2)
1480 if (C.isZero()) {
1481 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1482 return new ICmpInst(NewPred, Y,
1483 ConstantInt::get(SrcTy, DstBits - Pow2->logBase2()));
1484 }
1485 // (trunc (Pow2 << Y) to iN) == 2**C --> Y == C - log2(Pow2)
1486 // (trunc (Pow2 << Y) to iN) != 2**C --> Y != C - log2(Pow2)
1487 if (C.isPowerOf2())
1488 return new ICmpInst(
1489 Pred, Y, ConstantInt::get(SrcTy, C.logBase2() - Pow2->logBase2()));
1490 }
1491
1492 if (Cmp.isEquality() && (Trunc->hasOneUse() || Trunc->hasNoUnsignedWrap())) {
1493 // Canonicalize to a mask and wider compare if the wide type is suitable:
1494 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1495 if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1496 Constant *Mask =
1497 ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1498 Value *And = Trunc->hasNoUnsignedWrap() ? X : Builder.CreateAnd(X, Mask);
1499 Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1500 return new ICmpInst(Pred, And, WideC);
1501 }
1502
1503 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1504 // of the high bits truncated out of x are known.
1505 KnownBits Known = computeKnownBits(X, &Cmp);
1506
1507 // If all the high bits are known, we can do this xform.
1508 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1509 // Pull in the high bits from known-ones set.
1510 APInt NewRHS = C.zext(SrcBits);
1511 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1512 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1513 }
1514 }
1515
1516 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1517 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1518 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1519 Value *ShOp;
1520 uint64_t ShAmt;
1521 bool TrueIfSigned;
1522 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1523 match(X, m_Shr(m_Value(ShOp), m_ConstantInt(ShAmt))) &&
1524 DstBits == SrcBits - ShAmt) {
1525 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1527 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1529 }
1530
1531 return nullptr;
1532}
1533
1534/// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
1535/// Fold icmp (trunc nuw/nsw X), (zext/sext Y).
1538 const SimplifyQuery &Q) {
1539 Value *X, *Y;
1540 CmpPredicate Pred;
1541 bool YIsSExt = false;
1542 // Try to match icmp (trunc X), (trunc Y)
1543 if (match(&Cmp, m_ICmp(Pred, m_Trunc(m_Value(X)), m_Trunc(m_Value(Y))))) {
1544 unsigned NoWrapFlags = cast<TruncInst>(Cmp.getOperand(0))->getNoWrapKind() &
1545 cast<TruncInst>(Cmp.getOperand(1))->getNoWrapKind();
1546 if (Cmp.isSigned()) {
1547 // For signed comparisons, both truncs must be nsw.
1548 if (!(NoWrapFlags & TruncInst::NoSignedWrap))
1549 return nullptr;
1550 } else {
1551 // For unsigned and equality comparisons, either both must be nuw or
1552 // both must be nsw, we don't care which.
1553 if (!NoWrapFlags)
1554 return nullptr;
1555 }
1556
1557 if (X->getType() != Y->getType() &&
1558 (!Cmp.getOperand(0)->hasOneUse() || !Cmp.getOperand(1)->hasOneUse()))
1559 return nullptr;
1560 if (!isDesirableIntType(X->getType()->getScalarSizeInBits()) &&
1561 isDesirableIntType(Y->getType()->getScalarSizeInBits())) {
1562 std::swap(X, Y);
1563 Pred = Cmp.getSwappedPredicate(Pred);
1564 }
1565 YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);
1566 }
1567 // Try to match icmp (trunc nuw X), (zext Y)
1568 else if (!Cmp.isSigned() &&
1569 match(&Cmp, m_c_ICmp(Pred, m_NUWTrunc(m_Value(X)),
1570 m_OneUse(m_ZExt(m_Value(Y)))))) {
1571 // Can fold trunc nuw + zext for unsigned and equality predicates.
1572 }
1573 // Try to match icmp (trunc nsw X), (sext Y)
1574 else if (match(&Cmp, m_c_ICmp(Pred, m_NSWTrunc(m_Value(X)),
1576 // Can fold trunc nsw + zext/sext for all predicates.
1577 YIsSExt =
1578 isa<SExtInst>(Cmp.getOperand(0)) || isa<SExtInst>(Cmp.getOperand(1));
1579 } else
1580 return nullptr;
1581
1582 Type *TruncTy = Cmp.getOperand(0)->getType();
1583 unsigned TruncBits = TruncTy->getScalarSizeInBits();
1584
1585 // If this transform will end up changing from desirable types -> undesirable
1586 // types skip it.
1587 if (isDesirableIntType(TruncBits) &&
1588 !isDesirableIntType(X->getType()->getScalarSizeInBits()))
1589 return nullptr;
1590
1591 Value *NewY = Builder.CreateIntCast(Y, X->getType(), YIsSExt);
1592 return new ICmpInst(Pred, X, NewY);
1593}
1594
1595/// Fold icmp (xor X, Y), C.
1598 const APInt &C) {
1599 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1600 return I;
1601
1602 Value *X = Xor->getOperand(0);
1603 Value *Y = Xor->getOperand(1);
1604 const APInt *XorC;
1605 if (!match(Y, m_APInt(XorC)))
1606 return nullptr;
1607
1608 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1609 // fold the xor.
1610 ICmpInst::Predicate Pred = Cmp.getPredicate();
1611 bool TrueIfSigned = false;
1612 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1613
1614 // If the sign bit of the XorCst is not set, there is no change to
1615 // the operation, just stop using the Xor.
1616 if (!XorC->isNegative())
1617 return replaceOperand(Cmp, 0, X);
1618
1619 // Emit the opposite comparison.
1620 if (TrueIfSigned)
1621 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1622 ConstantInt::getAllOnesValue(X->getType()));
1623 else
1624 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1625 ConstantInt::getNullValue(X->getType()));
1626 }
1627
1628 if (Xor->hasOneUse()) {
1629 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1630 if (!Cmp.isEquality() && XorC->isSignMask()) {
1631 Pred = Cmp.getFlippedSignednessPredicate();
1632 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1633 }
1634
1635 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1636 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1637 Pred = Cmp.getFlippedSignednessPredicate();
1638 Pred = Cmp.getSwappedPredicate(Pred);
1639 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1640 }
1641 }
1642
1643 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1644 if (Pred == ICmpInst::ICMP_UGT) {
1645 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1646 if (*XorC == ~C && (C + 1).isPowerOf2())
1647 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1648 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1649 if (*XorC == C && (C + 1).isPowerOf2())
1650 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1651 }
1652 if (Pred == ICmpInst::ICMP_ULT) {
1653 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1654 if (*XorC == -C && C.isPowerOf2())
1655 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1656 ConstantInt::get(X->getType(), ~C));
1657 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1658 if (*XorC == C && (-C).isPowerOf2())
1659 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1660 ConstantInt::get(X->getType(), ~C));
1661 }
1662 return nullptr;
1663}
1664
1665/// For power-of-2 C:
1666/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1667/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1670 const APInt &C) {
1671 CmpInst::Predicate Pred = Cmp.getPredicate();
1672 APInt PowerOf2;
1673 if (Pred == ICmpInst::ICMP_ULT)
1674 PowerOf2 = C;
1675 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1676 PowerOf2 = C + 1;
1677 else
1678 return nullptr;
1679 if (!PowerOf2.isPowerOf2())
1680 return nullptr;
1681 Value *X;
1682 const APInt *ShiftC;
1684 m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1685 return nullptr;
1686 uint64_t Shift = ShiftC->getLimitedValue();
1687 Type *XType = X->getType();
1688 if (Shift == 0 || PowerOf2.isMinSignedValue())
1689 return nullptr;
1690 Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1691 APInt Bound =
1692 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1693 return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1694}
1695
1696/// Fold icmp (and (sh X, Y), C2), C1.
1699 const APInt &C1,
1700 const APInt &C2) {
1701 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1702 if (!Shift || !Shift->isShift())
1703 return nullptr;
1704
1705 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1706 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1707 // code produced by the clang front-end, for bitfield access.
1708 // This seemingly simple opportunity to fold away a shift turns out to be
1709 // rather complicated. See PR17827 for details.
1710 unsigned ShiftOpcode = Shift->getOpcode();
1711 bool IsShl = ShiftOpcode == Instruction::Shl;
1712 const APInt *C3;
1713 if (match(Shift->getOperand(1), m_APInt(C3))) {
1714 APInt NewAndCst, NewCmpCst;
1715 bool AnyCmpCstBitsShiftedOut;
1716 if (ShiftOpcode == Instruction::Shl) {
1717 // For a left shift, we can fold if the comparison is not signed. We can
1718 // also fold a signed comparison if the mask value and comparison value
1719 // are not negative. These constraints may not be obvious, but we can
1720 // prove that they are correct using an SMT solver.
1721 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1722 return nullptr;
1723
1724 NewCmpCst = C1.lshr(*C3);
1725 NewAndCst = C2.lshr(*C3);
1726 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1727 } else if (ShiftOpcode == Instruction::LShr) {
1728 // For a logical right shift, we can fold if the comparison is not signed.
1729 // We can also fold a signed comparison if the shifted mask value and the
1730 // shifted comparison value are not negative. These constraints may not be
1731 // obvious, but we can prove that they are correct using an SMT solver.
1732 NewCmpCst = C1.shl(*C3);
1733 NewAndCst = C2.shl(*C3);
1734 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1735 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1736 return nullptr;
1737 } else {
1738 // For an arithmetic shift, check that both constants don't use (in a
1739 // signed sense) the top bits being shifted out.
1740 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1741 NewCmpCst = C1.shl(*C3);
1742 NewAndCst = C2.shl(*C3);
1743 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1744 if (NewAndCst.ashr(*C3) != C2)
1745 return nullptr;
1746 }
1747
1748 if (AnyCmpCstBitsShiftedOut) {
1749 // If we shifted bits out, the fold is not going to work out. As a
1750 // special case, check to see if this means that the result is always
1751 // true or false now.
1752 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1753 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1754 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1755 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1756 } else {
1757 Value *NewAnd = Builder.CreateAnd(
1758 Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1759 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1760 ConstantInt::get(And->getType(), NewCmpCst));
1761 }
1762 }
1763
1764 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1765 // preferable because it allows the C2 << Y expression to be hoisted out of a
1766 // loop if Y is invariant and X is not.
1767 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1768 !Shift->isArithmeticShift() &&
1769 ((!IsShl && C2.isOne()) || !isa<Constant>(Shift->getOperand(0)))) {
1770 // Compute C2 << Y.
1771 Value *NewShift =
1772 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1773 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1774
1775 // Compute X & (C2 << Y).
1776 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1777 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1778 }
1779
1780 return nullptr;
1781}
1782
1783/// Fold icmp (and X, C2), C1.
1786 const APInt &C1) {
1787 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1788
1789 // icmp ne (and X, 1), 0 --> trunc X to i1
1790 if (isICMP_NE && C1.isZero() && match(And->getOperand(1), m_One()))
1791 return new TruncInst(And->getOperand(0), Cmp.getType());
1792
1793 const APInt *C2;
1794 Value *X;
1795 if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1796 return nullptr;
1797
1798 // (and X, highmask) s> [0, ~highmask] --> X s> ~highmask
1799 if (Cmp.getPredicate() == ICmpInst::ICMP_SGT && C1.ule(~*C2) &&
1800 C2->isNegatedPowerOf2())
1801 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1802 ConstantInt::get(X->getType(), ~*C2));
1803 // (and X, highmask) s< [1, -highmask] --> X s< -highmask
1804 if (Cmp.getPredicate() == ICmpInst::ICMP_SLT && !C1.isSignMask() &&
1805 (C1 - 1).ule(~*C2) && C2->isNegatedPowerOf2() && !C2->isSignMask())
1806 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1807 ConstantInt::get(X->getType(), -*C2));
1808
1809 // Don't perform the following transforms if the AND has multiple uses
1810 if (!And->hasOneUse())
1811 return nullptr;
1812
1813 if (Cmp.isEquality() && C1.isZero()) {
1814 // Restrict this fold to single-use 'and' (PR10267).
1815 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1816 if (C2->isSignMask()) {
1817 Constant *Zero = Constant::getNullValue(X->getType());
1818 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1819 return new ICmpInst(NewPred, X, Zero);
1820 }
1821
1822 APInt NewC2 = *C2;
1823 KnownBits Know = computeKnownBits(And->getOperand(0), And);
1824 // Set high zeros of C2 to allow matching negated power-of-2.
1825 NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
1826 Know.countMinLeadingZeros());
1827
1828 // Restrict this fold only for single-use 'and' (PR10267).
1829 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1830 if (NewC2.isNegatedPowerOf2()) {
1831 Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1832 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1833 return new ICmpInst(NewPred, X, NegBOC);
1834 }
1835 }
1836
1837 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1838 // the input width without changing the value produced, eliminate the cast:
1839 //
1840 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1841 //
1842 // We can do this transformation if the constants do not have their sign bits
1843 // set or if it is an equality comparison. Extending a relational comparison
1844 // when we're checking the sign bit would not work.
1845 Value *W;
1846 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1847 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1848 // TODO: Is this a good transform for vectors? Wider types may reduce
1849 // throughput. Should this transform be limited (even for scalars) by using
1850 // shouldChangeType()?
1851 if (!Cmp.getType()->isVectorTy()) {
1852 Type *WideType = W->getType();
1853 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1854 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1855 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1856 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1857 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1858 }
1859 }
1860
1861 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1862 return I;
1863
1864 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1865 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1866 //
1867 // iff pred isn't signed
1868 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1869 match(And->getOperand(1), m_One())) {
1870 Constant *One = cast<Constant>(And->getOperand(1));
1871 Value *Or = And->getOperand(0);
1872 Value *A, *B, *LShr;
1873 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1874 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1875 unsigned UsesRemoved = 0;
1876 if (And->hasOneUse())
1877 ++UsesRemoved;
1878 if (Or->hasOneUse())
1879 ++UsesRemoved;
1880 if (LShr->hasOneUse())
1881 ++UsesRemoved;
1882
1883 // Compute A & ((1 << B) | 1)
1884 unsigned RequireUsesRemoved = match(B, m_ImmConstant()) ? 1 : 3;
1885 if (UsesRemoved >= RequireUsesRemoved) {
1886 Value *NewOr =
1887 Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1888 /*HasNUW=*/true),
1889 One, Or->getName());
1890 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1891 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1892 }
1893 }
1894 }
1895
1896 // (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->
1897 // llvm.is.fpclass(X, fcInf|fcNan)
1898 // (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->
1899 // llvm.is.fpclass(X, ~(fcInf|fcNan))
1900 // (icmp eq (and (bitcast X to int), ExponentMask), 0) -->
1901 // llvm.is.fpclass(X, fcSubnormal|fcZero)
1902 // (icmp ne (and (bitcast X to int), ExponentMask), 0) -->
1903 // llvm.is.fpclass(X, ~(fcSubnormal|fcZero))
1904 Value *V;
1905 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1906 Attribute::NoImplicitFloat) &&
1907 Cmp.isEquality() &&
1909 Type *FPType = V->getType()->getScalarType();
1910 if (FPType->isIEEELikeFPTy() && (C1.isZero() || C1 == *C2)) {
1911 APInt ExponentMask =
1912 APFloat::getInf(FPType->getFltSemantics()).bitcastToAPInt();
1913 if (*C2 == ExponentMask) {
1914 unsigned Mask = C1.isZero()
1917 if (isICMP_NE)
1918 Mask = ~Mask & fcAllFlags;
1919 return replaceInstUsesWith(Cmp, Builder.createIsFPClass(V, Mask));
1920 }
1921 }
1922 }
1923
1924 return nullptr;
1925}
1926
1927/// Fold icmp (and X, Y), C.
1930 const APInt &C) {
1931 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1932 return I;
1933
1934 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1935 bool TrueIfNeg;
1936 if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1937 // ((X - 1) & ~X) < 0 --> X == 0
1938 // ((X - 1) & ~X) >= 0 --> X != 0
1939 Value *X;
1940 if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1941 match(And->getOperand(1), m_Not(m_Specific(X)))) {
1942 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1943 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1944 }
1945 // (X & -X) < 0 --> X == MinSignedC
1946 // (X & -X) > -1 --> X != MinSignedC
1947 if (match(And, m_c_And(m_Neg(m_Value(X)), m_Deferred(X)))) {
1948 Constant *MinSignedC = ConstantInt::get(
1949 X->getType(),
1950 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits()));
1951 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1952 return new ICmpInst(NewPred, X, MinSignedC);
1953 }
1954 }
1955
1956 // TODO: These all require that Y is constant too, so refactor with the above.
1957
1958 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1959 Value *X = And->getOperand(0);
1960 Value *Y = And->getOperand(1);
1961 if (auto *C2 = dyn_cast<ConstantInt>(Y))
1962 if (auto *LI = dyn_cast<LoadInst>(X))
1963 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1964 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(LI, GEP, Cmp, C2))
1965 return Res;
1966
1967 if (!Cmp.isEquality())
1968 return nullptr;
1969
1970 // X & -C == -C -> X > u ~C
1971 // X & -C != -C -> X <= u ~C
1972 // iff C is a power of 2
1973 if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
1974 auto NewPred =
1976 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1977 }
1978
1979 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
1980 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
1981 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
1982 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
1984 X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
1985 Value *TruncY = Builder.CreateTrunc(Y, X->getType());
1986 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
1987 Value *And = Builder.CreateAnd(TruncY, X);
1989 }
1990 return BinaryOperator::CreateAnd(TruncY, X);
1991 }
1992
1993 // (icmp eq/ne (and (shl -1, X), Y), 0)
1994 // -> (icmp eq/ne (lshr Y, X), 0)
1995 // We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems
1996 // highly unlikely the non-zero case will ever show up in code.
1997 if (C.isZero() &&
1999 m_Value(Y))))) {
2000 Value *LShr = Builder.CreateLShr(Y, X);
2001 return new ICmpInst(Pred, LShr, Constant::getNullValue(LShr->getType()));
2002 }
2003
2004 // (icmp eq/ne (and (add A, Addend), Msk), C)
2005 // -> (icmp eq/ne (and A, Msk), (and (sub C, Addend), Msk))
2006 {
2007 Value *A;
2008 const APInt *Addend, *Msk;
2010 m_LowBitMask(Msk)))) &&
2011 C.ule(*Msk)) {
2012 APInt NewComperand = (C - *Addend) & *Msk;
2013 Value *MaskA = Builder.CreateAnd(A, ConstantInt::get(A->getType(), *Msk));
2014 return new ICmpInst(Pred, MaskA,
2015 ConstantInt::get(MaskA->getType(), NewComperand));
2016 }
2017 }
2018
2019 return nullptr;
2020}
2021
2022/// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
2024 InstCombiner::BuilderTy &Builder) {
2025 // Are we using xors or subs to bitwise check for a pair or pairs of
2026 // (in)equalities? Convert to a shorter form that has more potential to be
2027 // folded even further.
2028 // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
2029 // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
2030 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
2031 // (X1 == X2) && (X3 == X4) && (X5 == X6)
2032 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
2033 // (X1 != X2) || (X3 != X4) || (X5 != X6)
2035 SmallVector<Value *, 16> WorkList(1, Or);
2036
2037 while (!WorkList.empty()) {
2038 auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
2039 Value *Lhs, *Rhs;
2040
2041 if (match(OrOperatorArgument,
2042 m_OneUse(m_Xor(m_Value(Lhs), m_Value(Rhs))))) {
2043 CmpValues.emplace_back(Lhs, Rhs);
2044 return;
2045 }
2046
2047 if (match(OrOperatorArgument,
2048 m_OneUse(m_Sub(m_Value(Lhs), m_Value(Rhs))))) {
2049 CmpValues.emplace_back(Lhs, Rhs);
2050 return;
2051 }
2052
2053 WorkList.push_back(OrOperatorArgument);
2054 };
2055
2056 Value *CurrentValue = WorkList.pop_back_val();
2057 Value *OrOperatorLhs, *OrOperatorRhs;
2058
2059 if (!match(CurrentValue,
2060 m_Or(m_Value(OrOperatorLhs), m_Value(OrOperatorRhs)))) {
2061 return nullptr;
2062 }
2063
2064 MatchOrOperatorArgument(OrOperatorRhs);
2065 MatchOrOperatorArgument(OrOperatorLhs);
2066 }
2067
2068 ICmpInst::Predicate Pred = Cmp.getPredicate();
2069 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2070 Value *LhsCmp = Builder.CreateICmp(Pred, CmpValues.rbegin()->first,
2071 CmpValues.rbegin()->second);
2072
2073 for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
2074 Value *RhsCmp = Builder.CreateICmp(Pred, It->first, It->second);
2075 LhsCmp = Builder.CreateBinOp(BOpc, LhsCmp, RhsCmp);
2076 }
2077
2078 return LhsCmp;
2079}
2080
2081/// Fold icmp (or X, Y), C.
2084 const APInt &C) {
2085 ICmpInst::Predicate Pred = Cmp.getPredicate();
2086 if (C.isOne()) {
2087 // icmp slt signum(V) 1 --> icmp slt V, 1
2088 Value *V = nullptr;
2089 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
2090 return new ICmpInst(ICmpInst::ICMP_SLT, V,
2091 ConstantInt::get(V->getType(), 1));
2092 }
2093
2094 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
2095
2096 // (icmp eq/ne (or disjoint x, C0), C1)
2097 // -> (icmp eq/ne x, C0^C1)
2098 if (Cmp.isEquality() && match(OrOp1, m_ImmConstant()) &&
2099 cast<PossiblyDisjointInst>(Or)->isDisjoint()) {
2100 Value *NewC =
2101 Builder.CreateXor(OrOp1, ConstantInt::get(OrOp1->getType(), C));
2102 return new ICmpInst(Pred, OrOp0, NewC);
2103 }
2104
2105 const APInt *MaskC;
2106 if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
2107 if (*MaskC == C && (C + 1).isPowerOf2()) {
2108 // X | C == C --> X <=u C
2109 // X | C != C --> X >u C
2110 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
2112 return new ICmpInst(Pred, OrOp0, OrOp1);
2113 }
2114
2115 // More general: canonicalize 'equality with set bits mask' to
2116 // 'equality with clear bits mask'.
2117 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2118 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2119 if (Or->hasOneUse()) {
2120 Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
2121 Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
2122 return new ICmpInst(Pred, And, NewC);
2123 }
2124 }
2125
2126 // (X | (X-1)) s< 0 --> X s< 1
2127 // (X | (X-1)) s> -1 --> X s> 0
2128 Value *X;
2129 bool TrueIfSigned;
2130 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
2132 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2133 Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
2134 return new ICmpInst(NewPred, X, NewC);
2135 }
2136
2137 const APInt *OrC;
2138 // icmp(X | OrC, C) --> icmp(X, 0)
2139 if (C.isNonNegative() && match(Or, m_Or(m_Value(X), m_APInt(OrC)))) {
2140 switch (Pred) {
2141 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2142 case ICmpInst::ICMP_SLT:
2143 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2144 case ICmpInst::ICMP_SGE:
2145 if (OrC->sge(C))
2146 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2147 break;
2148 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2149 case ICmpInst::ICMP_SLE:
2150 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2151 case ICmpInst::ICMP_SGT:
2152 if (OrC->sgt(C))
2154 ConstantInt::getNullValue(X->getType()));
2155 break;
2156 default:
2157 break;
2158 }
2159 }
2160
2161 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2162 return nullptr;
2163
2164 Value *P, *Q;
2166 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2167 // -> and (icmp eq P, null), (icmp eq Q, null).
2168 Value *CmpP =
2169 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
2170 Value *CmpQ =
2171 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
2172 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2173 return BinaryOperator::Create(BOpc, CmpP, CmpQ);
2174 }
2175
2176 if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2177 return replaceInstUsesWith(Cmp, V);
2178
2179 return nullptr;
2180}
2181
2182/// Fold icmp (mul X, Y), C.
2185 const APInt &C) {
2186 ICmpInst::Predicate Pred = Cmp.getPredicate();
2187 Type *MulTy = Mul->getType();
2188 Value *X = Mul->getOperand(0);
2189
2190 // If there's no overflow:
2191 // X * X == 0 --> X == 0
2192 // X * X != 0 --> X != 0
2193 if (Cmp.isEquality() && C.isZero() && X == Mul->getOperand(1) &&
2194 (Mul->hasNoUnsignedWrap() || Mul->hasNoSignedWrap()))
2195 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2196
2197 const APInt *MulC;
2198 if (!match(Mul->getOperand(1), m_APInt(MulC)))
2199 return nullptr;
2200
2201 // If this is a test of the sign bit and the multiply is sign-preserving with
2202 // a constant operand, use the multiply LHS operand instead:
2203 // (X * +MulC) < 0 --> X < 0
2204 // (X * -MulC) < 0 --> X > 0
2205 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2206 if (MulC->isNegative())
2207 Pred = ICmpInst::getSwappedPredicate(Pred);
2208 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2209 }
2210
2211 if (MulC->isZero())
2212 return nullptr;
2213
2214 // If the multiply does not wrap or the constant is odd, try to divide the
2215 // compare constant by the multiplication factor.
2216 if (Cmp.isEquality()) {
2217 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2218 if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
2219 Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
2220 return new ICmpInst(Pred, X, NewC);
2221 }
2222
2223 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2224 // correct to transform if MulC * N == C including overflow. I.e with i8
2225 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2226 // miss that case.
2227 if (C.urem(*MulC).isZero()) {
2228 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2229 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2230 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2231 Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
2232 return new ICmpInst(Pred, X, NewC);
2233 }
2234 }
2235 }
2236
2237 // With a matching no-overflow guarantee, fold the constants:
2238 // (X * MulC) < C --> X < (C / MulC)
2239 // (X * MulC) > C --> X > (C / MulC)
2240 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2241 Constant *NewC = nullptr;
2242 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2243 // MININT / -1 --> overflow.
2244 if (C.isMinSignedValue() && MulC->isAllOnes())
2245 return nullptr;
2246 if (MulC->isNegative())
2247 Pred = ICmpInst::getSwappedPredicate(Pred);
2248
2249 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2250 NewC = ConstantInt::get(
2252 } else {
2253 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2254 "Unexpected predicate");
2255 NewC = ConstantInt::get(
2257 }
2258 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2259 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2260 NewC = ConstantInt::get(
2262 } else {
2263 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2264 "Unexpected predicate");
2265 NewC = ConstantInt::get(
2267 }
2268 }
2269
2270 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2271}
2272
2273/// Fold icmp (shl nuw C2, Y), C.
2275 const APInt &C) {
2276 Value *Y;
2277 const APInt *C2;
2278 if (!match(Shl, m_NUWShl(m_APInt(C2), m_Value(Y))))
2279 return nullptr;
2280
2281 Type *ShiftType = Shl->getType();
2282 unsigned TypeBits = C.getBitWidth();
2283 ICmpInst::Predicate Pred = Cmp.getPredicate();
2284 if (Cmp.isUnsigned()) {
2285 if (C2->isZero() || C2->ugt(C))
2286 return nullptr;
2287 APInt Div, Rem;
2288 APInt::udivrem(C, *C2, Div, Rem);
2289 bool CIsPowerOf2 = Rem.isZero() && Div.isPowerOf2();
2290
2291 // (1 << Y) pred C -> Y pred Log2(C)
2292 if (!CIsPowerOf2) {
2293 // (1 << Y) < 30 -> Y <= 4
2294 // (1 << Y) <= 30 -> Y <= 4
2295 // (1 << Y) >= 30 -> Y > 4
2296 // (1 << Y) > 30 -> Y > 4
2297 if (Pred == ICmpInst::ICMP_ULT)
2298 Pred = ICmpInst::ICMP_ULE;
2299 else if (Pred == ICmpInst::ICMP_UGE)
2300 Pred = ICmpInst::ICMP_UGT;
2301 }
2302
2303 unsigned CLog2 = Div.logBase2();
2304 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2305 } else if (Cmp.isSigned() && C2->isOne()) {
2306 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2307 // (1 << Y) > 0 -> Y != 31
2308 // (1 << Y) > C -> Y != 31 if C is negative.
2309 if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
2310 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2311
2312 // (1 << Y) < 0 -> Y == 31
2313 // (1 << Y) < 1 -> Y == 31
2314 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2315 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2316 if (Pred == ICmpInst::ICMP_SLT && (C - 1).sle(0))
2317 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2318 }
2319
2320 return nullptr;
2321}
2322
2323/// Fold icmp (shl X, Y), C.
2325 BinaryOperator *Shl,
2326 const APInt &C) {
2327 const APInt *ShiftVal;
2328 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2329 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2330
2331 ICmpInst::Predicate Pred = Cmp.getPredicate();
2332 // (icmp pred (shl nuw&nsw X, Y), Csle0)
2333 // -> (icmp pred X, Csle0)
2334 //
2335 // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2336 // so X's must be what is used.
2337 if (C.sle(0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2338 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2339
2340 // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2341 // -> (icmp eq/ne X, 0)
2342 if (ICmpInst::isEquality(Pred) && C.isZero() &&
2343 (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2344 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2345
2346 // (icmp slt (shl nsw X, Y), 0/1)
2347 // -> (icmp slt X, 0/1)
2348 // (icmp sgt (shl nsw X, Y), 0/-1)
2349 // -> (icmp sgt X, 0/-1)
2350 //
2351 // NB: sge/sle with a constant will canonicalize to sgt/slt.
2352 if (Shl->hasNoSignedWrap() &&
2353 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2354 if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2355 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2356
2357 const APInt *ShiftAmt;
2358 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2359 return foldICmpShlLHSC(Cmp, Shl, C);
2360
2361 // Check that the shift amount is in range. If not, don't perform undefined
2362 // shifts. When the shift is visited, it will be simplified.
2363 unsigned TypeBits = C.getBitWidth();
2364 if (ShiftAmt->uge(TypeBits))
2365 return nullptr;
2366
2367 Value *X = Shl->getOperand(0);
2368 Type *ShType = Shl->getType();
2369
2370 // NSW guarantees that we are only shifting out sign bits from the high bits,
2371 // so we can ASHR the compare constant without needing a mask and eliminate
2372 // the shift.
2373 if (Shl->hasNoSignedWrap()) {
2374 if (Pred == ICmpInst::ICMP_SGT) {
2375 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2376 APInt ShiftedC = C.ashr(*ShiftAmt);
2377 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2378 }
2379 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2380 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2381 APInt ShiftedC = C.ashr(*ShiftAmt);
2382 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2383 }
2384 if (Pred == ICmpInst::ICMP_SLT) {
2385 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2386 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2387 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2388 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2389 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2390 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2391 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2392 }
2393 }
2394
2395 // NUW guarantees that we are only shifting out zero bits from the high bits,
2396 // so we can LSHR the compare constant without needing a mask and eliminate
2397 // the shift.
2398 if (Shl->hasNoUnsignedWrap()) {
2399 if (Pred == ICmpInst::ICMP_UGT) {
2400 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2401 APInt ShiftedC = C.lshr(*ShiftAmt);
2402 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2403 }
2404 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2405 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2406 APInt ShiftedC = C.lshr(*ShiftAmt);
2407 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2408 }
2409 if (Pred == ICmpInst::ICMP_ULT) {
2410 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2411 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2412 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2413 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2414 assert(C.ugt(0) && "ult 0 should have been eliminated");
2415 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2416 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2417 }
2418 }
2419
2420 if (Cmp.isEquality() && Shl->hasOneUse()) {
2421 // Strength-reduce the shift into an 'and'.
2422 Constant *Mask = ConstantInt::get(
2423 ShType,
2424 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2425 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2426 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2427 return new ICmpInst(Pred, And, LShrC);
2428 }
2429
2430 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2431 bool TrueIfSigned = false;
2432 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2433 // (X << 31) <s 0 --> (X & 1) != 0
2434 Constant *Mask = ConstantInt::get(
2435 ShType,
2436 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2437 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2438 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2439 And, Constant::getNullValue(ShType));
2440 }
2441
2442 // Simplify 'shl' inequality test into 'and' equality test.
2443 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2444 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2445 if ((C + 1).isPowerOf2() &&
2446 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2447 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2448 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2450 And, Constant::getNullValue(ShType));
2451 }
2452 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2453 if (C.isPowerOf2() &&
2454 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2455 Value *And =
2456 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2457 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2459 And, Constant::getNullValue(ShType));
2460 }
2461 }
2462
2463 // Transform (icmp pred iM (shl iM %v, N), C)
2464 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2465 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2466 // This enables us to get rid of the shift in favor of a trunc that may be
2467 // free on the target. It has the additional benefit of comparing to a
2468 // smaller constant that may be more target-friendly.
2469 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2470 if (Shl->hasOneUse() && Amt != 0 &&
2471 shouldChangeType(ShType->getScalarSizeInBits(), TypeBits - Amt)) {
2472 ICmpInst::Predicate CmpPred = Pred;
2473 APInt RHSC = C;
2474
2475 if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(CmpPred)) {
2476 // Try the flipped strictness predicate.
2477 // e.g.:
2478 // icmp ult i64 (shl X, 32), 8589934593 ->
2479 // icmp ule i64 (shl X, 32), 8589934592 ->
2480 // icmp ule i32 (trunc X, i32), 2 ->
2481 // icmp ult i32 (trunc X, i32), 3
2482 if (auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(
2483 Pred, ConstantInt::get(ShType->getContext(), C))) {
2484 CmpPred = FlippedStrictness->first;
2485 RHSC = cast<ConstantInt>(FlippedStrictness->second)->getValue();
2486 }
2487 }
2488
2489 if (RHSC.countr_zero() >= Amt) {
2490 Type *TruncTy = ShType->getWithNewBitWidth(TypeBits - Amt);
2491 Constant *NewC =
2492 ConstantInt::get(TruncTy, RHSC.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2493 return new ICmpInst(CmpPred,
2494 Builder.CreateTrunc(X, TruncTy, "", /*IsNUW=*/false,
2495 Shl->hasNoSignedWrap()),
2496 NewC);
2497 }
2498 }
2499
2500 return nullptr;
2501}
2502
2503/// Fold icmp ({al}shr X, Y), C.
2505 BinaryOperator *Shr,
2506 const APInt &C) {
2507 // An exact shr only shifts out zero bits, so:
2508 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2509 Value *X = Shr->getOperand(0);
2510 CmpInst::Predicate Pred = Cmp.getPredicate();
2511 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2512 return new ICmpInst(Pred, X, Cmp.getOperand(1));
2513
2514 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2515 const APInt *ShiftValC;
2516 if (match(X, m_APInt(ShiftValC))) {
2517 if (Cmp.isEquality())
2518 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2519
2520 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2521 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2522 bool TrueIfSigned;
2523 if (!IsAShr && ShiftValC->isNegative() &&
2524 isSignBitCheck(Pred, C, TrueIfSigned))
2525 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2526 Shr->getOperand(1),
2527 ConstantInt::getNullValue(X->getType()));
2528
2529 // If the shifted constant is a power-of-2, test the shift amount directly:
2530 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2531 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2532 if (!IsAShr && ShiftValC->isPowerOf2() &&
2533 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2534 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2535 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2536 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2537
2538 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2539 unsigned ShiftLZ = ShiftValC->countl_zero();
2540 Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2541 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2542 return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2543 }
2544 }
2545
2546 const APInt *ShiftAmtC;
2547 if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2548 return nullptr;
2549
2550 // Check that the shift amount is in range. If not, don't perform undefined
2551 // shifts. When the shift is visited it will be simplified.
2552 unsigned TypeBits = C.getBitWidth();
2553 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2554 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2555 return nullptr;
2556
2557 bool IsExact = Shr->isExact();
2558 Type *ShrTy = Shr->getType();
2559 // TODO: If we could guarantee that InstSimplify would handle all of the
2560 // constant-value-based preconditions in the folds below, then we could assert
2561 // those conditions rather than checking them. This is difficult because of
2562 // undef/poison (PR34838).
2563 if (IsAShr && Shr->hasOneUse()) {
2564 if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&
2565 (C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {
2566 // When C - 1 is a power of two and the transform can be legally
2567 // performed, prefer this form so the produced constant is close to a
2568 // power of two.
2569 // icmp slt/ult (ashr exact X, ShAmtC), C
2570 // --> icmp slt/ult X, (C - 1) << ShAmtC) + 1
2571 APInt ShiftedC = (C - 1).shl(ShAmtVal) + 1;
2572 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2573 }
2574 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2575 // When ShAmtC can be shifted losslessly:
2576 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2577 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2578 APInt ShiftedC = C.shl(ShAmtVal);
2579 if (ShiftedC.ashr(ShAmtVal) == C)
2580 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2581 }
2582 if (Pred == CmpInst::ICMP_SGT) {
2583 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2584 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2585 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2586 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2587 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2588 }
2589 if (Pred == CmpInst::ICMP_UGT) {
2590 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2591 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2592 // clause accounts for that pattern.
2593 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2594 if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2595 (C + 1).shl(ShAmtVal).isMinSignedValue())
2596 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2597 }
2598
2599 // If the compare constant has significant bits above the lowest sign-bit,
2600 // then convert an unsigned cmp to a test of the sign-bit:
2601 // (ashr X, ShiftC) u> C --> X s< 0
2602 // (ashr X, ShiftC) u< C --> X s> -1
2603 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2604 if (Pred == CmpInst::ICMP_UGT) {
2605 return new ICmpInst(CmpInst::ICMP_SLT, X,
2607 }
2608 if (Pred == CmpInst::ICMP_ULT) {
2609 return new ICmpInst(CmpInst::ICMP_SGT, X,
2611 }
2612 }
2613 } else if (!IsAShr) {
2614 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2615 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2616 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2617 APInt ShiftedC = C.shl(ShAmtVal);
2618 if (ShiftedC.lshr(ShAmtVal) == C)
2619 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2620 }
2621 if (Pred == CmpInst::ICMP_UGT) {
2622 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2623 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2624 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2625 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2626 }
2627 }
2628
2629 if (!Cmp.isEquality())
2630 return nullptr;
2631
2632 // Handle equality comparisons of shift-by-constant.
2633
2634 // If the comparison constant changes with the shift, the comparison cannot
2635 // succeed (bits of the comparison constant cannot match the shifted value).
2636 // This should be known by InstSimplify and already be folded to true/false.
2637 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2638 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2639 "Expected icmp+shr simplify did not occur.");
2640
2641 // If the bits shifted out are known zero, compare the unshifted value:
2642 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2643 if (Shr->isExact())
2644 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2645
2646 if (Shr->hasOneUse()) {
2647 // Canonicalize the shift into an 'and':
2648 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2649 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2650 Constant *Mask = ConstantInt::get(ShrTy, Val);
2651 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2652 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2653 }
2654
2655 return nullptr;
2656}
2657
2659 BinaryOperator *SRem,
2660 const APInt &C) {
2661 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2662 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT) {
2663 // Canonicalize unsigned predicates to signed:
2664 // (X s% DivisorC) u> C -> (X s% DivisorC) s< 0
2665 // iff (C s< 0 ? ~C : C) u>= abs(DivisorC)-1
2666 // (X s% DivisorC) u< C+1 -> (X s% DivisorC) s> -1
2667 // iff (C+1 s< 0 ? ~C : C) u>= abs(DivisorC)-1
2668
2669 const APInt *DivisorC;
2670 if (!match(SRem->getOperand(1), m_APInt(DivisorC)))
2671 return nullptr;
2672 if (DivisorC->isZero())
2673 return nullptr;
2674
2675 APInt NormalizedC = C;
2676 if (Pred == ICmpInst::ICMP_ULT) {
2677 assert(!NormalizedC.isZero() &&
2678 "ult X, 0 should have been simplified already.");
2679 --NormalizedC;
2680 }
2681 if (C.isNegative())
2682 NormalizedC.flipAllBits();
2683 if (!NormalizedC.uge(DivisorC->abs() - 1))
2684 return nullptr;
2685
2686 Type *Ty = SRem->getType();
2687 if (Pred == ICmpInst::ICMP_UGT)
2688 return new ICmpInst(ICmpInst::ICMP_SLT, SRem,
2690 return new ICmpInst(ICmpInst::ICMP_SGT, SRem,
2692 }
2693 // Match an 'is positive' or 'is negative' comparison of remainder by a
2694 // constant power-of-2 value:
2695 // (X % pow2C) sgt/slt 0
2696 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2697 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2698 return nullptr;
2699
2700 // TODO: The one-use check is standard because we do not typically want to
2701 // create longer instruction sequences, but this might be a special-case
2702 // because srem is not good for analysis or codegen.
2703 if (!SRem->hasOneUse())
2704 return nullptr;
2705
2706 const APInt *DivisorC;
2707 if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2708 return nullptr;
2709
2710 // For cmp_sgt/cmp_slt only zero valued C is handled.
2711 // For cmp_eq/cmp_ne only positive valued C is handled.
2712 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2713 !C.isZero()) ||
2714 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2715 !C.isStrictlyPositive()))
2716 return nullptr;
2717
2718 // Mask off the sign bit and the modulo bits (low-bits).
2719 Type *Ty = SRem->getType();
2720 APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
2721 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2722 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2723
2724 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2725 return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2726
2727 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2728 // bit is set. Example:
2729 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2730 if (Pred == ICmpInst::ICMP_SGT)
2732
2733 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2734 // bit is set. Example:
2735 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2736 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2737}
2738
2739/// Fold icmp (udiv X, Y), C.
2741 BinaryOperator *UDiv,
2742 const APInt &C) {
2743 ICmpInst::Predicate Pred = Cmp.getPredicate();
2744 Value *X = UDiv->getOperand(0);
2745 Value *Y = UDiv->getOperand(1);
2746 Type *Ty = UDiv->getType();
2747
2748 const APInt *C2;
2749 if (!match(X, m_APInt(C2)))
2750 return nullptr;
2751
2752 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2753
2754 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2755 if (Pred == ICmpInst::ICMP_UGT) {
2756 assert(!C.isMaxValue() &&
2757 "icmp ugt X, UINT_MAX should have been simplified already.");
2758 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2759 ConstantInt::get(Ty, C2->udiv(C + 1)));
2760 }
2761
2762 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2763 if (Pred == ICmpInst::ICMP_ULT) {
2764 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2765 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2766 ConstantInt::get(Ty, C2->udiv(C)));
2767 }
2768
2769 return nullptr;
2770}
2771
2772/// Fold icmp ({su}div X, Y), C.
2774 BinaryOperator *Div,
2775 const APInt &C) {
2776 ICmpInst::Predicate Pred = Cmp.getPredicate();
2777 Value *X = Div->getOperand(0);
2778 Value *Y = Div->getOperand(1);
2779 Type *Ty = Div->getType();
2780 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2781
2782 // If unsigned division and the compare constant is bigger than
2783 // UMAX/2 (negative), there's only one pair of values that satisfies an
2784 // equality check, so eliminate the division:
2785 // (X u/ Y) == C --> (X == C) && (Y == 1)
2786 // (X u/ Y) != C --> (X != C) || (Y != 1)
2787 // Similarly, if signed division and the compare constant is exactly SMIN:
2788 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2789 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2790 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2791 (!DivIsSigned || C.isMinSignedValue())) {
2792 Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2793 Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2794 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2795 return BinaryOperator::Create(Logic, XBig, YOne);
2796 }
2797
2798 // Fold: icmp pred ([us]div X, C2), C -> range test
2799 // Fold this div into the comparison, producing a range check.
2800 // Determine, based on the divide type, what the range is being
2801 // checked. If there is an overflow on the low or high side, remember
2802 // it, otherwise compute the range [low, hi) bounding the new value.
2803 // See: InsertRangeTest above for the kinds of replacements possible.
2804 const APInt *C2;
2805 if (!match(Y, m_APInt(C2)))
2806 return nullptr;
2807
2808 // FIXME: If the operand types don't match the type of the divide
2809 // then don't attempt this transform. The code below doesn't have the
2810 // logic to deal with a signed divide and an unsigned compare (and
2811 // vice versa). This is because (x /s C2) <s C produces different
2812 // results than (x /s C2) <u C or (x /u C2) <s C or even
2813 // (x /u C2) <u C. Simply casting the operands and result won't
2814 // work. :( The if statement below tests that condition and bails
2815 // if it finds it.
2816 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
2817 return nullptr;
2818
2819 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2820 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2821 // division-by-constant cases should be present, we can not assert that they
2822 // have happened before we reach this icmp instruction.
2823 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2824 return nullptr;
2825
2826 // Compute Prod = C * C2. We are essentially solving an equation of
2827 // form X / C2 = C. We solve for X by multiplying C2 and C.
2828 // By solving for X, we can turn this into a range check instead of computing
2829 // a divide.
2830 APInt Prod = C * *C2;
2831
2832 // Determine if the product overflows by seeing if the product is not equal to
2833 // the divide. Make sure we do the same kind of divide as in the LHS
2834 // instruction that we're folding.
2835 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2836
2837 // If the division is known to be exact, then there is no remainder from the
2838 // divide, so the covered range size is unit, otherwise it is the divisor.
2839 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2840
2841 // Figure out the interval that is being checked. For example, a comparison
2842 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2843 // Compute this interval based on the constants involved and the signedness of
2844 // the compare/divide. This computes a half-open interval, keeping track of
2845 // whether either value in the interval overflows. After analysis each
2846 // overflow variable is set to 0 if it's corresponding bound variable is valid
2847 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2848 int LoOverflow = 0, HiOverflow = 0;
2849 APInt LoBound, HiBound;
2850
2851 if (!DivIsSigned) { // udiv
2852 // e.g. X/5 op 3 --> [15, 20)
2853 LoBound = Prod;
2854 HiOverflow = LoOverflow = ProdOV;
2855 if (!HiOverflow) {
2856 // If this is not an exact divide, then many values in the range collapse
2857 // to the same result value.
2858 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2859 }
2860 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2861 if (C.isZero()) { // (X / pos) op 0
2862 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2863 LoBound = -(RangeSize - 1);
2864 HiBound = RangeSize;
2865 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2866 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2867 HiOverflow = LoOverflow = ProdOV;
2868 if (!HiOverflow)
2869 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2870 } else { // (X / pos) op neg
2871 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2872 HiBound = Prod + 1;
2873 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2874 if (!LoOverflow) {
2875 APInt DivNeg = -RangeSize;
2876 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2877 }
2878 }
2879 } else if (C2->isNegative()) { // Divisor is < 0.
2880 if (Div->isExact())
2881 RangeSize.negate();
2882 if (C.isZero()) { // (X / neg) op 0
2883 // e.g. X/-5 op 0 --> [-4, 5)
2884 LoBound = RangeSize + 1;
2885 HiBound = -RangeSize;
2886 if (HiBound == *C2) { // -INTMIN = INTMIN
2887 HiOverflow = 1; // [INTMIN+1, overflow)
2888 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2889 }
2890 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2891 // e.g. X/-5 op 3 --> [-19, -14)
2892 HiBound = Prod + 1;
2893 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2894 if (!LoOverflow)
2895 LoOverflow =
2896 addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
2897 } else { // (X / neg) op neg
2898 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2899 LoOverflow = HiOverflow = ProdOV;
2900 if (!HiOverflow)
2901 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2902 }
2903
2904 // Dividing by a negative swaps the condition. LT <-> GT
2905 Pred = ICmpInst::getSwappedPredicate(Pred);
2906 }
2907
2908 switch (Pred) {
2909 default:
2910 llvm_unreachable("Unhandled icmp predicate!");
2911 case ICmpInst::ICMP_EQ:
2912 if (LoOverflow && HiOverflow)
2913 return replaceInstUsesWith(Cmp, Builder.getFalse());
2914 if (HiOverflow)
2915 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2916 X, ConstantInt::get(Ty, LoBound));
2917 if (LoOverflow)
2918 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2919 X, ConstantInt::get(Ty, HiBound));
2920 return replaceInstUsesWith(
2921 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
2922 case ICmpInst::ICMP_NE:
2923 if (LoOverflow && HiOverflow)
2924 return replaceInstUsesWith(Cmp, Builder.getTrue());
2925 if (HiOverflow)
2926 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2927 X, ConstantInt::get(Ty, LoBound));
2928 if (LoOverflow)
2929 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2930 X, ConstantInt::get(Ty, HiBound));
2931 return replaceInstUsesWith(
2932 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
2933 case ICmpInst::ICMP_ULT:
2934 case ICmpInst::ICMP_SLT:
2935 if (LoOverflow == +1) // Low bound is greater than input range.
2936 return replaceInstUsesWith(Cmp, Builder.getTrue());
2937 if (LoOverflow == -1) // Low bound is less than input range.
2938 return replaceInstUsesWith(Cmp, Builder.getFalse());
2939 return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
2940 case ICmpInst::ICMP_UGT:
2941 case ICmpInst::ICMP_SGT:
2942 if (HiOverflow == +1) // High bound greater than input range.
2943 return replaceInstUsesWith(Cmp, Builder.getFalse());
2944 if (HiOverflow == -1) // High bound less than input range.
2945 return replaceInstUsesWith(Cmp, Builder.getTrue());
2946 if (Pred == ICmpInst::ICMP_UGT)
2947 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
2948 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
2949 }
2950
2951 return nullptr;
2952}
2953
2954/// Fold icmp (sub X, Y), C.
2957 const APInt &C) {
2958 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
2959 ICmpInst::Predicate Pred = Cmp.getPredicate();
2960 Type *Ty = Sub->getType();
2961
2962 // (SubC - Y) == C) --> Y == (SubC - C)
2963 // (SubC - Y) != C) --> Y != (SubC - C)
2964 Constant *SubC;
2965 if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
2966 return new ICmpInst(Pred, Y,
2967 ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C)));
2968 }
2969
2970 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
2971 const APInt *C2;
2972 APInt SubResult;
2973 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
2974 bool HasNSW = Sub->hasNoSignedWrap();
2975 bool HasNUW = Sub->hasNoUnsignedWrap();
2976 if (match(X, m_APInt(C2)) &&
2977 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
2978 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
2979 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
2980
2981 // X - Y == 0 --> X == Y.
2982 // X - Y != 0 --> X != Y.
2983 // TODO: We allow this with multiple uses as long as the other uses are not
2984 // in phis. The phi use check is guarding against a codegen regression
2985 // for a loop test. If the backend could undo this (and possibly
2986 // subsequent transforms), we would not need this hack.
2987 if (Cmp.isEquality() && C.isZero() &&
2988 none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
2989 return new ICmpInst(Pred, X, Y);
2990
2991 // The following transforms are only worth it if the only user of the subtract
2992 // is the icmp.
2993 // TODO: This is an artificial restriction for all of the transforms below
2994 // that only need a single replacement icmp. Can these use the phi test
2995 // like the transform above here?
2996 if (!Sub->hasOneUse())
2997 return nullptr;
2998
2999 if (Sub->hasNoSignedWrap()) {
3000 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
3001 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3002 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3003
3004 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
3005 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
3006 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3007
3008 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
3009 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
3010 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3011
3012 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
3013 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3014 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3015 }
3016
3017 if (!match(X, m_APInt(C2)))
3018 return nullptr;
3019
3020 // C2 - Y <u C -> (Y | (C - 1)) == C2
3021 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
3022 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
3023 (*C2 & (C - 1)) == (C - 1))
3024 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
3025
3026 // C2 - Y >u C -> (Y | C) != C2
3027 // iff C2 & C == C and C + 1 is a power of 2
3028 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
3029 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
3030
3031 // We have handled special cases that reduce.
3032 // Canonicalize any remaining sub to add as:
3033 // (C2 - Y) > C --> (Y + ~C2) < ~C
3034 Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
3035 HasNUW, HasNSW);
3036 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
3037}
3038
3039static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
3040 Value *Op1, IRBuilderBase &Builder,
3041 bool HasOneUse) {
3042 auto FoldConstant = [&](bool Val) {
3043 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3044 if (Op0->getType()->isVectorTy())
3046 cast<VectorType>(Op0->getType())->getElementCount(), Res);
3047 return Res;
3048 };
3049
3050 switch (Table.to_ulong()) {
3051 case 0: // 0 0 0 0
3052 return FoldConstant(false);
3053 case 1: // 0 0 0 1
3054 return HasOneUse ? Builder.CreateNot(Builder.CreateOr(Op0, Op1)) : nullptr;
3055 case 2: // 0 0 1 0
3056 return HasOneUse ? Builder.CreateAnd(Builder.CreateNot(Op0), Op1) : nullptr;
3057 case 3: // 0 0 1 1
3058 return Builder.CreateNot(Op0);
3059 case 4: // 0 1 0 0
3060 return HasOneUse ? Builder.CreateAnd(Op0, Builder.CreateNot(Op1)) : nullptr;
3061 case 5: // 0 1 0 1
3062 return Builder.CreateNot(Op1);
3063 case 6: // 0 1 1 0
3064 return Builder.CreateXor(Op0, Op1);
3065 case 7: // 0 1 1 1
3066 return HasOneUse ? Builder.CreateNot(Builder.CreateAnd(Op0, Op1)) : nullptr;
3067 case 8: // 1 0 0 0
3068 return Builder.CreateAnd(Op0, Op1);
3069 case 9: // 1 0 0 1
3070 return HasOneUse ? Builder.CreateNot(Builder.CreateXor(Op0, Op1)) : nullptr;
3071 case 10: // 1 0 1 0
3072 return Op1;
3073 case 11: // 1 0 1 1
3074 return HasOneUse ? Builder.CreateOr(Builder.CreateNot(Op0), Op1) : nullptr;
3075 case 12: // 1 1 0 0
3076 return Op0;
3077 case 13: // 1 1 0 1
3078 return HasOneUse ? Builder.CreateOr(Op0, Builder.CreateNot(Op1)) : nullptr;
3079 case 14: // 1 1 1 0
3080 return Builder.CreateOr(Op0, Op1);
3081 case 15: // 1 1 1 1
3082 return FoldConstant(true);
3083 default:
3084 llvm_unreachable("Invalid Operation");
3085 }
3086 return nullptr;
3087}
3088
3090 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3091 Value *A, *B;
3092 Constant *C1, *C2, *C3, *C4;
3093 if (!match(BO->getOperand(0),
3095 !match(BO->getOperand(1),
3097 Cmp.getType() != A->getType() || Cmp.getType() != B->getType())
3098 return nullptr;
3099
3100 std::bitset<4> Table;
3101 auto ComputeTable = [&](bool First, bool Second) -> std::optional<bool> {
3102 Constant *L = First ? C1 : C2;
3103 Constant *R = Second ? C3 : C4;
3104 if (auto *Res = ConstantFoldBinaryOpOperands(BO->getOpcode(), L, R, DL)) {
3105 auto *Val = Res->getType()->isVectorTy() ? Res->getSplatValue() : Res;
3106 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val))
3107 return ICmpInst::compare(CI->getValue(), C, Cmp.getPredicate());
3108 }
3109 return std::nullopt;
3110 };
3111
3112 for (unsigned I = 0; I < 4; ++I) {
3113 bool First = (I >> 1) & 1;
3114 bool Second = I & 1;
3115 if (auto Res = ComputeTable(First, Second))
3116 Table[I] = *Res;
3117 else
3118 return nullptr;
3119 }
3120
3121 // Synthesize optimal logic.
3122 if (auto *Cond = createLogicFromTable(Table, A, B, Builder, BO->hasOneUse()))
3123 return replaceInstUsesWith(Cmp, Cond);
3124 return nullptr;
3125}
3126
3127/// Fold icmp (add X, Y), C.
3130 const APInt &C) {
3131 Value *Y = Add->getOperand(1);
3132 Value *X = Add->getOperand(0);
3133 const CmpPredicate Pred = Cmp.getCmpPredicate();
3134
3135 // icmp ult (add nuw A, (lshr A, ShAmtC)), C --> icmp ult A, C
3136 // when C <= (1 << ShAmtC).
3137 const APInt *ShAmtC;
3138 Value *A;
3139 unsigned BitWidth = C.getBitWidth();
3140 if (Pred == ICmpInst::ICMP_ULT &&
3141 match(Add,
3142 m_c_NUWAdd(m_Value(A), m_LShr(m_Deferred(A), m_APInt(ShAmtC)))) &&
3143 ShAmtC->ult(BitWidth) &&
3144 C.ule(APInt::getOneBitSet(BitWidth, ShAmtC->getZExtValue())))
3145 return new ICmpInst(Pred, A, ConstantInt::get(A->getType(), C));
3146
3147 const APInt *C2;
3148 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
3149 return nullptr;
3150
3151 // Fold icmp pred (add X, C2), C.
3152 Type *Ty = Add->getType();
3153
3154 // If the add does not wrap, we can always adjust the compare by subtracting
3155 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3156 // have been canonicalized to SGT/SLT/UGT/ULT.
3157 if (Add->hasNoUnsignedWrap() &&
3158 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT)) {
3159 bool Overflow;
3160 APInt NewC = C.usub_ov(*C2, Overflow);
3161 // If there is overflow, the result must be true or false.
3162 if (!Overflow)
3163 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
3164 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
3165 }
3166
3167 CmpInst::Predicate ChosenPred = Pred.getPreferredSignedPredicate();
3168
3169 if (Add->hasNoSignedWrap() &&
3170 (ChosenPred == ICmpInst::ICMP_SGT || ChosenPred == ICmpInst::ICMP_SLT)) {
3171 bool Overflow;
3172 APInt NewC = C.ssub_ov(*C2, Overflow);
3173 if (!Overflow)
3174 // icmp samesign ugt/ult (add nsw X, C2), C
3175 // -> icmp sgt/slt X, (C - C2)
3176 return new ICmpInst(ChosenPred, X, ConstantInt::get(Ty, NewC));
3177 }
3178
3179 if (ICmpInst::isUnsigned(Pred) && Add->hasNoSignedWrap() &&
3180 C.isNonNegative() && (C - *C2).isNonNegative() &&
3181 computeConstantRange(X, /*ForSigned=*/true).add(*C2).isAllNonNegative())
3182 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), X,
3183 ConstantInt::get(Ty, C - *C2));
3184
3185 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
3186 const APInt &Upper = CR.getUpper();
3187 const APInt &Lower = CR.getLower();
3188 if (Cmp.isSigned()) {
3189 if (Lower.isSignMask())
3190 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
3191 if (Upper.isSignMask())
3192 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
3193 } else {
3194 if (Lower.isMinValue())
3195 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
3196 if (Upper.isMinValue())
3197 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
3198 }
3199
3200 // This set of folds is intentionally placed after folds that use no-wrapping
3201 // flags because those folds are likely better for later analysis/codegen.
3202 const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
3203 const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
3204
3205 // Fold compare with offset to opposite sign compare if it eliminates offset:
3206 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3207 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3208 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
3209
3210 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3211 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3212 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
3213
3214 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3215 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3216 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
3217
3218 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3219 if (Pred == CmpInst::ICMP_SLT && C == *C2)
3220 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
3221
3222 // (X + -1) <u C --> X <=u C (if X is never null)
3223 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3224 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3225 if (llvm::isKnownNonZero(X, Q))
3226 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
3227 }
3228
3229 if (!Add->hasOneUse())
3230 return nullptr;
3231
3232 // X+C <u C2 -> (X & -C2) == C
3233 // iff C & (C2-1) == 0
3234 // C2 is a power of 2
3235 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3236 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
3238
3239 // X+C2 <u C -> (X & C) == 2C
3240 // iff C == -(C2)
3241 // C2 is a power of 2
3242 if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)
3243 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, C),
3244 ConstantInt::get(Ty, C * 2));
3245
3246 // X+C >u C2 -> (X & ~C2) != C
3247 // iff C & C2 == 0
3248 // C2+1 is a power of 2
3249 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3250 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
3252
3253 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3254 // to the ult form.
3255 // X+C2 >u C -> X+(C2-C-1) <u ~C
3256 if (Pred == ICmpInst::ICMP_UGT)
3257 return new ICmpInst(ICmpInst::ICMP_ULT,
3258 Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
3259 ConstantInt::get(Ty, ~C));
3260
3261 // zext(V) + C2 pred C -> V + C3 pred' C4
3262 Value *V;
3263 if (match(X, m_ZExt(m_Value(V)))) {
3264 Type *NewCmpTy = V->getType();
3265 unsigned NewCmpBW = NewCmpTy->getScalarSizeInBits();
3266 if (shouldChangeType(Ty, NewCmpTy)) {
3267 ConstantRange SrcCR = CR.truncate(NewCmpBW, TruncInst::NoUnsignedWrap);
3268 CmpInst::Predicate EquivPred;
3269 APInt EquivInt;
3270 APInt EquivOffset;
3271
3272 SrcCR.getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
3273 return new ICmpInst(
3274 EquivPred,
3275 EquivOffset.isZero()
3276 ? V
3277 : Builder.CreateAdd(V, ConstantInt::get(NewCmpTy, EquivOffset)),
3278 ConstantInt::get(NewCmpTy, EquivInt));
3279 }
3280 }
3281
3282 return nullptr;
3283}
3284
3286 Value *&RHS, ConstantInt *&Less,
3287 ConstantInt *&Equal,
3288 ConstantInt *&Greater) {
3289 // TODO: Generalize this to work with other comparison idioms or ensure
3290 // they get canonicalized into this form.
3291
3292 // select i1 (a == b),
3293 // i32 Equal,
3294 // i32 (select i1 (a < b), i32 Less, i32 Greater)
3295 // where Equal, Less and Greater are placeholders for any three constants.
3296 CmpPredicate PredA;
3297 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
3298 !ICmpInst::isEquality(PredA))
3299 return false;
3300 Value *EqualVal = SI->getTrueValue();
3301 Value *UnequalVal = SI->getFalseValue();
3302 // We still can get non-canonical predicate here, so canonicalize.
3303 if (PredA == ICmpInst::ICMP_NE)
3304 std::swap(EqualVal, UnequalVal);
3305 if (!match(EqualVal, m_ConstantInt(Equal)))
3306 return false;
3307 CmpPredicate PredB;
3308 Value *LHS2, *RHS2;
3309 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
3310 m_ConstantInt(Less), m_ConstantInt(Greater))))
3311 return false;
3312 // We can get predicate mismatch here, so canonicalize if possible:
3313 // First, ensure that 'LHS' match.
3314 if (LHS2 != LHS) {
3315 // x sgt y <--> y slt x
3316 std::swap(LHS2, RHS2);
3317 PredB = ICmpInst::getSwappedPredicate(PredB);
3318 }
3319 if (LHS2 != LHS)
3320 return false;
3321 // We also need to canonicalize 'RHS'.
3322 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
3323 // x sgt C-1 <--> x sge C <--> not(x slt C)
3324 auto FlippedStrictness =
3326 if (!FlippedStrictness)
3327 return false;
3328 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3329 "basic correctness failure");
3330 RHS2 = FlippedStrictness->second;
3331 // And kind-of perform the result swap.
3332 std::swap(Less, Greater);
3333 PredB = ICmpInst::ICMP_SLT;
3334 }
3335 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3336}
3337
3340 ConstantInt *C) {
3341
3342 assert(C && "Cmp RHS should be a constant int!");
3343 // If we're testing a constant value against the result of a three way
3344 // comparison, the result can be expressed directly in terms of the
3345 // original values being compared. Note: We could possibly be more
3346 // aggressive here and remove the hasOneUse test. The original select is
3347 // really likely to simplify or sink when we remove a test of the result.
3348 Value *OrigLHS, *OrigRHS;
3349 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3350 if (Cmp.hasOneUse() &&
3351 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
3352 C3GreaterThan)) {
3353 assert(C1LessThan && C2Equal && C3GreaterThan);
3354
3355 bool TrueWhenLessThan = ICmpInst::compare(
3356 C1LessThan->getValue(), C->getValue(), Cmp.getPredicate());
3357 bool TrueWhenEqual = ICmpInst::compare(C2Equal->getValue(), C->getValue(),
3358 Cmp.getPredicate());
3359 bool TrueWhenGreaterThan = ICmpInst::compare(
3360 C3GreaterThan->getValue(), C->getValue(), Cmp.getPredicate());
3361
3362 // This generates the new instruction that will replace the original Cmp
3363 // Instruction. Instead of enumerating the various combinations when
3364 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3365 // false, we rely on chaining of ORs and future passes of InstCombine to
3366 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3367
3368 // When none of the three constants satisfy the predicate for the RHS (C),
3369 // the entire original Cmp can be simplified to a false.
3370 Value *Cond = Builder.getFalse();
3371 if (TrueWhenLessThan)
3372 Cond = Builder.CreateOr(
3373 Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT, OrigLHS, OrigRHS));
3374 if (TrueWhenEqual)
3375 Cond = Builder.CreateOr(
3376 Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ, OrigLHS, OrigRHS));
3377 if (TrueWhenGreaterThan)
3378 Cond = Builder.CreateOr(
3379 Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT, OrigLHS, OrigRHS));
3380
3381 return replaceInstUsesWith(Cmp, Cond);
3382 }
3383 return nullptr;
3384}
3385
3387 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3388 if (!Bitcast)
3389 return nullptr;
3390
3391 ICmpInst::Predicate Pred = Cmp.getPredicate();
3392 Value *Op1 = Cmp.getOperand(1);
3393 Value *BCSrcOp = Bitcast->getOperand(0);
3394 Type *SrcType = Bitcast->getSrcTy();
3395 Type *DstType = Bitcast->getType();
3396
3397 // Make sure the bitcast doesn't change between scalar and vector and
3398 // doesn't change the number of vector elements.
3399 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3400 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3401 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3402 Value *X;
3403 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
3404 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3405 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3406 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3407 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3408 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3409 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3410 match(Op1, m_Zero()))
3411 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3412
3413 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3414 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
3415 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
3416
3417 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3418 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
3419 return new ICmpInst(Pred, X,
3420 ConstantInt::getAllOnesValue(X->getType()));
3421 }
3422
3423 // Zero-equality checks are preserved through unsigned floating-point casts:
3424 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3425 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3426 if (match(BCSrcOp, m_UIToFP(m_Value(X))))
3427 if (Cmp.isEquality() && match(Op1, m_Zero()))
3428 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3429
3430 const APInt *C;
3431 bool TrueIfSigned;
3432 if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse()) {
3433 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3434 // the FP extend/truncate because that cast does not change the sign-bit.
3435 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3436 // The sign-bit is always the most significant bit in those types.
3437 if (isSignBitCheck(Pred, *C, TrueIfSigned) &&
3438 (match(BCSrcOp, m_FPExt(m_Value(X))) ||
3439 match(BCSrcOp, m_FPTrunc(m_Value(X))))) {
3440 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3441 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3442 Type *XType = X->getType();
3443
3444 // We can't currently handle Power style floating point operations here.
3445 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3446 Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
3447 if (auto *XVTy = dyn_cast<VectorType>(XType))
3448 NewType = VectorType::get(NewType, XVTy->getElementCount());
3449 Value *NewBitcast = Builder.CreateBitCast(X, NewType);
3450 if (TrueIfSigned)
3451 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3452 ConstantInt::getNullValue(NewType));
3453 else
3454 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3456 }
3457 }
3458
3459 // icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)
3460 Type *FPType = SrcType->getScalarType();
3461 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3462 Attribute::NoImplicitFloat) &&
3463 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3464 FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();
3465 if (Mask & (fcInf | fcZero)) {
3466 if (Pred == ICmpInst::ICMP_NE)
3467 Mask = ~Mask;
3468 return replaceInstUsesWith(Cmp,
3469 Builder.createIsFPClass(BCSrcOp, Mask));
3470 }
3471 }
3472 }
3473 }
3474
3475 const APInt *C;
3476 if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3477 !SrcType->isIntOrIntVectorTy())
3478 return nullptr;
3479
3480 // If this is checking if all elements of a vector compare are set or not,
3481 // invert the casted vector equality compare and test if all compare
3482 // elements are clear or not. Compare against zero is generally easier for
3483 // analysis and codegen.
3484 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3485 // Example: are all elements equal? --> are zero elements not equal?
3486 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3487 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3488 if (Value *NotBCSrcOp =
3489 getFreelyInverted(BCSrcOp, BCSrcOp->hasOneUse(), &Builder)) {
3490 Value *Cast = Builder.CreateBitCast(NotBCSrcOp, DstType);
3491 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3492 }
3493 }
3494
3495 // If this is checking if all elements of an extended vector are clear or not,
3496 // compare in a narrow type to eliminate the extend:
3497 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3498 Value *X;
3499 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3500 match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3501 if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3502 Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3503 Value *NewCast = Builder.CreateBitCast(X, NewType);
3504 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3505 }
3506 }
3507
3508 // Folding: icmp <pred> iN X, C
3509 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3510 // and C is a splat of a K-bit pattern
3511 // and SC is a constant vector = <C', C', C', ..., C'>
3512 // Into:
3513 // %E = extractelement <M x iK> %vec, i32 C'
3514 // icmp <pred> iK %E, trunc(C)
3515 Value *Vec;
3516 ArrayRef<int> Mask;
3517 if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3518 // Check whether every element of Mask is the same constant
3519 if (all_equal(Mask)) {
3520 auto *VecTy = cast<VectorType>(SrcType);
3521 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3522 if (C->isSplat(EltTy->getBitWidth())) {
3523 // Fold the icmp based on the value of C
3524 // If C is M copies of an iK sized bit pattern,
3525 // then:
3526 // => %E = extractelement <N x iK> %vec, i32 Elem
3527 // icmp <pred> iK %SplatVal, <pattern>
3528 Value *Elem = Builder.getInt32(Mask[0]);
3529 Value *Extract = Builder.CreateExtractElement(Vec, Elem);
3530 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3531 return new ICmpInst(Pred, Extract, NewC);
3532 }
3533 }
3534 }
3535 return nullptr;
3536}
3537
3538/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3539/// where X is some kind of instruction.
3541 const APInt *C;
3542
3543 if (match(Cmp.getOperand(1), m_APInt(C))) {
3544 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3545 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3546 return I;
3547
3548 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3549 // For now, we only support constant integers while folding the
3550 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3551 // similar to the cases handled by binary ops above.
3552 if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3553 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3554 return I;
3555
3556 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3557 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3558 return I;
3559
3560 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3562 return I;
3563
3564 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3565 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3566 // TODO: This checks one-use, but that is not strictly necessary.
3567 Value *Cmp0 = Cmp.getOperand(0);
3568 Value *X, *Y;
3569 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3570 (match(Cmp0,
3572 m_Value(X), m_Value(Y)))) ||
3573 match(Cmp0,
3575 m_Value(X), m_Value(Y))))))
3576 return new ICmpInst(Cmp.getPredicate(), X, Y);
3577 }
3578
3579 if (match(Cmp.getOperand(1), m_APIntAllowPoison(C)))
3581
3582 return nullptr;
3583}
3584
3585/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3586/// icmp eq/ne BO, C.
3588 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3589 // TODO: Some of these folds could work with arbitrary constants, but this
3590 // function is limited to scalar and vector splat constants.
3591 if (!Cmp.isEquality())
3592 return nullptr;
3593
3594 ICmpInst::Predicate Pred = Cmp.getPredicate();
3595 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3596 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3597 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3598
3599 switch (BO->getOpcode()) {
3600 case Instruction::SRem:
3601 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3602 if (C.isZero() && BO->hasOneUse()) {
3603 const APInt *BOC;
3604 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3605 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3606 return new ICmpInst(Pred, NewRem,
3608 }
3609 }
3610 break;
3611 case Instruction::Add: {
3612 // (A + C2) == C --> A == (C - C2)
3613 // (A + C2) != C --> A != (C - C2)
3614 // TODO: Remove the one-use limitation? See discussion in D58633.
3615 if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
3616 if (BO->hasOneUse())
3617 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
3618 } else if (C.isZero()) {
3619 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3620 // efficiently invertible, or if the add has just this one use.
3621 if (Value *NegVal = dyn_castNegVal(BOp1))
3622 return new ICmpInst(Pred, BOp0, NegVal);
3623 if (Value *NegVal = dyn_castNegVal(BOp0))
3624 return new ICmpInst(Pred, NegVal, BOp1);
3625 if (BO->hasOneUse()) {
3626 // (add nuw A, B) != 0 -> (or A, B) != 0
3627 if (match(BO, m_NUWAdd(m_Value(), m_Value()))) {
3628 Value *Or = Builder.CreateOr(BOp0, BOp1);
3629 return new ICmpInst(Pred, Or, Constant::getNullValue(BO->getType()));
3630 }
3631 Value *Neg = Builder.CreateNeg(BOp1);
3632 Neg->takeName(BO);
3633 return new ICmpInst(Pred, BOp0, Neg);
3634 }
3635 }
3636 break;
3637 }
3638 case Instruction::Xor:
3639 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3640 // For the xor case, we can xor two constants together, eliminating
3641 // the explicit xor.
3642 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3643 } else if (C.isZero()) {
3644 // Replace ((xor A, B) != 0) with (A != B)
3645 return new ICmpInst(Pred, BOp0, BOp1);
3646 }
3647 break;
3648 case Instruction::Or: {
3649 const APInt *BOC;
3650 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3651 // Comparing if all bits outside of a constant mask are set?
3652 // Replace (X | C) == -1 with (X & ~C) == ~C.
3653 // This removes the -1 constant.
3655 Value *And = Builder.CreateAnd(BOp0, NotBOC);
3656 return new ICmpInst(Pred, And, NotBOC);
3657 }
3658 // (icmp eq (or (select cond, 0, NonZero), Other), 0)
3659 // -> (and cond, (icmp eq Other, 0))
3660 // (icmp ne (or (select cond, NonZero, 0), Other), 0)
3661 // -> (or cond, (icmp ne Other, 0))
3662 Value *Cond, *TV, *FV, *Other, *Sel;
3663 if (C.isZero() &&
3664 match(BO,
3667 m_Value(FV))),
3668 m_Value(Other)))) &&
3669 Cond->getType() == Cmp.getType()) {
3670 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3671 // Easy case is if eq/ne matches whether 0 is trueval/falseval.
3672 if (Pred == ICmpInst::ICMP_EQ
3673 ? (match(TV, m_Zero()) && isKnownNonZero(FV, Q))
3674 : (match(FV, m_Zero()) && isKnownNonZero(TV, Q))) {
3675 Value *Cmp = Builder.CreateICmp(
3676 Pred, Other, Constant::getNullValue(Other->getType()));
3678 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3679 Cond);
3680 }
3681 // Harder case is if eq/ne matches whether 0 is falseval/trueval. In this
3682 // case we need to invert the select condition so we need to be careful to
3683 // avoid creating extra instructions.
3684 // (icmp ne (or (select cond, 0, NonZero), Other), 0)
3685 // -> (or (not cond), (icmp ne Other, 0))
3686 // (icmp eq (or (select cond, NonZero, 0), Other), 0)
3687 // -> (and (not cond), (icmp eq Other, 0))
3688 //
3689 // Only do this if the inner select has one use, in which case we are
3690 // replacing `select` with `(not cond)`. Otherwise, we will create more
3691 // uses. NB: Trying to freely invert cond doesn't make sense here, as if
3692 // cond was freely invertable, the select arms would have been inverted.
3693 if (Sel->hasOneUse() &&
3694 (Pred == ICmpInst::ICMP_EQ
3695 ? (match(FV, m_Zero()) && isKnownNonZero(TV, Q))
3696 : (match(TV, m_Zero()) && isKnownNonZero(FV, Q)))) {
3697 Value *NotCond = Builder.CreateNot(Cond);
3698 Value *Cmp = Builder.CreateICmp(
3699 Pred, Other, Constant::getNullValue(Other->getType()));
3701 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3702 NotCond);
3703 }
3704 }
3705 break;
3706 }
3707 case Instruction::UDiv:
3708 case Instruction::SDiv:
3709 if (BO->isExact()) {
3710 // div exact X, Y eq/ne 0 -> X eq/ne 0
3711 // div exact X, Y eq/ne 1 -> X eq/ne Y
3712 // div exact X, Y eq/ne C ->
3713 // if Y * C never-overflow && OneUse:
3714 // -> Y * C eq/ne X
3715 if (C.isZero())
3716 return new ICmpInst(Pred, BOp0, Constant::getNullValue(BO->getType()));
3717 else if (C.isOne())
3718 return new ICmpInst(Pred, BOp0, BOp1);
3719 else if (BO->hasOneUse()) {
3721 Instruction::Mul, BO->getOpcode() == Instruction::SDiv, BOp1,
3722 Cmp.getOperand(1), BO);
3724 Value *YC =
3725 Builder.CreateMul(BOp1, ConstantInt::get(BO->getType(), C));
3726 return new ICmpInst(Pred, YC, BOp0);
3727 }
3728 }
3729 }
3730 if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3731 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3732 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3733 return new ICmpInst(NewPred, BOp1, BOp0);
3734 }
3735 break;
3736 default:
3737 break;
3738 }
3739 return nullptr;
3740}
3741
3743 const APInt &CRhs,
3744 InstCombiner::BuilderTy &Builder,
3745 const SimplifyQuery &Q) {
3746 assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3747 "Non-ctpop intrin in ctpop fold");
3748 if (!CtpopLhs->hasOneUse())
3749 return nullptr;
3750
3751 // Power of 2 test:
3752 // isPow2OrZero : ctpop(X) u< 2
3753 // isPow2 : ctpop(X) == 1
3754 // NotPow2OrZero: ctpop(X) u> 1
3755 // NotPow2 : ctpop(X) != 1
3756 // If we know any bit of X can be folded to:
3757 // IsPow2 : X & (~Bit) == 0
3758 // NotPow2 : X & (~Bit) != 0
3759 const ICmpInst::Predicate Pred = I.getPredicate();
3760 if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3761 (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3762 Value *Op = CtpopLhs->getArgOperand(0);
3763 KnownBits OpKnown = computeKnownBits(Op, Q.DL, Q.AC, Q.CxtI, Q.DT);
3764 // No need to check for count > 1, that should be already constant folded.
3765 if (OpKnown.countMinPopulation() == 1) {
3766 Value *And = Builder.CreateAnd(
3767 Op, Constant::getIntegerValue(Op->getType(), ~(OpKnown.One)));
3768 return new ICmpInst(
3769 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3772 And, Constant::getNullValue(Op->getType()));
3773 }
3774 }
3775
3776 return nullptr;
3777}
3778
3779/// Fold an equality icmp with LLVM intrinsic and constant operand.
3781 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3782 Type *Ty = II->getType();
3783 unsigned BitWidth = C.getBitWidth();
3784 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3785
3786 switch (II->getIntrinsicID()) {
3787 case Intrinsic::abs:
3788 // abs(A) == 0 -> A == 0
3789 // abs(A) == INT_MIN -> A == INT_MIN
3790 if (C.isZero() || C.isMinSignedValue())
3791 return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3792 break;
3793
3794 case Intrinsic::bswap:
3795 // bswap(A) == C -> A == bswap(C)
3796 return new ICmpInst(Pred, II->getArgOperand(0),
3797 ConstantInt::get(Ty, C.byteSwap()));
3798
3799 case Intrinsic::bitreverse:
3800 // bitreverse(A) == C -> A == bitreverse(C)
3801 return new ICmpInst(Pred, II->getArgOperand(0),
3802 ConstantInt::get(Ty, C.reverseBits()));
3803
3804 case Intrinsic::ctlz:
3805 case Intrinsic::cttz: {
3806 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3807 if (C == BitWidth)
3808 return new ICmpInst(Pred, II->getArgOperand(0),
3810
3811 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3812 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3813 // Limit to one use to ensure we don't increase instruction count.
3814 unsigned Num = C.getLimitedValue(BitWidth);
3815 if (Num != BitWidth && II->hasOneUse()) {
3816 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3817 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3818 : APInt::getHighBitsSet(BitWidth, Num + 1);
3819 APInt Mask2 = IsTrailing
3822 return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
3823 ConstantInt::get(Ty, Mask2));
3824 }
3825 break;
3826 }
3827
3828 case Intrinsic::ctpop: {
3829 // popcount(A) == 0 -> A == 0 and likewise for !=
3830 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3831 bool IsZero = C.isZero();
3832 if (IsZero || C == BitWidth)
3833 return new ICmpInst(Pred, II->getArgOperand(0),
3834 IsZero ? Constant::getNullValue(Ty)
3836
3837 break;
3838 }
3839
3840 case Intrinsic::fshl:
3841 case Intrinsic::fshr:
3842 if (II->getArgOperand(0) == II->getArgOperand(1)) {
3843 const APInt *RotAmtC;
3844 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3845 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3846 if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
3847 return new ICmpInst(Pred, II->getArgOperand(0),
3848 II->getIntrinsicID() == Intrinsic::fshl
3849 ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
3850 : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
3851 }
3852 break;
3853
3854 case Intrinsic::umax:
3855 case Intrinsic::uadd_sat: {
3856 // uadd.sat(a, b) == 0 -> (a | b) == 0
3857 // umax(a, b) == 0 -> (a | b) == 0
3858 if (C.isZero() && II->hasOneUse()) {
3859 Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));
3860 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
3861 }
3862 break;
3863 }
3864
3865 case Intrinsic::ssub_sat:
3866 // ssub.sat(a, b) == 0 -> a == b
3867 //
3868 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
3869 // (because 1 saturates to 0). Just skip the optimization for i1.
3870 if (C.isZero() && II->getType()->getScalarSizeInBits() > 1)
3871 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
3872 break;
3873 case Intrinsic::usub_sat: {
3874 // usub.sat(a, b) == 0 -> a <= b
3875 if (C.isZero()) {
3876 ICmpInst::Predicate NewPred =
3878 return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
3879 }
3880 break;
3881 }
3882 default:
3883 break;
3884 }
3885
3886 return nullptr;
3887}
3888
3889/// Fold an icmp with LLVM intrinsics
3890static Instruction *
3892 InstCombiner::BuilderTy &Builder) {
3893 assert(Cmp.isEquality());
3894
3895 ICmpInst::Predicate Pred = Cmp.getPredicate();
3896 Value *Op0 = Cmp.getOperand(0);
3897 Value *Op1 = Cmp.getOperand(1);
3898 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
3899 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
3900 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
3901 return nullptr;
3902
3903 switch (IIOp0->getIntrinsicID()) {
3904 case Intrinsic::bswap:
3905 case Intrinsic::bitreverse:
3906 // If both operands are byte-swapped or bit-reversed, just compare the
3907 // original values.
3908 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3909 case Intrinsic::fshl:
3910 case Intrinsic::fshr: {
3911 // If both operands are rotated by same amount, just compare the
3912 // original values.
3913 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
3914 break;
3915 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
3916 break;
3917 if (IIOp0->getOperand(2) == IIOp1->getOperand(2))
3918 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3919
3920 // rotate(X, AmtX) == rotate(Y, AmtY)
3921 // -> rotate(X, AmtX - AmtY) == Y
3922 // Do this if either both rotates have one use or if only one has one use
3923 // and AmtX/AmtY are constants.
3924 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
3925 if (OneUses == 2 ||
3926 (OneUses == 1 && match(IIOp0->getOperand(2), m_ImmConstant()) &&
3927 match(IIOp1->getOperand(2), m_ImmConstant()))) {
3928 Value *SubAmt =
3929 Builder.CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));
3930 Value *CombinedRotate = Builder.CreateIntrinsic(
3931 Op0->getType(), IIOp0->getIntrinsicID(),
3932 {IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});
3933 return new ICmpInst(Pred, IIOp1->getOperand(0), CombinedRotate);
3934 }
3935 } break;
3936 default:
3937 break;
3938 }
3939
3940 return nullptr;
3941}
3942
3943/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3944/// where X is some kind of instruction and C is AllowPoison.
3945/// TODO: Move more folds which allow poison to this function.
3948 const APInt &C) {
3949 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3950 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
3951 switch (II->getIntrinsicID()) {
3952 default:
3953 break;
3954 case Intrinsic::fshl:
3955 case Intrinsic::fshr:
3956 if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
3957 // (rot X, ?) == 0/-1 --> X == 0/-1
3958 if (C.isZero() || C.isAllOnes())
3959 return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
3960 }
3961 break;
3962 }
3963 }
3964
3965 return nullptr;
3966}
3967
3968/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
3970 BinaryOperator *BO,
3971 const APInt &C) {
3972 switch (BO->getOpcode()) {
3973 case Instruction::Xor:
3974 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
3975 return I;
3976 break;
3977 case Instruction::And:
3978 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
3979 return I;
3980 break;
3981 case Instruction::Or:
3982 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
3983 return I;
3984 break;
3985 case Instruction::Mul:
3986 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
3987 return I;
3988 break;
3989 case Instruction::Shl:
3990 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
3991 return I;
3992 break;
3993 case Instruction::LShr:
3994 case Instruction::AShr:
3995 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
3996 return I;
3997 break;
3998 case Instruction::SRem:
3999 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
4000 return I;
4001 break;
4002 case Instruction::UDiv:
4003 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
4004 return I;
4005 [[fallthrough]];
4006 case Instruction::SDiv:
4007 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
4008 return I;
4009 break;
4010 case Instruction::Sub:
4011 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
4012 return I;
4013 break;
4014 case Instruction::Add:
4015 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
4016 return I;
4017 break;
4018 default:
4019 break;
4020 }
4021
4022 // TODO: These folds could be refactored to be part of the above calls.
4024 return I;
4025
4026 // Fall back to handling `icmp pred (select A ? C1 : C2) binop (select B ? C3
4027 // : C4), C5` pattern, by computing a truth table of the four constant
4028 // variants.
4030}
4031
4032static Instruction *
4034 const APInt &C,
4035 InstCombiner::BuilderTy &Builder) {
4036 // This transform may end up producing more than one instruction for the
4037 // intrinsic, so limit it to one user of the intrinsic.
4038 if (!II->hasOneUse())
4039 return nullptr;
4040
4041 // Let Y = [add/sub]_sat(X, C) pred C2
4042 // SatVal = The saturating value for the operation
4043 // WillWrap = Whether or not the operation will underflow / overflow
4044 // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
4045 // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
4046 //
4047 // When (SatVal pred C2) is true, then
4048 // Y = WillWrap ? true : ((X binop C) pred C2)
4049 // => Y = WillWrap || ((X binop C) pred C2)
4050 // else
4051 // Y = WillWrap ? false : ((X binop C) pred C2)
4052 // => Y = !WillWrap ? ((X binop C) pred C2) : false
4053 // => Y = !WillWrap && ((X binop C) pred C2)
4054 Value *Op0 = II->getOperand(0);
4055 Value *Op1 = II->getOperand(1);
4056
4057 const APInt *COp1;
4058 // This transform only works when the intrinsic has an integral constant or
4059 // splat vector as the second operand.
4060 if (!match(Op1, m_APInt(COp1)))
4061 return nullptr;
4062
4063 APInt SatVal;
4064 switch (II->getIntrinsicID()) {
4065 default:
4067 "This function only works with usub_sat and uadd_sat for now!");
4068 case Intrinsic::uadd_sat:
4069 SatVal = APInt::getAllOnes(C.getBitWidth());
4070 break;
4071 case Intrinsic::usub_sat:
4072 SatVal = APInt::getZero(C.getBitWidth());
4073 break;
4074 }
4075
4076 // Check (SatVal pred C2)
4077 bool SatValCheck = ICmpInst::compare(SatVal, C, Pred);
4078
4079 // !WillWrap.
4081 II->getBinaryOp(), *COp1, II->getNoWrapKind());
4082
4083 // WillWrap.
4084 if (SatValCheck)
4085 C1 = C1.inverse();
4086
4088 if (II->getBinaryOp() == Instruction::Add)
4089 C2 = C2.sub(*COp1);
4090 else
4091 C2 = C2.add(*COp1);
4092
4093 Instruction::BinaryOps CombiningOp =
4094 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4095
4096 std::optional<ConstantRange> Combination;
4097 if (CombiningOp == Instruction::BinaryOps::Or)
4098 Combination = C1.exactUnionWith(C2);
4099 else /* CombiningOp == Instruction::BinaryOps::And */
4100 Combination = C1.exactIntersectWith(C2);
4101
4102 if (!Combination)
4103 return nullptr;
4104
4105 CmpInst::Predicate EquivPred;
4106 APInt EquivInt;
4107 APInt EquivOffset;
4108
4109 Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
4110
4111 return new ICmpInst(
4112 EquivPred,
4113 Builder.CreateAdd(Op0, ConstantInt::get(Op1->getType(), EquivOffset)),
4114 ConstantInt::get(Op1->getType(), EquivInt));
4115}
4116
4117static Instruction *
4119 const APInt &C,
4120 InstCombiner::BuilderTy &Builder) {
4121 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4122 switch (Pred) {
4123 case ICmpInst::ICMP_EQ:
4124 case ICmpInst::ICMP_NE:
4125 if (C.isZero())
4126 NewPredicate = Pred;
4127 else if (C.isOne())
4128 NewPredicate =
4130 else if (C.isAllOnes())
4131 NewPredicate =
4133 break;
4134
4135 case ICmpInst::ICMP_SGT:
4136 if (C.isAllOnes())
4137 NewPredicate = ICmpInst::ICMP_UGE;
4138 else if (C.isZero())
4139 NewPredicate = ICmpInst::ICMP_UGT;
4140 break;
4141
4142 case ICmpInst::ICMP_SLT:
4143 if (C.isZero())
4144 NewPredicate = ICmpInst::ICMP_ULT;
4145 else if (C.isOne())
4146 NewPredicate = ICmpInst::ICMP_ULE;
4147 break;
4148
4149 case ICmpInst::ICMP_ULT:
4150 if (C.ugt(1))
4151 NewPredicate = ICmpInst::ICMP_UGE;
4152 break;
4153
4154 case ICmpInst::ICMP_UGT:
4155 if (!C.isZero() && !C.isAllOnes())
4156 NewPredicate = ICmpInst::ICMP_ULT;
4157 break;
4158
4159 default:
4160 break;
4161 }
4162
4163 if (!NewPredicate)
4164 return nullptr;
4165
4166 if (I->getIntrinsicID() == Intrinsic::scmp)
4167 NewPredicate = ICmpInst::getSignedPredicate(*NewPredicate);
4168 Value *LHS = I->getOperand(0);
4169 Value *RHS = I->getOperand(1);
4170 return new ICmpInst(*NewPredicate, LHS, RHS);
4171}
4172
4173/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
4176 const APInt &C) {
4177 ICmpInst::Predicate Pred = Cmp.getPredicate();
4178
4179 // Handle folds that apply for any kind of icmp.
4180 switch (II->getIntrinsicID()) {
4181 default:
4182 break;
4183 case Intrinsic::uadd_sat:
4184 case Intrinsic::usub_sat:
4185 if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(
4186 Pred, cast<SaturatingInst>(II), C, Builder))
4187 return Folded;
4188 break;
4189 case Intrinsic::ctpop: {
4190 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
4191 if (Instruction *R = foldCtpopPow2Test(Cmp, II, C, Builder, Q))
4192 return R;
4193 } break;
4194 case Intrinsic::scmp:
4195 case Intrinsic::ucmp:
4196 if (auto *Folded = foldICmpOfCmpIntrinsicWithConstant(Pred, II, C, Builder))
4197 return Folded;
4198 break;
4199 }
4200
4201 if (Cmp.isEquality())
4202 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
4203
4204 Type *Ty = II->getType();
4205 unsigned BitWidth = C.getBitWidth();
4206 switch (II->getIntrinsicID()) {
4207 case Intrinsic::ctpop: {
4208 // (ctpop X > BitWidth - 1) --> X == -1
4209 Value *X = II->getArgOperand(0);
4210 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
4211 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
4213 // (ctpop X < BitWidth) --> X != -1
4214 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
4215 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
4217 break;
4218 }
4219 case Intrinsic::ctlz: {
4220 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
4221 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4222 unsigned Num = C.getLimitedValue();
4223 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
4224 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
4225 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4226 }
4227
4228 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
4229 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4230 unsigned Num = C.getLimitedValue();
4232 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
4233 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4234 }
4235 break;
4236 }
4237 case Intrinsic::cttz: {
4238 // Limit to one use to ensure we don't increase instruction count.
4239 if (!II->hasOneUse())
4240 return nullptr;
4241
4242 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
4243 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4244 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
4245 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
4246 Builder.CreateAnd(II->getArgOperand(0), Mask),
4248 }
4249
4250 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
4251 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4252 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
4253 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
4254 Builder.CreateAnd(II->getArgOperand(0), Mask),
4256 }
4257 break;
4258 }
4259 case Intrinsic::ssub_sat:
4260 // ssub.sat(a, b) spred 0 -> a spred b
4261 //
4262 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4263 // (because 1 saturates to 0). Just skip the optimization for i1.
4264 if (ICmpInst::isSigned(Pred) && C.getBitWidth() > 1) {
4265 if (C.isZero())
4266 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4267 // X s<= 0 is cannonicalized to X s< 1
4268 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
4269 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(0),
4270 II->getArgOperand(1));
4271 // X s>= 0 is cannonicalized to X s> -1
4272 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
4273 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(0),
4274 II->getArgOperand(1));
4275 }
4276 break;
4277 case Intrinsic::abs: {
4278 if (!II->hasOneUse())
4279 return nullptr;
4280
4281 Value *X = II->getArgOperand(0);
4282 bool IsIntMinPoison =
4283 cast<ConstantInt>(II->getArgOperand(1))->getValue().isOne();
4284
4285 // If C >= 0:
4286 // abs(X) u> C --> X + C u> 2 * C
4287 if (Pred == CmpInst::ICMP_UGT && C.isNonNegative()) {
4288 return new ICmpInst(ICmpInst::ICMP_UGT,
4289 Builder.CreateAdd(X, ConstantInt::get(Ty, C)),
4290 ConstantInt::get(Ty, 2 * C));
4291 }
4292
4293 // If abs(INT_MIN) is poison and C >= 1:
4294 // abs(X) u< C --> X + (C - 1) u<= 2 * (C - 1)
4295 if (IsIntMinPoison && Pred == CmpInst::ICMP_ULT && C.sge(1)) {
4296 return new ICmpInst(ICmpInst::ICMP_ULE,
4297 Builder.CreateAdd(X, ConstantInt::get(Ty, C - 1)),
4298 ConstantInt::get(Ty, 2 * (C - 1)));
4299 }
4300
4301 break;
4302 }
4303 default:
4304 break;
4305 }
4306
4307 return nullptr;
4308}
4309
4310/// Handle icmp with constant (but not simple integer constant) RHS.
4312 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4313 Constant *RHSC = dyn_cast<Constant>(Op1);
4315 if (!RHSC || !LHSI)
4316 return nullptr;
4317
4318 switch (LHSI->getOpcode()) {
4319 case Instruction::IntToPtr:
4320 // icmp pred inttoptr(X), null -> icmp pred X, 0
4321 if (RHSC->isNullValue() &&
4322 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
4323 return new ICmpInst(
4324 I.getPredicate(), LHSI->getOperand(0),
4326 break;
4327
4328 case Instruction::Load:
4329 // Try to optimize things like "A[i] > 4" to index computations.
4330 if (GetElementPtrInst *GEP =
4332 if (Instruction *Res =
4334 return Res;
4335 break;
4336 }
4337
4338 return nullptr;
4339}
4340
4342 Value *RHS, const ICmpInst &I) {
4343 // Try to fold the comparison into the select arms, which will cause the
4344 // select to be converted into a logical and/or.
4345 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
4346 if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
4347 return Res;
4348 if (std::optional<bool> Impl = isImpliedCondition(
4349 SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
4350 return ConstantInt::get(I.getType(), *Impl);
4351 return nullptr;
4352 };
4353
4354 ConstantInt *CI = nullptr;
4355 Value *Op1 = SimplifyOp(SI->getOperand(1), true);
4356 if (Op1)
4357 CI = dyn_cast<ConstantInt>(Op1);
4358
4359 Value *Op2 = SimplifyOp(SI->getOperand(2), false);
4360 if (Op2)
4361 CI = dyn_cast<ConstantInt>(Op2);
4362
4363 auto Simplifies = [&](Value *Op, unsigned Idx) {
4364 // A comparison of ucmp/scmp with a constant will fold into an icmp.
4365 const APInt *Dummy;
4366 return Op ||
4367 (isa<CmpIntrinsic>(SI->getOperand(Idx)) &&
4368 SI->getOperand(Idx)->hasOneUse() && match(RHS, m_APInt(Dummy)));
4369 };
4370
4371 // We only want to perform this transformation if it will not lead to
4372 // additional code. This is true if either both sides of the select
4373 // fold to a constant (in which case the icmp is replaced with a select
4374 // which will usually simplify) or this is the only user of the
4375 // select (in which case we are trading a select+icmp for a simpler
4376 // select+icmp) or all uses of the select can be replaced based on
4377 // dominance information ("Global cases").
4378 bool Transform = false;
4379 if (Op1 && Op2)
4380 Transform = true;
4381 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4382 // Local case
4383 if (SI->hasOneUse())
4384 Transform = true;
4385 // Global cases
4386 else if (CI && !CI->isZero())
4387 // When Op1 is constant try replacing select with second operand.
4388 // Otherwise Op2 is constant and try replacing select with first
4389 // operand.
4390 Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
4391 }
4392 if (Transform) {
4393 if (!Op1)
4394 Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
4395 if (!Op2)
4396 Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
4397 return SelectInst::Create(SI->getOperand(0), Op1, Op2, "", nullptr,
4398 ProfcheckDisableMetadataFixes ? nullptr : SI);
4399 }
4400
4401 return nullptr;
4402}
4403
4404// Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)
4405static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,
4406 unsigned Depth = 0) {
4407 if (Not ? match(V, m_NegatedPower2OrZero()) : match(V, m_LowBitMaskOrZero()))
4408 return true;
4409 if (V->getType()->getScalarSizeInBits() == 1)
4410 return true;
4412 return false;
4413 Value *X;
4415 if (!I)
4416 return false;
4417 switch (I->getOpcode()) {
4418 case Instruction::ZExt:
4419 // ZExt(Mask) is a Mask.
4420 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4421 case Instruction::SExt:
4422 // SExt(Mask) is a Mask.
4423 // SExt(~Mask) is a ~Mask.
4424 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4425 case Instruction::And:
4426 case Instruction::Or:
4427 // Mask0 | Mask1 is a Mask.
4428 // Mask0 & Mask1 is a Mask.
4429 // ~Mask0 | ~Mask1 is a ~Mask.
4430 // ~Mask0 & ~Mask1 is a ~Mask.
4431 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4432 isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4433 case Instruction::Xor:
4434 if (match(V, m_Not(m_Value(X))))
4435 return isMaskOrZero(X, !Not, Q, Depth);
4436
4437 // (X ^ -X) is a ~Mask
4438 if (Not)
4439 return match(V, m_c_Xor(m_Value(X), m_Neg(m_Deferred(X))));
4440 // (X ^ (X - 1)) is a Mask
4441 else
4442 return match(V, m_c_Xor(m_Value(X), m_Add(m_Deferred(X), m_AllOnes())));
4443 case Instruction::Select:
4444 // c ? Mask0 : Mask1 is a Mask.
4445 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4446 isMaskOrZero(I->getOperand(2), Not, Q, Depth);
4447 case Instruction::Shl:
4448 // (~Mask) << X is a ~Mask.
4449 return Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4450 case Instruction::LShr:
4451 // Mask >> X is a Mask.
4452 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4453 case Instruction::AShr:
4454 // Mask s>> X is a Mask.
4455 // ~Mask s>> X is a ~Mask.
4456 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4457 case Instruction::Add:
4458 // Pow2 - 1 is a Mask.
4459 if (!Not && match(I->getOperand(1), m_AllOnes()))
4460 return isKnownToBeAPowerOfTwo(I->getOperand(0), Q.DL, /*OrZero*/ true,
4461 Q.AC, Q.CxtI, Q.DT, Depth);
4462 break;
4463 case Instruction::Sub:
4464 // -Pow2 is a ~Mask.
4465 if (Not && match(I->getOperand(0), m_Zero()))
4466 return isKnownToBeAPowerOfTwo(I->getOperand(1), Q.DL, /*OrZero*/ true,
4467 Q.AC, Q.CxtI, Q.DT, Depth);
4468 break;
4469 case Instruction::Call: {
4470 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
4471 switch (II->getIntrinsicID()) {
4472 // min/max(Mask0, Mask1) is a Mask.
4473 // min/max(~Mask0, ~Mask1) is a ~Mask.
4474 case Intrinsic::umax:
4475 case Intrinsic::smax:
4476 case Intrinsic::umin:
4477 case Intrinsic::smin:
4478 return isMaskOrZero(II->getArgOperand(1), Not, Q, Depth) &&
4479 isMaskOrZero(II->getArgOperand(0), Not, Q, Depth);
4480
4481 // In the context of masks, bitreverse(Mask) == ~Mask
4482 case Intrinsic::bitreverse:
4483 return isMaskOrZero(II->getArgOperand(0), !Not, Q, Depth);
4484 default:
4485 break;
4486 }
4487 }
4488 break;
4489 }
4490 default:
4491 break;
4492 }
4493 return false;
4494}
4495
4496/// Some comparisons can be simplified.
4497/// In this case, we are looking for comparisons that look like
4498/// a check for a lossy truncation.
4499/// Folds:
4500/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
4501/// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask
4502/// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask
4503/// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask
4504/// Where Mask is some pattern that produces all-ones in low bits:
4505/// (-1 >> y)
4506/// ((-1 << y) >> y) <- non-canonical, has extra uses
4507/// ~(-1 << y)
4508/// ((1 << y) + (-1)) <- non-canonical, has extra uses
4509/// The Mask can be a constant, too.
4510/// For some predicates, the operands are commutative.
4511/// For others, x can only be on a specific side.
4513 Value *Op1, const SimplifyQuery &Q,
4514 InstCombiner &IC) {
4515
4516 ICmpInst::Predicate DstPred;
4517 switch (Pred) {
4519 // x & Mask == x
4520 // x & ~Mask == 0
4521 // ~x | Mask == -1
4522 // -> x u<= Mask
4523 // x & ~Mask == ~Mask
4524 // -> ~Mask u<= x
4526 break;
4528 // x & Mask != x
4529 // x & ~Mask != 0
4530 // ~x | Mask != -1
4531 // -> x u> Mask
4532 // x & ~Mask != ~Mask
4533 // -> ~Mask u> x
4535 break;
4537 // x & Mask u< x
4538 // -> x u> Mask
4539 // x & ~Mask u< ~Mask
4540 // -> ~Mask u> x
4542 break;
4544 // x & Mask u>= x
4545 // -> x u<= Mask
4546 // x & ~Mask u>= ~Mask
4547 // -> ~Mask u<= x
4549 break;
4551 // x & Mask s< x [iff Mask s>= 0]
4552 // -> x s> Mask
4553 // x & ~Mask s< ~Mask [iff ~Mask != 0]
4554 // -> ~Mask s> x
4556 break;
4558 // x & Mask s>= x [iff Mask s>= 0]
4559 // -> x s<= Mask
4560 // x & ~Mask s>= ~Mask [iff ~Mask != 0]
4561 // -> ~Mask s<= x
4563 break;
4564 default:
4565 // We don't support sgt,sle
4566 // ult/ugt are simplified to true/false respectively.
4567 return nullptr;
4568 }
4569
4570 Value *X, *M;
4571 // Put search code in lambda for early positive returns.
4572 auto IsLowBitMask = [&]() {
4573 if (match(Op0, m_c_And(m_Specific(Op1), m_Value(M)))) {
4574 X = Op1;
4575 // Look for: x & Mask pred x
4576 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4577 return !ICmpInst::isSigned(Pred) ||
4578 (match(M, m_NonNegative()) || isKnownNonNegative(M, Q));
4579 }
4580
4581 // Look for: x & ~Mask pred ~Mask
4582 if (isMaskOrZero(X, /*Not=*/true, Q)) {
4583 return !ICmpInst::isSigned(Pred) || isKnownNonZero(X, Q);
4584 }
4585 return false;
4586 }
4587 if (ICmpInst::isEquality(Pred) && match(Op1, m_AllOnes()) &&
4588 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(M))))) {
4589
4590 auto Check = [&]() {
4591 // Look for: ~x | Mask == -1
4592 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4593 if (Value *NotX =
4594 IC.getFreelyInverted(X, X->hasOneUse(), &IC.Builder)) {
4595 X = NotX;
4596 return true;
4597 }
4598 }
4599 return false;
4600 };
4601 if (Check())
4602 return true;
4603 std::swap(X, M);
4604 return Check();
4605 }
4606 if (ICmpInst::isEquality(Pred) && match(Op1, m_Zero()) &&
4607 match(Op0, m_OneUse(m_And(m_Value(X), m_Value(M))))) {
4608 auto Check = [&]() {
4609 // Look for: x & ~Mask == 0
4610 if (isMaskOrZero(M, /*Not=*/true, Q)) {
4611 if (Value *NotM =
4612 IC.getFreelyInverted(M, M->hasOneUse(), &IC.Builder)) {
4613 M = NotM;
4614 return true;
4615 }
4616 }
4617 return false;
4618 };
4619 if (Check())
4620 return true;
4621 std::swap(X, M);
4622 return Check();
4623 }
4624 return false;
4625 };
4626
4627 if (!IsLowBitMask())
4628 return nullptr;
4629
4630 return IC.Builder.CreateICmp(DstPred, X, M);
4631}
4632
4633/// Some comparisons can be simplified.
4634/// In this case, we are looking for comparisons that look like
4635/// a check for a lossy signed truncation.
4636/// Folds: (MaskedBits is a constant.)
4637/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4638/// Into:
4639/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4640/// Where KeptBits = bitwidth(%x) - MaskedBits
4641static Value *
4643 InstCombiner::BuilderTy &Builder) {
4644 CmpPredicate SrcPred;
4645 Value *X;
4646 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4647 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4648 if (!match(&I, m_c_ICmp(SrcPred,
4650 m_APInt(C1))),
4651 m_Deferred(X))))
4652 return nullptr;
4653
4654 // Potential handling of non-splats: for each element:
4655 // * if both are undef, replace with constant 0.
4656 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4657 // * if both are not undef, and are different, bailout.
4658 // * else, only one is undef, then pick the non-undef one.
4659
4660 // The shift amount must be equal.
4661 if (*C0 != *C1)
4662 return nullptr;
4663 const APInt &MaskedBits = *C0;
4664 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4665
4666 ICmpInst::Predicate DstPred;
4667 switch (SrcPred) {
4669 // ((%x << MaskedBits) a>> MaskedBits) == %x
4670 // =>
4671 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4673 break;
4675 // ((%x << MaskedBits) a>> MaskedBits) != %x
4676 // =>
4677 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4679 break;
4680 // FIXME: are more folds possible?
4681 default:
4682 return nullptr;
4683 }
4684
4685 auto *XType = X->getType();
4686 const unsigned XBitWidth = XType->getScalarSizeInBits();
4687 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4688 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4689
4690 // KeptBits = bitwidth(%x) - MaskedBits
4691 const APInt KeptBits = BitWidth - MaskedBits;
4692 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4693 // ICmpCst = (1 << KeptBits)
4694 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
4695 assert(ICmpCst.isPowerOf2());
4696 // AddCst = (1 << (KeptBits-1))
4697 const APInt AddCst = ICmpCst.lshr(1);
4698 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4699
4700 // T0 = add %x, AddCst
4701 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
4702 // T1 = T0 DstPred ICmpCst
4703 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
4704
4705 return T1;
4706}
4707
4708// Given pattern:
4709// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4710// we should move shifts to the same hand of 'and', i.e. rewrite as
4711// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4712// We are only interested in opposite logical shifts here.
4713// One of the shifts can be truncated.
4714// If we can, we want to end up creating 'lshr' shift.
4715static Value *
4717 InstCombiner::BuilderTy &Builder) {
4718 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
4719 !I.getOperand(0)->hasOneUse())
4720 return nullptr;
4721
4722 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
4723
4724 // Look for an 'and' of two logical shifts, one of which may be truncated.
4725 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4726 Instruction *XShift, *MaybeTruncation, *YShift;
4727 if (!match(
4728 I.getOperand(0),
4729 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
4731 m_AnyLogicalShift, m_Instruction(YShift))),
4732 m_Instruction(MaybeTruncation)))))
4733 return nullptr;
4734
4735 // We potentially looked past 'trunc', but only when matching YShift,
4736 // therefore YShift must have the widest type.
4737 Instruction *WidestShift = YShift;
4738 // Therefore XShift must have the shallowest type.
4739 // Or they both have identical types if there was no truncation.
4740 Instruction *NarrowestShift = XShift;
4741
4742 Type *WidestTy = WidestShift->getType();
4743 Type *NarrowestTy = NarrowestShift->getType();
4744 assert(NarrowestTy == I.getOperand(0)->getType() &&
4745 "We did not look past any shifts while matching XShift though.");
4746 bool HadTrunc = WidestTy != I.getOperand(0)->getType();
4747
4748 // If YShift is a 'lshr', swap the shifts around.
4749 if (match(YShift, m_LShr(m_Value(), m_Value())))
4750 std::swap(XShift, YShift);
4751
4752 // The shifts must be in opposite directions.
4753 auto XShiftOpcode = XShift->getOpcode();
4754 if (XShiftOpcode == YShift->getOpcode())
4755 return nullptr; // Do not care about same-direction shifts here.
4756
4757 Value *X, *XShAmt, *Y, *YShAmt;
4758 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
4759 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
4760
4761 // If one of the values being shifted is a constant, then we will end with
4762 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4763 // however, we will need to ensure that we won't increase instruction count.
4764 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
4765 // At least one of the hands of the 'and' should be one-use shift.
4766 if (!match(I.getOperand(0),
4767 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
4768 return nullptr;
4769 if (HadTrunc) {
4770 // Due to the 'trunc', we will need to widen X. For that either the old
4771 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4772 if (!MaybeTruncation->hasOneUse() &&
4773 !NarrowestShift->getOperand(1)->hasOneUse())
4774 return nullptr;
4775 }
4776 }
4777
4778 // We have two shift amounts from two different shifts. The types of those
4779 // shift amounts may not match. If that's the case let's bailout now.
4780 if (XShAmt->getType() != YShAmt->getType())
4781 return nullptr;
4782
4783 // As input, we have the following pattern:
4784 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4785 // We want to rewrite that as:
4786 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4787 // While we know that originally (Q+K) would not overflow
4788 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
4789 // shift amounts. so it may now overflow in smaller bitwidth.
4790 // To ensure that does not happen, we need to ensure that the total maximal
4791 // shift amount is still representable in that smaller bit width.
4792 unsigned MaximalPossibleTotalShiftAmount =
4793 (WidestTy->getScalarSizeInBits() - 1) +
4794 (NarrowestTy->getScalarSizeInBits() - 1);
4795 APInt MaximalRepresentableShiftAmount =
4797 if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
4798 return nullptr;
4799
4800 // Can we fold (XShAmt+YShAmt) ?
4801 auto *NewShAmt = dyn_cast_or_null<Constant>(
4802 simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
4803 /*isNUW=*/false, SQ.getWithInstruction(&I)));
4804 if (!NewShAmt)
4805 return nullptr;
4806 if (NewShAmt->getType() != WidestTy) {
4807 NewShAmt =
4808 ConstantFoldCastOperand(Instruction::ZExt, NewShAmt, WidestTy, SQ.DL);
4809 if (!NewShAmt)
4810 return nullptr;
4811 }
4812 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
4813
4814 // Is the new shift amount smaller than the bit width?
4815 // FIXME: could also rely on ConstantRange.
4816 if (!match(NewShAmt,
4818 APInt(WidestBitWidth, WidestBitWidth))))
4819 return nullptr;
4820
4821 // An extra legality check is needed if we had trunc-of-lshr.
4822 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
4823 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
4824 WidestShift]() {
4825 // It isn't obvious whether it's worth it to analyze non-constants here.
4826 // Also, let's basically give up on non-splat cases, pessimizing vectors.
4827 // If *any* of these preconditions matches we can perform the fold.
4828 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
4829 ? NewShAmt->getSplatValue()
4830 : NewShAmt;
4831 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
4832 if (NewShAmtSplat &&
4833 (NewShAmtSplat->isNullValue() ||
4834 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
4835 return true;
4836 // We consider *min* leading zeros so a single outlier
4837 // blocks the transform as opposed to allowing it.
4838 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
4839 KnownBits Known = computeKnownBits(C, SQ.DL);
4840 unsigned MinLeadZero = Known.countMinLeadingZeros();
4841 // If the value being shifted has at most lowest bit set we can fold.
4842 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4843 if (MaxActiveBits <= 1)
4844 return true;
4845 // Precondition: NewShAmt u<= countLeadingZeros(C)
4846 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
4847 return true;
4848 }
4849 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
4850 KnownBits Known = computeKnownBits(C, SQ.DL);
4851 unsigned MinLeadZero = Known.countMinLeadingZeros();
4852 // If the value being shifted has at most lowest bit set we can fold.
4853 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4854 if (MaxActiveBits <= 1)
4855 return true;
4856 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
4857 if (NewShAmtSplat) {
4858 APInt AdjNewShAmt =
4859 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
4860 if (AdjNewShAmt.ule(MinLeadZero))
4861 return true;
4862 }
4863 }
4864 return false; // Can't tell if it's ok.
4865 };
4866 if (!CanFold())
4867 return nullptr;
4868 }
4869
4870 // All good, we can do this fold.
4871 X = Builder.CreateZExt(X, WidestTy);
4872 Y = Builder.CreateZExt(Y, WidestTy);
4873 // The shift is the same that was for X.
4874 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
4875 ? Builder.CreateLShr(X, NewShAmt)
4876 : Builder.CreateShl(X, NewShAmt);
4877 Value *T1 = Builder.CreateAnd(T0, Y);
4878 return Builder.CreateICmp(I.getPredicate(), T1,
4879 Constant::getNullValue(WidestTy));
4880}
4881
4882/// Fold
4883/// (-1 u/ x) u< y
4884/// ((x * y) ?/ x) != y
4885/// to
4886/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
4887/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
4888/// will mean that we are looking for the opposite answer.
4890 CmpPredicate Pred;
4891 Value *X, *Y;
4893 Instruction *Div;
4894 bool NeedNegation;
4895 // Look for: (-1 u/ x) u</u>= y
4896 if (!I.isEquality() &&
4897 match(&I, m_c_ICmp(Pred,
4899 m_Instruction(Div)),
4900 m_Value(Y)))) {
4901 Mul = nullptr;
4902
4903 // Are we checking that overflow does not happen, or does happen?
4904 switch (Pred) {
4906 NeedNegation = false;
4907 break; // OK
4909 NeedNegation = true;
4910 break; // OK
4911 default:
4912 return nullptr; // Wrong predicate.
4913 }
4914 } else // Look for: ((x * y) / x) !=/== y
4915 if (I.isEquality() &&
4916 match(&I, m_c_ICmp(Pred, m_Value(Y),
4919 m_Value(X)),
4921 m_Deferred(X))),
4922 m_Instruction(Div))))) {
4923 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
4924 } else
4925 return nullptr;
4926
4928 // If the pattern included (x * y), we'll want to insert new instructions
4929 // right before that original multiplication so that we can replace it.
4930 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
4931 if (MulHadOtherUses)
4932 Builder.SetInsertPoint(Mul);
4933
4934 CallInst *Call = Builder.CreateIntrinsic(
4935 Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
4936 : Intrinsic::smul_with_overflow,
4937 X->getType(), {X, Y}, /*FMFSource=*/nullptr, "mul");
4938
4939 // If the multiplication was used elsewhere, to ensure that we don't leave
4940 // "duplicate" instructions, replace uses of that original multiplication
4941 // with the multiplication result from the with.overflow intrinsic.
4942 if (MulHadOtherUses)
4943 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
4944
4945 Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
4946 if (NeedNegation) // This technically increases instruction count.
4947 Res = Builder.CreateNot(Res, "mul.not.ov");
4948
4949 // If we replaced the mul, erase it. Do this after all uses of Builder,
4950 // as the mul is used as insertion point.
4951 if (MulHadOtherUses)
4953
4954 return Res;
4955}
4956
4958 InstCombiner::BuilderTy &Builder) {
4959 CmpPredicate Pred;
4960 Value *X;
4961 if (match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) {
4962
4963 if (ICmpInst::isSigned(Pred))
4964 Pred = ICmpInst::getSwappedPredicate(Pred);
4965 else if (ICmpInst::isUnsigned(Pred))
4966 Pred = ICmpInst::getSignedPredicate(Pred);
4967 // else for equality-comparisons just keep the predicate.
4968
4969 return ICmpInst::Create(Instruction::ICmp, Pred, X,
4970 Constant::getNullValue(X->getType()), I.getName());
4971 }
4972
4973 // A value is not equal to its negation unless that value is 0 or
4974 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
4975 if (match(&I, m_c_ICmp(Pred, m_OneUse(m_Neg(m_Value(X))), m_Deferred(X))) &&
4976 ICmpInst::isEquality(Pred)) {
4977 Type *Ty = X->getType();
4978 uint32_t BitWidth = Ty->getScalarSizeInBits();
4979 Constant *MaxSignedVal =
4980 ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
4981 Value *And = Builder.CreateAnd(X, MaxSignedVal);
4982 Constant *Zero = Constant::getNullValue(Ty);
4983 return CmpInst::Create(Instruction::ICmp, Pred, And, Zero);
4984 }
4985
4986 return nullptr;
4987}
4988
4990 InstCombinerImpl &IC) {
4991 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
4992 // Normalize and operand as operand 0.
4993 CmpInst::Predicate Pred = I.getPredicate();
4994 if (match(Op1, m_c_And(m_Specific(Op0), m_Value()))) {
4995 std::swap(Op0, Op1);
4996 Pred = ICmpInst::getSwappedPredicate(Pred);
4997 }
4998
4999 if (!match(Op0, m_c_And(m_Specific(Op1), m_Value(A))))
5000 return nullptr;
5001
5002 // (icmp (X & Y) u< X --> (X & Y) != X
5003 if (Pred == ICmpInst::ICMP_ULT)
5004 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5005
5006 // (icmp (X & Y) u>= X --> (X & Y) == X
5007 if (Pred == ICmpInst::ICMP_UGE)
5008 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5009
5010 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5011 // icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and
5012 // Y is non-constant. If Y is constant the `X & C == C` form is preferable
5013 // so don't do this fold.
5014 if (!match(Op1, m_ImmConstant()))
5015 if (auto *NotOp1 =
5016 IC.getFreelyInverted(Op1, !Op1->hasNUsesOrMore(3), &IC.Builder))
5017 return new ICmpInst(Pred, IC.Builder.CreateOr(A, NotOp1),
5018 Constant::getAllOnesValue(Op1->getType()));
5019 // icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.
5020 if (auto *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5021 return new ICmpInst(Pred, IC.Builder.CreateAnd(Op1, NotA),
5022 Constant::getNullValue(Op1->getType()));
5023 }
5024
5025 if (!ICmpInst::isSigned(Pred))
5026 return nullptr;
5027
5028 KnownBits KnownY = IC.computeKnownBits(A, &I);
5029 // (X & NegY) spred X --> (X & NegY) upred X
5030 if (KnownY.isNegative())
5031 return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);
5032
5033 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGT)
5034 return nullptr;
5035
5036 if (KnownY.isNonNegative())
5037 // (X & PosY) s<= X --> X s>= 0
5038 // (X & PosY) s> X --> X s< 0
5039 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
5040 Constant::getNullValue(Op1->getType()));
5041
5043 // (NegX & Y) s<= NegX --> Y s< 0
5044 // (NegX & Y) s> NegX --> Y s>= 0
5046 Constant::getNullValue(A->getType()));
5047
5048 return nullptr;
5049}
5050
5052 InstCombinerImpl &IC) {
5053 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5054
5055 // Normalize or operand as operand 0.
5056 CmpInst::Predicate Pred = I.getPredicate();
5057 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value(A)))) {
5058 std::swap(Op0, Op1);
5059 Pred = ICmpInst::getSwappedPredicate(Pred);
5060 } else if (!match(Op0, m_c_Or(m_Specific(Op1), m_Value(A)))) {
5061 return nullptr;
5062 }
5063
5064 // icmp (X | Y) u<= X --> (X | Y) == X
5065 if (Pred == ICmpInst::ICMP_ULE)
5066 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5067
5068 // icmp (X | Y) u> X --> (X | Y) != X
5069 if (Pred == ICmpInst::ICMP_UGT)
5070 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5071
5072 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5073 // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
5074 if (Value *NotOp1 = IC.getFreelyInverted(
5075 Op1, !isa<Constant>(Op1) && !Op1->hasNUsesOrMore(3), &IC.Builder))
5076 return new ICmpInst(Pred, IC.Builder.CreateAnd(A, NotOp1),
5077 Constant::getNullValue(Op1->getType()));
5078 // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.
5079 if (Value *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5080 return new ICmpInst(Pred, IC.Builder.CreateOr(Op1, NotA),
5081 Constant::getAllOnesValue(Op1->getType()));
5082 }
5083 return nullptr;
5084}
5085
5087 InstCombinerImpl &IC) {
5088 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5089 // Normalize xor operand as operand 0.
5090 CmpInst::Predicate Pred = I.getPredicate();
5091 if (match(Op1, m_c_Xor(m_Specific(Op0), m_Value()))) {
5092 std::swap(Op0, Op1);
5093 Pred = ICmpInst::getSwappedPredicate(Pred);
5094 }
5095 if (!match(Op0, m_c_Xor(m_Specific(Op1), m_Value(A))))
5096 return nullptr;
5097
5098 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
5099 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
5100 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
5101 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
5103 if (PredOut != Pred && isKnownNonZero(A, Q))
5104 return new ICmpInst(PredOut, Op0, Op1);
5105
5106 // These transform work when A is negative.
5107 // X s< X^A, X s<= X^A, X u> X^A, X u>= X^A --> X s< 0
5108 // X s> X^A, X s>= X^A, X u< X^A, X u<= X^A --> X s>= 0
5109 if (match(A, m_Negative())) {
5110 CmpInst::Predicate NewPred;
5111 switch (ICmpInst::getStrictPredicate(Pred)) {
5112 default:
5113 return nullptr;
5114 case ICmpInst::ICMP_SLT:
5115 case ICmpInst::ICMP_UGT:
5116 NewPred = ICmpInst::ICMP_SLT;
5117 break;
5118 case ICmpInst::ICMP_SGT:
5119 case ICmpInst::ICMP_ULT:
5120 NewPred = ICmpInst::ICMP_SGE;
5121 break;
5122 }
5123 Constant *Const = Constant::getNullValue(Op0->getType());
5124 return new ICmpInst(NewPred, Op0, Const);
5125 }
5126
5127 return nullptr;
5128}
5129
5130/// Return true if X is a multiple of C.
5131/// TODO: Handle non-power-of-2 factors.
5132static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q) {
5133 if (C.isOne())
5134 return true;
5135
5136 if (!C.isPowerOf2())
5137 return false;
5138
5139 return MaskedValueIsZero(X, C - 1, Q);
5140}
5141
5142/// Try to fold icmp (binop), X or icmp X, (binop).
5143/// TODO: A large part of this logic is duplicated in InstSimplify's
5144/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
5145/// duplication.
5147 const SimplifyQuery &SQ) {
5148 const SimplifyQuery Q = SQ.getWithInstruction(&I);
5149 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5150
5151 // Special logic for binary operators.
5154 if (!BO0 && !BO1)
5155 return nullptr;
5156
5157 if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
5158 return NewICmp;
5159
5160 const CmpInst::Predicate Pred = I.getPredicate();
5161 Value *X;
5162
5163 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
5164 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
5165 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
5166 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5167 return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
5168 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
5169 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
5170 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5171 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
5172
5173 {
5174 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
5175 Constant *C;
5176 if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
5177 m_ImmConstant(C)))) &&
5178 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
5180 return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
5181 }
5182 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
5183 if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
5184 m_ImmConstant(C)))) &&
5185 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
5187 return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
5188 }
5189 }
5190
5191 // (icmp eq/ne (X, -P2), INT_MIN)
5192 // -> (icmp slt/sge X, INT_MIN + P2)
5193 if (ICmpInst::isEquality(Pred) && BO0 &&
5194 match(I.getOperand(1), m_SignMask()) &&
5196 // Will Constant fold.
5197 Value *NewC = Builder.CreateSub(I.getOperand(1), BO0->getOperand(1));
5198 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SLT
5200 BO0->getOperand(0), NewC);
5201 }
5202
5203 {
5204 // Similar to above: an unsigned overflow comparison may use offset + mask:
5205 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
5206 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
5207 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
5208 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
5209 BinaryOperator *BO;
5210 const APInt *C;
5211 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
5212 match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5214 CmpInst::Predicate NewPred =
5216 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5217 return new ICmpInst(NewPred, Op1, Zero);
5218 }
5219
5220 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5221 match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5223 CmpInst::Predicate NewPred =
5225 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5226 return new ICmpInst(NewPred, Op0, Zero);
5227 }
5228 }
5229
5230 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
5231 bool Op0HasNUW = false, Op1HasNUW = false;
5232 bool Op0HasNSW = false, Op1HasNSW = false;
5233 // Analyze the case when either Op0 or Op1 is an add instruction.
5234 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
5235 auto hasNoWrapProblem = [](const BinaryOperator &BO, CmpInst::Predicate Pred,
5236 bool &HasNSW, bool &HasNUW) -> bool {
5238 HasNUW = BO.hasNoUnsignedWrap();
5239 HasNSW = BO.hasNoSignedWrap();
5240 return ICmpInst::isEquality(Pred) ||
5241 (CmpInst::isUnsigned(Pred) && HasNUW) ||
5242 (CmpInst::isSigned(Pred) && HasNSW);
5243 } else if (BO.getOpcode() == Instruction::Or) {
5244 HasNUW = true;
5245 HasNSW = true;
5246 return true;
5247 } else {
5248 return false;
5249 }
5250 };
5251 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5252
5253 if (BO0) {
5254 match(BO0, m_AddLike(m_Value(A), m_Value(B)));
5255 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5256 }
5257 if (BO1) {
5258 match(BO1, m_AddLike(m_Value(C), m_Value(D)));
5259 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5260 }
5261
5262 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5263 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5264 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5265 return new ICmpInst(Pred, A == Op1 ? B : A,
5266 Constant::getNullValue(Op1->getType()));
5267
5268 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5269 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5270 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5271 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
5272 C == Op0 ? D : C);
5273
5274 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
5275 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
5276 NoOp1WrapProblem) {
5277 // Determine Y and Z in the form icmp (X+Y), (X+Z).
5278 Value *Y, *Z;
5279 if (A == C) {
5280 // C + B == C + D -> B == D
5281 Y = B;
5282 Z = D;
5283 } else if (A == D) {
5284 // D + B == C + D -> B == C
5285 Y = B;
5286 Z = C;
5287 } else if (B == C) {
5288 // A + C == C + D -> A == D
5289 Y = A;
5290 Z = D;
5291 } else {
5292 assert(B == D);
5293 // A + D == C + D -> A == C
5294 Y = A;
5295 Z = C;
5296 }
5297 return new ICmpInst(Pred, Y, Z);
5298 }
5299
5300 if (ICmpInst::isRelational(Pred)) {
5301 // Return if both X and Y is divisible by Z/-Z.
5302 // TODO: Generalize to check if (X - Y) is divisible by Z/-Z.
5303 auto ShareCommonDivisor = [&Q](Value *X, Value *Y, Value *Z,
5304 bool IsNegative) -> bool {
5305 const APInt *OffsetC;
5306 if (!match(Z, m_APInt(OffsetC)))
5307 return false;
5308
5309 // Fast path for Z == 1/-1.
5310 if (IsNegative ? OffsetC->isAllOnes() : OffsetC->isOne())
5311 return true;
5312
5313 APInt C = *OffsetC;
5314 if (IsNegative)
5315 C.negate();
5316 // Note: -INT_MIN is also negative.
5317 if (!C.isStrictlyPositive())
5318 return false;
5319
5320 return isMultipleOf(X, C, Q) && isMultipleOf(Y, C, Q);
5321 };
5322
5323 // TODO: The subtraction-related identities shown below also hold, but
5324 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
5325 // wouldn't happen even if they were implemented.
5326 //
5327 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5328 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5329 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5330 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5331
5332 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5333 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5334 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5335 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5336 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5337 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5338 if (A && NoOp0WrapProblem &&
5339 ShareCommonDivisor(A, Op1, B,
5340 ICmpInst::isLT(Pred) || ICmpInst::isGE(Pred)))
5342 Op1);
5343
5344 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5345 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5346 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5347 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5348 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5349 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5350 if (C && NoOp1WrapProblem &&
5351 ShareCommonDivisor(Op0, C, D,
5352 ICmpInst::isGT(Pred) || ICmpInst::isLE(Pred)))
5354 C);
5355 }
5356
5357 // if C1 has greater magnitude than C2:
5358 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5359 // s.t. C3 = C1 - C2
5360 //
5361 // if C2 has greater magnitude than C1:
5362 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5363 // s.t. C3 = C2 - C1
5364 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5365 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5366 const APInt *AP1, *AP2;
5367 // TODO: Support non-uniform vectors.
5368 // TODO: Allow poison passthrough if B or D's element is poison.
5369 if (match(B, m_APIntAllowPoison(AP1)) &&
5370 match(D, m_APIntAllowPoison(AP2)) &&
5371 AP1->isNegative() == AP2->isNegative()) {
5372 APInt AP1Abs = AP1->abs();
5373 APInt AP2Abs = AP2->abs();
5374 if (AP1Abs.uge(AP2Abs)) {
5375 APInt Diff = *AP1 - *AP2;
5376 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5377 Value *NewAdd = Builder.CreateAdd(
5378 A, C3, "", Op0HasNUW && Diff.ule(*AP1), Op0HasNSW);
5379 return new ICmpInst(Pred, NewAdd, C);
5380 } else {
5381 APInt Diff = *AP2 - *AP1;
5382 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5383 Value *NewAdd = Builder.CreateAdd(
5384 C, C3, "", Op1HasNUW && Diff.ule(*AP2), Op1HasNSW);
5385 return new ICmpInst(Pred, A, NewAdd);
5386 }
5387 }
5388 Constant *Cst1, *Cst2;
5389 if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
5390 ICmpInst::isEquality(Pred)) {
5391 Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
5392 Value *NewAdd = Builder.CreateAdd(C, Diff);
5393 return new ICmpInst(Pred, A, NewAdd);
5394 }
5395 }
5396
5397 // Analyze the case when either Op0 or Op1 is a sub instruction.
5398 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5399 A = nullptr;
5400 B = nullptr;
5401 C = nullptr;
5402 D = nullptr;
5403 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5404 A = BO0->getOperand(0);
5405 B = BO0->getOperand(1);
5406 }
5407 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5408 C = BO1->getOperand(0);
5409 D = BO1->getOperand(1);
5410 }
5411
5412 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5413 if (A == Op1 && NoOp0WrapProblem)
5414 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
5415 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5416 if (C == Op0 && NoOp1WrapProblem)
5417 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
5418
5419 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5420 // (A - B) u>/u<= A --> B u>/u<= A
5421 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5422 return new ICmpInst(Pred, B, A);
5423 // C u</u>= (C - D) --> C u</u>= D
5424 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5425 return new ICmpInst(Pred, C, D);
5426 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5427 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5428 isKnownNonZero(B, Q))
5430 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5431 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5432 isKnownNonZero(D, Q))
5434
5435 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
5436 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
5437 return new ICmpInst(Pred, A, C);
5438
5439 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
5440 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
5441 return new ICmpInst(Pred, D, B);
5442
5443 // icmp (0-X) < cst --> x > -cst
5444 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
5445 Value *X;
5446 if (match(BO0, m_Neg(m_Value(X))))
5447 if (Constant *RHSC = dyn_cast<Constant>(Op1))
5448 if (RHSC->isNotMinSignedValue())
5449 return new ICmpInst(I.getSwappedPredicate(), X,
5450 ConstantExpr::getNeg(RHSC));
5451 }
5452
5453 if (Instruction *R = foldICmpXorXX(I, Q, *this))
5454 return R;
5455 if (Instruction *R = foldICmpOrXX(I, Q, *this))
5456 return R;
5457
5458 {
5459 // Try to remove shared multiplier from comparison:
5460 // X * Z pred Y * Z
5461 Value *X, *Y, *Z;
5462 if ((match(Op0, m_Mul(m_Value(X), m_Value(Z))) &&
5463 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))) ||
5464 (match(Op0, m_Mul(m_Value(Z), m_Value(X))) &&
5465 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y))))) {
5466 if (ICmpInst::isSigned(Pred)) {
5467 if (Op0HasNSW && Op1HasNSW) {
5468 KnownBits ZKnown = computeKnownBits(Z, &I);
5469 if (ZKnown.isStrictlyPositive())
5470 return new ICmpInst(Pred, X, Y);
5471 if (ZKnown.isNegative())
5472 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), X, Y);
5474 SQ.getWithInstruction(&I));
5475 if (LessThan && match(LessThan, m_One()))
5476 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Z,
5477 Constant::getNullValue(Z->getType()));
5478 Value *GreaterThan = simplifyICmpInst(ICmpInst::ICMP_SGT, X, Y,
5479 SQ.getWithInstruction(&I));
5480 if (GreaterThan && match(GreaterThan, m_One()))
5481 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5482 }
5483 } else {
5484 bool NonZero;
5485 if (ICmpInst::isEquality(Pred)) {
5486 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5487 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5488 isKnownNonEqual(X, Y, SQ))
5489 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5490
5491 KnownBits ZKnown = computeKnownBits(Z, &I);
5492 // if Z % 2 != 0
5493 // X * Z eq/ne Y * Z -> X eq/ne Y
5494 if (ZKnown.countMaxTrailingZeros() == 0)
5495 return new ICmpInst(Pred, X, Y);
5496 NonZero = !ZKnown.One.isZero() || isKnownNonZero(Z, Q);
5497 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5498 // X * Z eq/ne Y * Z -> X eq/ne Y
5499 if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)
5500 return new ICmpInst(Pred, X, Y);
5501 } else
5502 NonZero = isKnownNonZero(Z, Q);
5503
5504 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5505 // X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
5506 if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)
5507 return new ICmpInst(Pred, X, Y);
5508 }
5509 }
5510 }
5511
5512 BinaryOperator *SRem = nullptr;
5513 // icmp (srem X, Y), Y
5514 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
5515 SRem = BO0;
5516 // icmp Y, (srem X, Y)
5517 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5518 Op0 == BO1->getOperand(1))
5519 SRem = BO1;
5520 if (SRem) {
5521 // We don't check hasOneUse to avoid increasing register pressure because
5522 // the value we use is the same value this instruction was already using.
5523 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
5524 default:
5525 break;
5526 case ICmpInst::ICMP_EQ:
5527 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5528 case ICmpInst::ICMP_NE:
5529 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5530 case ICmpInst::ICMP_SGT:
5531 case ICmpInst::ICMP_SGE:
5532 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
5534 case ICmpInst::ICMP_SLT:
5535 case ICmpInst::ICMP_SLE:
5536 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
5538 }
5539 }
5540
5541 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5542 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5543 BO0->getOperand(1) == BO1->getOperand(1)) {
5544 switch (BO0->getOpcode()) {
5545 default:
5546 break;
5547 case Instruction::Add:
5548 case Instruction::Sub:
5549 case Instruction::Xor: {
5550 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5551 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5552
5553 const APInt *C;
5554 if (match(BO0->getOperand(1), m_APInt(C))) {
5555 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5556 if (C->isSignMask()) {
5557 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5558 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5559 }
5560
5561 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5562 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5563 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5564 NewPred = I.getSwappedPredicate(NewPred);
5565 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5566 }
5567 }
5568 break;
5569 }
5570 case Instruction::Mul: {
5571 if (!I.isEquality())
5572 break;
5573
5574 const APInt *C;
5575 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
5576 !C->isOne()) {
5577 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5578 // Mask = -1 >> count-trailing-zeros(C).
5579 if (unsigned TZs = C->countr_zero()) {
5580 Constant *Mask = ConstantInt::get(
5581 BO0->getType(),
5582 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
5583 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
5584 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
5585 return new ICmpInst(Pred, And1, And2);
5586 }
5587 }
5588 break;
5589 }
5590 case Instruction::UDiv:
5591 case Instruction::LShr:
5592 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
5593 break;
5594 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5595
5596 case Instruction::SDiv:
5597 if (!(I.isEquality() || match(BO0->getOperand(1), m_NonNegative())) ||
5598 !BO0->isExact() || !BO1->isExact())
5599 break;
5600 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5601
5602 case Instruction::AShr:
5603 if (!BO0->isExact() || !BO1->isExact())
5604 break;
5605 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5606
5607 case Instruction::Shl: {
5608 bool NUW = Op0HasNUW && Op1HasNUW;
5609 bool NSW = Op0HasNSW && Op1HasNSW;
5610 if (!NUW && !NSW)
5611 break;
5612 if (!NSW && I.isSigned())
5613 break;
5614 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5615 }
5616 }
5617 }
5618
5619 if (BO0) {
5620 // Transform A & (L - 1) `ult` L --> L != 0
5621 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
5622 auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
5623
5624 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5625 auto *Zero = Constant::getNullValue(BO0->getType());
5626 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5627 }
5628 }
5629
5630 // For unsigned predicates / eq / ne:
5631 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5632 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5633 if (!ICmpInst::isSigned(Pred)) {
5634 if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
5635 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5636 Constant::getNullValue(Op1->getType()));
5637 else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
5638 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5639 Constant::getNullValue(Op0->getType()), Op0);
5640 }
5641
5643 return replaceInstUsesWith(I, V);
5644
5645 if (Instruction *R = foldICmpAndXX(I, Q, *this))
5646 return R;
5647
5649 return replaceInstUsesWith(I, V);
5650
5652 return replaceInstUsesWith(I, V);
5653
5654 return nullptr;
5655}
5656
5657/// Fold icmp Pred min|max(X, Y), Z.
5660 Value *Z, CmpPredicate Pred) {
5661 Value *X = MinMax->getLHS();
5662 Value *Y = MinMax->getRHS();
5663 if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5664 return nullptr;
5665 if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {
5666 // Revert the transform signed pred -> unsigned pred
5667 // TODO: We can flip the signedness of predicate if both operands of icmp
5668 // are negative.
5669 if (isKnownNonNegative(Z, SQ.getWithInstruction(&I)) &&
5670 isKnownNonNegative(MinMax, SQ.getWithInstruction(&I))) {
5672 } else
5673 return nullptr;
5674 }
5675 SimplifyQuery Q = SQ.getWithInstruction(&I);
5676 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5677 if (!Val)
5678 return std::nullopt;
5679 if (match(Val, m_One()))
5680 return true;
5681 if (match(Val, m_Zero()))
5682 return false;
5683 return std::nullopt;
5684 };
5685 // Remove samesign here since it is illegal to keep it when we speculatively
5686 // execute comparisons. For example, `icmp samesign ult umax(X, -46), -32`
5687 // cannot be decomposed into `(icmp samesign ult X, -46) or (icmp samesign ult
5688 // -46, -32)`. `X` is allowed to be non-negative here.
5689 Pred = Pred.dropSameSign();
5690 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, X, Z, Q));
5691 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, Y, Z, Q));
5692 if (!CmpXZ.has_value() && !CmpYZ.has_value())
5693 return nullptr;
5694 if (!CmpXZ.has_value()) {
5695 std::swap(X, Y);
5696 std::swap(CmpXZ, CmpYZ);
5697 }
5698
5699 auto FoldIntoCmpYZ = [&]() -> Instruction * {
5700 if (CmpYZ.has_value())
5701 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *CmpYZ));
5702 return ICmpInst::Create(Instruction::ICmp, Pred, Y, Z);
5703 };
5704
5705 switch (Pred) {
5706 case ICmpInst::ICMP_EQ:
5707 case ICmpInst::ICMP_NE: {
5708 // If X == Z:
5709 // Expr Result
5710 // min(X, Y) == Z X <= Y
5711 // max(X, Y) == Z X >= Y
5712 // min(X, Y) != Z X > Y
5713 // max(X, Y) != Z X < Y
5714 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5715 ICmpInst::Predicate NewPred =
5716 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
5717 if (Pred == ICmpInst::ICMP_NE)
5718 NewPred = ICmpInst::getInversePredicate(NewPred);
5719 return ICmpInst::Create(Instruction::ICmp, NewPred, X, Y);
5720 }
5721 // Otherwise (X != Z):
5722 ICmpInst::Predicate NewPred = MinMax->getPredicate();
5723 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5724 if (!MinMaxCmpXZ.has_value()) {
5725 std::swap(X, Y);
5726 std::swap(CmpXZ, CmpYZ);
5727 // Re-check pre-condition X != Z
5728 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5729 break;
5730 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5731 }
5732 if (!MinMaxCmpXZ.has_value())
5733 break;
5734 if (*MinMaxCmpXZ) {
5735 // Expr Fact Result
5736 // min(X, Y) == Z X < Z false
5737 // max(X, Y) == Z X > Z false
5738 // min(X, Y) != Z X < Z true
5739 // max(X, Y) != Z X > Z true
5740 return replaceInstUsesWith(
5741 I, ConstantInt::getBool(I.getType(), Pred == ICmpInst::ICMP_NE));
5742 } else {
5743 // Expr Fact Result
5744 // min(X, Y) == Z X > Z Y == Z
5745 // max(X, Y) == Z X < Z Y == Z
5746 // min(X, Y) != Z X > Z Y != Z
5747 // max(X, Y) != Z X < Z Y != Z
5748 return FoldIntoCmpYZ();
5749 }
5750 break;
5751 }
5752 case ICmpInst::ICMP_SLT:
5753 case ICmpInst::ICMP_ULT:
5754 case ICmpInst::ICMP_SLE:
5755 case ICmpInst::ICMP_ULE:
5756 case ICmpInst::ICMP_SGT:
5757 case ICmpInst::ICMP_UGT:
5758 case ICmpInst::ICMP_SGE:
5759 case ICmpInst::ICMP_UGE: {
5760 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(Pred);
5761 if (*CmpXZ) {
5762 if (IsSame) {
5763 // Expr Fact Result
5764 // min(X, Y) < Z X < Z true
5765 // min(X, Y) <= Z X <= Z true
5766 // max(X, Y) > Z X > Z true
5767 // max(X, Y) >= Z X >= Z true
5768 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5769 } else {
5770 // Expr Fact Result
5771 // max(X, Y) < Z X < Z Y < Z
5772 // max(X, Y) <= Z X <= Z Y <= Z
5773 // min(X, Y) > Z X > Z Y > Z
5774 // min(X, Y) >= Z X >= Z Y >= Z
5775 return FoldIntoCmpYZ();
5776 }
5777 } else {
5778 if (IsSame) {
5779 // Expr Fact Result
5780 // min(X, Y) < Z X >= Z Y < Z
5781 // min(X, Y) <= Z X > Z Y <= Z
5782 // max(X, Y) > Z X <= Z Y > Z
5783 // max(X, Y) >= Z X < Z Y >= Z
5784 return FoldIntoCmpYZ();
5785 } else {
5786 // Expr Fact Result
5787 // max(X, Y) < Z X >= Z false
5788 // max(X, Y) <= Z X > Z false
5789 // min(X, Y) > Z X <= Z false
5790 // min(X, Y) >= Z X < Z false
5791 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5792 }
5793 }
5794 break;
5795 }
5796 default:
5797 break;
5798 }
5799
5800 return nullptr;
5801}
5802
5803/// Match and fold patterns like:
5804/// icmp eq/ne X, min(max(X, Lo), Hi)
5805/// which represents a range check and can be repsented as a ConstantRange.
5806///
5807/// For icmp eq, build ConstantRange [Lo, Hi + 1) and convert to:
5808/// (X - Lo) u< (Hi + 1 - Lo)
5809/// For icmp ne, build ConstantRange [Hi + 1, Lo) and convert to:
5810/// (X - (Hi + 1)) u< (Lo - (Hi + 1))
5812 MinMaxIntrinsic *Min) {
5813 if (!I.isEquality() || !Min->hasOneUse() || !Min->isMin())
5814 return nullptr;
5815
5816 const APInt *Lo = nullptr, *Hi = nullptr;
5817 if (Min->isSigned()) {
5818 if (!match(Min->getLHS(), m_OneUse(m_SMax(m_Specific(X), m_APInt(Lo)))) ||
5819 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->slt(*Hi))
5820 return nullptr;
5821 } else {
5822 if (!match(Min->getLHS(), m_OneUse(m_UMax(m_Specific(X), m_APInt(Lo)))) ||
5823 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->ult(*Hi))
5824 return nullptr;
5825 }
5826
5829 APInt C, Offset;
5830 if (I.getPredicate() == ICmpInst::ICMP_EQ)
5831 CR.getEquivalentICmp(Pred, C, Offset);
5832 else
5833 CR.inverse().getEquivalentICmp(Pred, C, Offset);
5834
5835 if (!Offset.isZero())
5836 X = Builder.CreateAdd(X, ConstantInt::get(X->getType(), Offset));
5837
5838 return replaceInstUsesWith(
5839 I, Builder.CreateICmp(Pred, X, ConstantInt::get(X->getType(), C)));
5840}
5841
5842// Canonicalize checking for a power-of-2-or-zero value:
5844 InstCombiner::BuilderTy &Builder) {
5845 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5846 const CmpInst::Predicate Pred = I.getPredicate();
5847 Value *A = nullptr;
5848 bool CheckIs;
5849 if (I.isEquality()) {
5850 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
5851 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
5852 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
5853 m_Deferred(A)))) ||
5854 !match(Op1, m_ZeroInt()))
5855 A = nullptr;
5856
5857 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
5858 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
5859 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
5860 A = Op1;
5861 else if (match(Op1,
5863 A = Op0;
5864
5865 CheckIs = Pred == ICmpInst::ICMP_EQ;
5866 } else if (ICmpInst::isUnsigned(Pred)) {
5867 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
5868 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
5869
5870 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5872 m_Specific(Op1))))) {
5873 A = Op1;
5874 CheckIs = Pred == ICmpInst::ICMP_UGE;
5875 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5877 m_Specific(Op0))))) {
5878 A = Op0;
5879 CheckIs = Pred == ICmpInst::ICMP_ULE;
5880 }
5881 }
5882
5883 if (A) {
5884 Type *Ty = A->getType();
5885 CallInst *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
5886 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
5887 ConstantInt::get(Ty, 2))
5888 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
5889 ConstantInt::get(Ty, 1));
5890 }
5891
5892 return nullptr;
5893}
5894
5895/// Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
5896using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
5898 bool AllowRecursion) {
5900 if (!Inst || !Inst->hasOneUse())
5901 return;
5902
5903 switch (Inst->getOpcode()) {
5904 case Instruction::Add:
5905 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(1));
5906 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(0));
5907 break;
5908 case Instruction::Sub:
5909 Offsets.emplace_back(Instruction::Add, Inst->getOperand(1));
5910 break;
5911 case Instruction::Xor:
5912 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(1));
5913 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(0));
5914 break;
5915 case Instruction::Shl:
5916 if (Inst->hasNoSignedWrap())
5917 Offsets.emplace_back(Instruction::AShr, Inst->getOperand(1));
5918 if (Inst->hasNoUnsignedWrap())
5919 Offsets.emplace_back(Instruction::LShr, Inst->getOperand(1));
5920 break;
5921 case Instruction::Select:
5922 if (AllowRecursion) {
5923 collectOffsetOp(Inst->getOperand(1), Offsets, /*AllowRecursion=*/false);
5924 collectOffsetOp(Inst->getOperand(2), Offsets, /*AllowRecursion=*/false);
5925 }
5926 break;
5927 default:
5928 break;
5929 }
5930}
5931
5933
5938
5940 return {OffsetKind::Invalid, nullptr, nullptr, nullptr, nullptr};
5941 }
5943 return {OffsetKind::Value, V, nullptr, nullptr, nullptr};
5944 }
5945 static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV,
5947 return {OffsetKind::Select, Cond, TrueV, FalseV, MDFrom};
5948 }
5949 bool isValid() const { return Kind != OffsetKind::Invalid; }
5951 switch (Kind) {
5953 llvm_unreachable("Invalid offset result");
5954 case OffsetKind::Value:
5955 return V0;
5956 case OffsetKind::Select:
5957 return Builder.CreateSelect(
5958 V0, V1, V2, "", ProfcheckDisableMetadataFixes ? nullptr : MDFrom);
5959 }
5960 llvm_unreachable("Unknown OffsetKind enum");
5961 }
5962};
5963
5964/// Offset both sides of an equality icmp to see if we can save some
5965/// instructions: icmp eq/ne X, Y -> icmp eq/ne X op Z, Y op Z.
5966/// Note: This operation should not introduce poison.
5968 InstCombiner::BuilderTy &Builder,
5969 const SimplifyQuery &SQ) {
5970 assert(I.isEquality() && "Expected an equality icmp");
5971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5972 if (!Op0->getType()->isIntOrIntVectorTy())
5973 return nullptr;
5974
5975 SmallVector<OffsetOp, 4> OffsetOps;
5976 collectOffsetOp(Op0, OffsetOps, /*AllowRecursion=*/true);
5977 collectOffsetOp(Op1, OffsetOps, /*AllowRecursion=*/true);
5978
5979 auto ApplyOffsetImpl = [&](Value *V, unsigned BinOpc, Value *RHS) -> Value * {
5980 switch (BinOpc) {
5981 // V = shl nsw X, RHS => X = ashr V, RHS
5982 case Instruction::AShr: {
5983 const APInt *CV, *CRHS;
5984 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
5985 CV->ashr(*CRHS).shl(*CRHS) == *CV) &&
5987 return nullptr;
5988 break;
5989 }
5990 // V = shl nuw X, RHS => X = lshr V, RHS
5991 case Instruction::LShr: {
5992 const APInt *CV, *CRHS;
5993 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
5994 CV->lshr(*CRHS).shl(*CRHS) == *CV) &&
5996 return nullptr;
5997 break;
5998 }
5999 default:
6000 break;
6001 }
6002
6003 Value *Simplified = simplifyBinOp(BinOpc, V, RHS, SQ);
6004 if (!Simplified)
6005 return nullptr;
6006 // Reject constant expressions as they don't simplify things.
6007 if (isa<Constant>(Simplified) && !match(Simplified, m_ImmConstant()))
6008 return nullptr;
6009 // Check if the transformation introduces poison.
6010 return impliesPoison(RHS, V) ? Simplified : nullptr;
6011 };
6012
6013 auto ApplyOffset = [&](Value *V, unsigned BinOpc,
6014 Value *RHS) -> OffsetResult {
6015 if (auto *Sel = dyn_cast<SelectInst>(V)) {
6016 if (!Sel->hasOneUse())
6017 return OffsetResult::invalid();
6018 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc, RHS);
6019 if (!TrueVal)
6020 return OffsetResult::invalid();
6021 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc, RHS);
6022 if (!FalseVal)
6023 return OffsetResult::invalid();
6024 return OffsetResult::select(Sel->getCondition(), TrueVal, FalseVal, Sel);
6025 }
6026 if (Value *Simplified = ApplyOffsetImpl(V, BinOpc, RHS))
6027 return OffsetResult::value(Simplified);
6028 return OffsetResult::invalid();
6029 };
6030
6031 for (auto [BinOp, RHS] : OffsetOps) {
6032 auto BinOpc = static_cast<unsigned>(BinOp);
6033
6034 auto Op0Result = ApplyOffset(Op0, BinOpc, RHS);
6035 if (!Op0Result.isValid())
6036 continue;
6037 auto Op1Result = ApplyOffset(Op1, BinOpc, RHS);
6038 if (!Op1Result.isValid())
6039 continue;
6040
6041 Value *NewLHS = Op0Result.materialize(Builder);
6042 Value *NewRHS = Op1Result.materialize(Builder);
6043 return new ICmpInst(I.getPredicate(), NewLHS, NewRHS);
6044 }
6045
6046 return nullptr;
6047}
6048
6050 if (!I.isEquality())
6051 return nullptr;
6052
6053 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6054 const CmpInst::Predicate Pred = I.getPredicate();
6055 Value *A, *B, *C, *D;
6056 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6057 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6058 Value *OtherVal = A == Op1 ? B : A;
6059 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6060 }
6061
6062 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6063 // A^c1 == C^c2 --> A == C^(c1^c2)
6064 ConstantInt *C1, *C2;
6065 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
6066 Op1->hasOneUse()) {
6067 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
6068 Value *Xor = Builder.CreateXor(C, NC);
6069 return new ICmpInst(Pred, A, Xor);
6070 }
6071
6072 // A^B == A^D -> B == D
6073 if (A == C)
6074 return new ICmpInst(Pred, B, D);
6075 if (A == D)
6076 return new ICmpInst(Pred, B, C);
6077 if (B == C)
6078 return new ICmpInst(Pred, A, D);
6079 if (B == D)
6080 return new ICmpInst(Pred, A, C);
6081 }
6082 }
6083
6084 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
6085 // A == (A^B) -> B == 0
6086 Value *OtherVal = A == Op0 ? B : A;
6087 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6088 }
6089
6090 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6091 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
6092 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6093 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
6094
6095 if (A == C) {
6096 X = B;
6097 Y = D;
6098 Z = A;
6099 } else if (A == D) {
6100 X = B;
6101 Y = C;
6102 Z = A;
6103 } else if (B == C) {
6104 X = A;
6105 Y = D;
6106 Z = B;
6107 } else if (B == D) {
6108 X = A;
6109 Y = C;
6110 Z = B;
6111 }
6112
6113 if (X) {
6114 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
6115 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
6116 // instructions.
6117 const APInt *C0, *C1;
6118 bool XorIsNegP2 = match(X, m_APInt(C0)) && match(Y, m_APInt(C1)) &&
6119 (*C0 ^ *C1).isNegatedPowerOf2();
6120
6121 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
6122 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
6123 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
6124 int UseCnt =
6125 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
6126 (int(match(X, m_ImmConstant()) && match(Y, m_ImmConstant())));
6127 if (XorIsNegP2 || UseCnt >= 2) {
6128 // Build (X^Y) & Z
6129 Op1 = Builder.CreateXor(X, Y);
6130 Op1 = Builder.CreateAnd(Op1, Z);
6131 return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
6132 }
6133 }
6134 }
6135
6136 {
6137 // Similar to above, but specialized for constant because invert is needed:
6138 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
6139 Value *X, *Y;
6140 Constant *C;
6141 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
6142 match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
6143 Value *Xor = Builder.CreateXor(X, Y);
6144 Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
6145 return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
6146 }
6147 }
6148
6149 if (match(Op1, m_ZExt(m_Value(A))) &&
6150 (Op0->hasOneUse() || Op1->hasOneUse())) {
6151 // (B & (Pow2C-1)) == zext A --> A == trunc B
6152 // (B & (Pow2C-1)) != zext A --> A != trunc B
6153 const APInt *MaskC;
6154 if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
6155 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
6156 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
6157 }
6158
6159 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
6160 // For lshr and ashr pairs.
6161 const APInt *AP1, *AP2;
6162 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6163 match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowPoison(AP2))))) ||
6164 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6165 match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowPoison(AP2)))))) {
6166 if (*AP1 != *AP2)
6167 return nullptr;
6168 unsigned TypeBits = AP1->getBitWidth();
6169 unsigned ShAmt = AP1->getLimitedValue(TypeBits);
6170 if (ShAmt < TypeBits && ShAmt != 0) {
6171 ICmpInst::Predicate NewPred =
6173 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6174 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
6175 return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
6176 }
6177 }
6178
6179 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
6180 ConstantInt *Cst1;
6181 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
6182 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
6183 unsigned TypeBits = Cst1->getBitWidth();
6184 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
6185 if (ShAmt < TypeBits && ShAmt != 0) {
6186 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6187 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
6188 Value *And =
6189 Builder.CreateAnd(Xor, Builder.getInt(AndVal), I.getName() + ".mask");
6190 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
6191 }
6192 }
6193
6194 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
6195 // "icmp (and X, mask), cst"
6196 uint64_t ShAmt = 0;
6197 if (Op0->hasOneUse() &&
6198 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
6199 match(Op1, m_ConstantInt(Cst1)) &&
6200 // Only do this when A has multiple uses. This is most important to do
6201 // when it exposes other optimizations.
6202 !A->hasOneUse()) {
6203 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
6204
6205 if (ShAmt < ASize) {
6206 APInt MaskV =
6208 MaskV <<= ShAmt;
6209
6210 APInt CmpV = Cst1->getValue().zext(ASize);
6211 CmpV <<= ShAmt;
6212
6213 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
6214 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
6215 }
6216 }
6217
6219 return ICmp;
6220
6221 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
6222 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
6223 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
6224 // few steps of instcombine.
6225 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6226 if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
6228 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
6229 (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
6231 Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
6232 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
6234 Add, ConstantInt::get(A->getType(), C.shl(1)));
6235 }
6236
6237 // Canonicalize:
6238 // Assume B_Pow2 != 0
6239 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
6240 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
6241 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
6242 isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, &I))
6243 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
6245
6246 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
6247 isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, &I))
6248 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
6249 ConstantInt::getNullValue(Op1->getType()));
6250
6251 // Canonicalize:
6252 // icmp eq/ne X, OneUse(rotate-right(X))
6253 // -> icmp eq/ne X, rotate-left(X)
6254 // We generally try to convert rotate-right -> rotate-left, this just
6255 // canonicalizes another case.
6256 if (match(&I, m_c_ICmp(m_Value(A),
6258 m_Deferred(A), m_Deferred(A), m_Value(B))))))
6259 return new ICmpInst(
6260 Pred, A,
6261 Builder.CreateIntrinsic(Op0->getType(), Intrinsic::fshl, {A, A, B}));
6262
6263 // Canonicalize:
6264 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
6265 Constant *Cst;
6268 return new ICmpInst(Pred, Builder.CreateXor(A, B), Cst);
6269
6270 {
6271 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6272 auto m_Matcher =
6275 m_Sub(m_Value(B), m_Deferred(A)));
6276 std::optional<bool> IsZero = std::nullopt;
6277 if (match(&I, m_c_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)),
6278 m_Deferred(A))))
6279 IsZero = false;
6280 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6281 else if (match(&I,
6282 m_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)), m_Zero())))
6283 IsZero = true;
6284
6285 if (IsZero && isKnownToBeAPowerOfTwo(A, /* OrZero */ true, &I))
6286 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6287 // -> (icmp eq/ne (and X, P2), 0)
6288 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6289 // -> (icmp eq/ne (and X, P2), P2)
6290 return new ICmpInst(Pred, Builder.CreateAnd(B, A),
6291 *IsZero ? A
6292 : ConstantInt::getNullValue(A->getType()));
6293 }
6294
6295 if (auto *Res = foldICmpEqualityWithOffset(
6296 I, Builder, getSimplifyQuery().getWithInstruction(&I)))
6297 return Res;
6298
6299 return nullptr;
6300}
6301
6303 ICmpInst::Predicate Pred = ICmp.getPredicate();
6304 Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
6305
6306 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6307 // The trunc masks high bits while the compare may effectively mask low bits.
6308 Value *X;
6309 const APInt *C;
6310 if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
6311 return nullptr;
6312
6313 // This matches patterns corresponding to tests of the signbit as well as:
6314 // (trunc X) pred C2 --> (X & Mask) == C
6315 if (auto Res = decomposeBitTestICmp(Op0, Op1, Pred, /*LookThroughTrunc=*/true,
6316 /*AllowNonZeroC=*/true)) {
6317 Value *And = Builder.CreateAnd(Res->X, Res->Mask);
6318 Constant *C = ConstantInt::get(Res->X->getType(), Res->C);
6319 return new ICmpInst(Res->Pred, And, C);
6320 }
6321
6322 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6323 if (auto *II = dyn_cast<IntrinsicInst>(X)) {
6324 if (II->getIntrinsicID() == Intrinsic::cttz ||
6325 II->getIntrinsicID() == Intrinsic::ctlz) {
6326 unsigned MaxRet = SrcBits;
6327 // If the "is_zero_poison" argument is set, then we know at least
6328 // one bit is set in the input, so the result is always at least one
6329 // less than the full bitwidth of that input.
6330 if (match(II->getArgOperand(1), m_One()))
6331 MaxRet--;
6332
6333 // Make sure the destination is wide enough to hold the largest output of
6334 // the intrinsic.
6335 if (llvm::Log2_32(MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6336 if (Instruction *I =
6337 foldICmpIntrinsicWithConstant(ICmp, II, C->zext(SrcBits)))
6338 return I;
6339 }
6340 }
6341
6342 return nullptr;
6343}
6344
6346 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6347 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
6348 Value *X;
6349 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
6350 return nullptr;
6351
6352 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6353 bool IsSignedCmp = ICmp.isSigned();
6354
6355 // icmp Pred (ext X), (ext Y)
6356 Value *Y;
6357 if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
6358 bool IsZext0 = isa<ZExtInst>(ICmp.getOperand(0));
6359 bool IsZext1 = isa<ZExtInst>(ICmp.getOperand(1));
6360
6361 if (IsZext0 != IsZext1) {
6362 // If X and Y and both i1
6363 // (icmp eq/ne (zext X) (sext Y))
6364 // eq -> (icmp eq (or X, Y), 0)
6365 // ne -> (icmp ne (or X, Y), 0)
6366 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(1) &&
6367 Y->getType()->isIntOrIntVectorTy(1))
6368 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
6369 Constant::getNullValue(X->getType()));
6370
6371 // If we have mismatched casts and zext has the nneg flag, we can
6372 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6373
6374 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(0));
6375 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(1));
6376
6377 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6378 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6379
6380 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6381 IsSignedExt = true;
6382 else
6383 return nullptr;
6384 }
6385
6386 // Not an extension from the same type?
6387 Type *XTy = X->getType(), *YTy = Y->getType();
6388 if (XTy != YTy) {
6389 // One of the casts must have one use because we are creating a new cast.
6390 if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
6391 return nullptr;
6392 // Extend the narrower operand to the type of the wider operand.
6393 CastInst::CastOps CastOpcode =
6394 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6395 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6396 X = Builder.CreateCast(CastOpcode, X, YTy);
6397 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6398 Y = Builder.CreateCast(CastOpcode, Y, XTy);
6399 else
6400 return nullptr;
6401 }
6402
6403 // (zext X) == (zext Y) --> X == Y
6404 // (sext X) == (sext Y) --> X == Y
6405 if (ICmp.isEquality())
6406 return new ICmpInst(ICmp.getPredicate(), X, Y);
6407
6408 // A signed comparison of sign extended values simplifies into a
6409 // signed comparison.
6410 if (IsSignedCmp && IsSignedExt)
6411 return new ICmpInst(ICmp.getPredicate(), X, Y);
6412
6413 // The other three cases all fold into an unsigned comparison.
6414 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6415 }
6416
6417 // Below here, we are only folding a compare with constant.
6418 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
6419 if (!C)
6420 return nullptr;
6421
6422 // If a lossless truncate is possible...
6423 Type *SrcTy = CastOp0->getSrcTy();
6424 Constant *Res = getLosslessInvCast(C, SrcTy, CastOp0->getOpcode(), DL);
6425 if (Res) {
6426 if (ICmp.isEquality())
6427 return new ICmpInst(ICmp.getPredicate(), X, Res);
6428
6429 // A signed comparison of sign extended values simplifies into a
6430 // signed comparison.
6431 if (IsSignedExt && IsSignedCmp)
6432 return new ICmpInst(ICmp.getPredicate(), X, Res);
6433
6434 // The other three cases all fold into an unsigned comparison.
6435 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6436 }
6437
6438 // The re-extended constant changed, partly changed (in the case of a vector),
6439 // or could not be determined to be equal (in the case of a constant
6440 // expression), so the constant cannot be represented in the shorter type.
6441 // All the cases that fold to true or false will have already been handled
6442 // by simplifyICmpInst, so only deal with the tricky case.
6443 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
6444 return nullptr;
6445
6446 // Is source op positive?
6447 // icmp ult (sext X), C --> icmp sgt X, -1
6448 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6450
6451 // Is source op negative?
6452 // icmp ugt (sext X), C --> icmp slt X, 0
6453 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6455}
6456
6457/// Handle icmp (cast x), (cast or constant).
6459 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6460 // icmp compares only pointer's value.
6461 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6462 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
6463 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
6464 if (SimplifiedOp0 || SimplifiedOp1)
6465 return new ICmpInst(ICmp.getPredicate(),
6466 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
6467 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
6468
6469 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
6470 if (!CastOp0)
6471 return nullptr;
6472 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
6473 return nullptr;
6474
6475 Value *Op0Src = CastOp0->getOperand(0);
6476 Type *SrcTy = CastOp0->getSrcTy();
6477 Type *DestTy = CastOp0->getDestTy();
6478
6479 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6480 // integer type is the same size as the pointer type.
6481 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6482 if (isa<VectorType>(PtrTy)) {
6483 PtrTy = cast<VectorType>(PtrTy)->getElementType();
6484 IntTy = cast<VectorType>(IntTy)->getElementType();
6485 }
6486 return DL.getPointerTypeSizeInBits(PtrTy) == IntTy->getIntegerBitWidth();
6487 };
6488 if (CastOp0->getOpcode() == Instruction::PtrToInt &&
6489 CompatibleSizes(SrcTy, DestTy)) {
6490 Value *NewOp1 = nullptr;
6491 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
6492 Value *PtrSrc = PtrToIntOp1->getOperand(0);
6493 if (PtrSrc->getType() == Op0Src->getType())
6494 NewOp1 = PtrToIntOp1->getOperand(0);
6495 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
6496 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6497 }
6498
6499 if (NewOp1)
6500 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6501 }
6502
6503 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6504 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6505 CompatibleSizes(DestTy, SrcTy)) {
6506 Value *NewOp1 = nullptr;
6507 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(ICmp.getOperand(1))) {
6508 Value *IntSrc = IntToPtrOp1->getOperand(0);
6509 if (IntSrc->getType() == Op0Src->getType())
6510 NewOp1 = IntToPtrOp1->getOperand(0);
6511 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
6512 NewOp1 = ConstantFoldConstant(ConstantExpr::getPtrToInt(RHSC, SrcTy), DL);
6513 }
6514
6515 if (NewOp1)
6516 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6517 }
6518
6519 if (Instruction *R = foldICmpWithTrunc(ICmp))
6520 return R;
6521
6522 return foldICmpWithZextOrSext(ICmp);
6523}
6524
6526 bool IsSigned) {
6527 switch (BinaryOp) {
6528 default:
6529 llvm_unreachable("Unsupported binary op");
6530 case Instruction::Add:
6531 case Instruction::Sub:
6532 return match(RHS, m_Zero());
6533 case Instruction::Mul:
6534 return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
6535 match(RHS, m_One());
6536 }
6537}
6538
6541 bool IsSigned, Value *LHS, Value *RHS,
6542 Instruction *CxtI) const {
6543 switch (BinaryOp) {
6544 default:
6545 llvm_unreachable("Unsupported binary op");
6546 case Instruction::Add:
6547 if (IsSigned)
6548 return computeOverflowForSignedAdd(LHS, RHS, CxtI);
6549 else
6550 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
6551 case Instruction::Sub:
6552 if (IsSigned)
6553 return computeOverflowForSignedSub(LHS, RHS, CxtI);
6554 else
6555 return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
6556 case Instruction::Mul:
6557 if (IsSigned)
6558 return computeOverflowForSignedMul(LHS, RHS, CxtI);
6559 else
6560 return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
6561 }
6562}
6563
6564bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6565 bool IsSigned, Value *LHS,
6566 Value *RHS, Instruction &OrigI,
6567 Value *&Result,
6568 Constant *&Overflow) {
6569 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
6570 std::swap(LHS, RHS);
6571
6572 // If the overflow check was an add followed by a compare, the insertion point
6573 // may be pointing to the compare. We want to insert the new instructions
6574 // before the add in case there are uses of the add between the add and the
6575 // compare.
6576 Builder.SetInsertPoint(&OrigI);
6577
6578 Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
6579 if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
6580 OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
6581
6582 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6583 Result = LHS;
6584 Overflow = ConstantInt::getFalse(OverflowTy);
6585 return true;
6586 }
6587
6588 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
6590 return false;
6593 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6594 Result->takeName(&OrigI);
6595 Overflow = ConstantInt::getTrue(OverflowTy);
6596 return true;
6598 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6599 Result->takeName(&OrigI);
6600 Overflow = ConstantInt::getFalse(OverflowTy);
6601 if (auto *Inst = dyn_cast<Instruction>(Result)) {
6602 if (IsSigned)
6603 Inst->setHasNoSignedWrap();
6604 else
6605 Inst->setHasNoUnsignedWrap();
6606 }
6607 return true;
6608 }
6609
6610 llvm_unreachable("Unexpected overflow result");
6611}
6612
6613/// Recognize and process idiom involving test for multiplication
6614/// overflow.
6615///
6616/// The caller has matched a pattern of the form:
6617/// I = cmp u (mul(zext A, zext B), V
6618/// The function checks if this is a test for overflow and if so replaces
6619/// multiplication with call to 'mul.with.overflow' intrinsic.
6620///
6621/// \param I Compare instruction.
6622/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
6623/// the compare instruction. Must be of integer type.
6624/// \param OtherVal The other argument of compare instruction.
6625/// \returns Instruction which must replace the compare instruction, NULL if no
6626/// replacement required.
6628 const APInt *OtherVal,
6629 InstCombinerImpl &IC) {
6630 // Don't bother doing this transformation for pointers, don't do it for
6631 // vectors.
6632 if (!isa<IntegerType>(MulVal->getType()))
6633 return nullptr;
6634
6635 auto *MulInstr = dyn_cast<Instruction>(MulVal);
6636 if (!MulInstr)
6637 return nullptr;
6638 assert(MulInstr->getOpcode() == Instruction::Mul);
6639
6640 auto *LHS = cast<ZExtInst>(MulInstr->getOperand(0)),
6641 *RHS = cast<ZExtInst>(MulInstr->getOperand(1));
6642 assert(LHS->getOpcode() == Instruction::ZExt);
6643 assert(RHS->getOpcode() == Instruction::ZExt);
6644 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
6645
6646 // Calculate type and width of the result produced by mul.with.overflow.
6647 Type *TyA = A->getType(), *TyB = B->getType();
6648 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6649 WidthB = TyB->getPrimitiveSizeInBits();
6650 unsigned MulWidth;
6651 Type *MulType;
6652 if (WidthB > WidthA) {
6653 MulWidth = WidthB;
6654 MulType = TyB;
6655 } else {
6656 MulWidth = WidthA;
6657 MulType = TyA;
6658 }
6659
6660 // In order to replace the original mul with a narrower mul.with.overflow,
6661 // all uses must ignore upper bits of the product. The number of used low
6662 // bits must be not greater than the width of mul.with.overflow.
6663 if (MulVal->hasNUsesOrMore(2))
6664 for (User *U : MulVal->users()) {
6665 if (U == &I)
6666 continue;
6667 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6668 // Check if truncation ignores bits above MulWidth.
6669 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
6670 if (TruncWidth > MulWidth)
6671 return nullptr;
6672 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6673 // Check if AND ignores bits above MulWidth.
6674 if (BO->getOpcode() != Instruction::And)
6675 return nullptr;
6676 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6677 const APInt &CVal = CI->getValue();
6678 if (CVal.getBitWidth() - CVal.countl_zero() > MulWidth)
6679 return nullptr;
6680 } else {
6681 // In this case we could have the operand of the binary operation
6682 // being defined in another block, and performing the replacement
6683 // could break the dominance relation.
6684 return nullptr;
6685 }
6686 } else {
6687 // Other uses prohibit this transformation.
6688 return nullptr;
6689 }
6690 }
6691
6692 // Recognize patterns
6693 switch (I.getPredicate()) {
6694 case ICmpInst::ICMP_UGT: {
6695 // Recognize pattern:
6696 // mulval = mul(zext A, zext B)
6697 // cmp ugt mulval, max
6698 APInt MaxVal = APInt::getMaxValue(MulWidth);
6699 MaxVal = MaxVal.zext(OtherVal->getBitWidth());
6700 if (MaxVal.eq(*OtherVal))
6701 break; // Recognized
6702 return nullptr;
6703 }
6704
6705 case ICmpInst::ICMP_ULT: {
6706 // Recognize pattern:
6707 // mulval = mul(zext A, zext B)
6708 // cmp ule mulval, max + 1
6709 APInt MaxVal = APInt::getOneBitSet(OtherVal->getBitWidth(), MulWidth);
6710 if (MaxVal.eq(*OtherVal))
6711 break; // Recognized
6712 return nullptr;
6713 }
6714
6715 default:
6716 return nullptr;
6717 }
6718
6719 InstCombiner::BuilderTy &Builder = IC.Builder;
6720 Builder.SetInsertPoint(MulInstr);
6721
6722 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
6723 Value *MulA = A, *MulB = B;
6724 if (WidthA < MulWidth)
6725 MulA = Builder.CreateZExt(A, MulType);
6726 if (WidthB < MulWidth)
6727 MulB = Builder.CreateZExt(B, MulType);
6728 CallInst *Call =
6729 Builder.CreateIntrinsic(Intrinsic::umul_with_overflow, MulType,
6730 {MulA, MulB}, /*FMFSource=*/nullptr, "umul");
6731 IC.addToWorklist(MulInstr);
6732
6733 // If there are uses of mul result other than the comparison, we know that
6734 // they are truncation or binary AND. Change them to use result of
6735 // mul.with.overflow and adjust properly mask/size.
6736 if (MulVal->hasNUsesOrMore(2)) {
6737 Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value");
6738 for (User *U : make_early_inc_range(MulVal->users())) {
6739 if (U == &I)
6740 continue;
6741 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6742 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
6743 IC.replaceInstUsesWith(*TI, Mul);
6744 else
6745 TI->setOperand(0, Mul);
6746 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6747 assert(BO->getOpcode() == Instruction::And);
6748 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
6749 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
6750 APInt ShortMask = CI->getValue().trunc(MulWidth);
6751 Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask);
6752 Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
6753 IC.replaceInstUsesWith(*BO, Zext);
6754 } else {
6755 llvm_unreachable("Unexpected Binary operation");
6756 }
6758 }
6759 }
6760
6761 // The original icmp gets replaced with the overflow value, maybe inverted
6762 // depending on predicate.
6763 if (I.getPredicate() == ICmpInst::ICMP_ULT) {
6764 Value *Res = Builder.CreateExtractValue(Call, 1);
6765 return BinaryOperator::CreateNot(Res);
6766 }
6767
6768 return ExtractValueInst::Create(Call, 1);
6769}
6770
6771/// When performing a comparison against a constant, it is possible that not all
6772/// the bits in the LHS are demanded. This helper method computes the mask that
6773/// IS demanded.
6775 const APInt *RHS;
6776 if (!match(I.getOperand(1), m_APInt(RHS)))
6778
6779 // If this is a normal comparison, it demands all bits. If it is a sign bit
6780 // comparison, it only demands the sign bit.
6781 bool UnusedBit;
6782 if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
6784
6785 switch (I.getPredicate()) {
6786 // For a UGT comparison, we don't care about any bits that
6787 // correspond to the trailing ones of the comparand. The value of these
6788 // bits doesn't impact the outcome of the comparison, because any value
6789 // greater than the RHS must differ in a bit higher than these due to carry.
6790 case ICmpInst::ICMP_UGT:
6791 return APInt::getBitsSetFrom(BitWidth, RHS->countr_one());
6792
6793 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
6794 // Any value less than the RHS must differ in a higher bit because of carries.
6795 case ICmpInst::ICMP_ULT:
6796 return APInt::getBitsSetFrom(BitWidth, RHS->countr_zero());
6797
6798 default:
6800 }
6801}
6802
6803/// Check that one use is in the same block as the definition and all
6804/// other uses are in blocks dominated by a given block.
6805///
6806/// \param DI Definition
6807/// \param UI Use
6808/// \param DB Block that must dominate all uses of \p DI outside
6809/// the parent block
6810/// \return true when \p UI is the only use of \p DI in the parent block
6811/// and all other uses of \p DI are in blocks dominated by \p DB.
6812///
6814 const Instruction *UI,
6815 const BasicBlock *DB) const {
6816 assert(DI && UI && "Instruction not defined\n");
6817 // Ignore incomplete definitions.
6818 if (!DI->getParent())
6819 return false;
6820 // DI and UI must be in the same block.
6821 if (DI->getParent() != UI->getParent())
6822 return false;
6823 // Protect from self-referencing blocks.
6824 if (DI->getParent() == DB)
6825 return false;
6826 for (const User *U : DI->users()) {
6827 auto *Usr = cast<Instruction>(U);
6828 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
6829 return false;
6830 }
6831 return true;
6832}
6833
6834/// Return true when the instruction sequence within a block is select-cmp-br.
6836 const BasicBlock *BB = SI->getParent();
6837 if (!BB)
6838 return false;
6840 if (!BI || BI->getNumSuccessors() != 2)
6841 return false;
6842 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
6843 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
6844 return false;
6845 return true;
6846}
6847
6848/// True when a select result is replaced by one of its operands
6849/// in select-icmp sequence. This will eventually result in the elimination
6850/// of the select.
6851///
6852/// \param SI Select instruction
6853/// \param Icmp Compare instruction
6854/// \param SIOpd Operand that replaces the select
6855///
6856/// Notes:
6857/// - The replacement is global and requires dominator information
6858/// - The caller is responsible for the actual replacement
6859///
6860/// Example:
6861///
6862/// entry:
6863/// %4 = select i1 %3, %C* %0, %C* null
6864/// %5 = icmp eq %C* %4, null
6865/// br i1 %5, label %9, label %7
6866/// ...
6867/// ; <label>:7 ; preds = %entry
6868/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
6869/// ...
6870///
6871/// can be transformed to
6872///
6873/// %5 = icmp eq %C* %0, null
6874/// %6 = select i1 %3, i1 %5, i1 true
6875/// br i1 %6, label %9, label %7
6876/// ...
6877/// ; <label>:7 ; preds = %entry
6878/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
6879///
6880/// Similar when the first operand of the select is a constant or/and
6881/// the compare is for not equal rather than equal.
6882///
6883/// NOTE: The function is only called when the select and compare constants
6884/// are equal, the optimization can work only for EQ predicates. This is not a
6885/// major restriction since a NE compare should be 'normalized' to an equal
6886/// compare, which usually happens in the combiner and test case
6887/// select-cmp-br.ll checks for it.
6889 const ICmpInst *Icmp,
6890 const unsigned SIOpd) {
6891 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
6893 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
6894 // The check for the single predecessor is not the best that can be
6895 // done. But it protects efficiently against cases like when SI's
6896 // home block has two successors, Succ and Succ1, and Succ1 predecessor
6897 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
6898 // replaced can be reached on either path. So the uniqueness check
6899 // guarantees that the path all uses of SI (outside SI's parent) are on
6900 // is disjoint from all other paths out of SI. But that information
6901 // is more expensive to compute, and the trade-off here is in favor
6902 // of compile-time. It should also be noticed that we check for a single
6903 // predecessor and not only uniqueness. This to handle the situation when
6904 // Succ and Succ1 points to the same basic block.
6905 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
6906 NumSel++;
6907 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
6908 return true;
6909 }
6910 }
6911 return false;
6912}
6913
6914/// Try to fold the comparison based on range information we can get by checking
6915/// whether bits are known to be zero or one in the inputs.
6917 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6918 Type *Ty = Op0->getType();
6919 ICmpInst::Predicate Pred = I.getPredicate();
6920
6921 // Get scalar or pointer size.
6922 unsigned BitWidth = Ty->isIntOrIntVectorTy()
6923 ? Ty->getScalarSizeInBits()
6924 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
6925
6926 if (!BitWidth)
6927 return nullptr;
6928
6929 KnownBits Op0Known(BitWidth);
6930 KnownBits Op1Known(BitWidth);
6931
6932 {
6933 // Don't use dominating conditions when folding icmp using known bits. This
6934 // may convert signed into unsigned predicates in ways that other passes
6935 // (especially IndVarSimplify) may not be able to reliably undo.
6936 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(&I);
6938 Op0Known, Q))
6939 return &I;
6940
6941 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, Q))
6942 return &I;
6943 }
6944
6945 if (!isa<Constant>(Op0) && Op0Known.isConstant())
6946 return new ICmpInst(
6947 Pred, ConstantExpr::getIntegerValue(Ty, Op0Known.getConstant()), Op1);
6948 if (!isa<Constant>(Op1) && Op1Known.isConstant())
6949 return new ICmpInst(
6950 Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Known.getConstant()));
6951
6952 if (std::optional<bool> Res = ICmpInst::compare(Op0Known, Op1Known, Pred))
6953 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *Res));
6954
6955 // Given the known and unknown bits, compute a range that the LHS could be
6956 // in. Compute the Min, Max and RHS values based on the known bits. For the
6957 // EQ and NE we use unsigned values.
6958 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6959 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6960 if (I.isSigned()) {
6961 Op0Min = Op0Known.getSignedMinValue();
6962 Op0Max = Op0Known.getSignedMaxValue();
6963 Op1Min = Op1Known.getSignedMinValue();
6964 Op1Max = Op1Known.getSignedMaxValue();
6965 } else {
6966 Op0Min = Op0Known.getMinValue();
6967 Op0Max = Op0Known.getMaxValue();
6968 Op1Min = Op1Known.getMinValue();
6969 Op1Max = Op1Known.getMaxValue();
6970 }
6971
6972 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
6973 // min/max canonical compare with some other compare. That could lead to
6974 // conflict with select canonicalization and infinite looping.
6975 // FIXME: This constraint may go away if min/max intrinsics are canonical.
6976 auto isMinMaxCmp = [&](Instruction &Cmp) {
6977 if (!Cmp.hasOneUse())
6978 return false;
6979 Value *A, *B;
6980 SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
6982 return false;
6983 return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
6984 match(Op1, m_MaxOrMin(m_Value(), m_Value()));
6985 };
6986 if (!isMinMaxCmp(I)) {
6987 switch (Pred) {
6988 default:
6989 break;
6990 case ICmpInst::ICMP_ULT: {
6991 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6992 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6993 const APInt *CmpC;
6994 if (match(Op1, m_APInt(CmpC))) {
6995 // A <u C -> A == C-1 if min(A)+1 == C
6996 if (*CmpC == Op0Min + 1)
6997 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6998 ConstantInt::get(Op1->getType(), *CmpC - 1));
6999 // X <u C --> X == 0, if the number of zero bits in the bottom of X
7000 // exceeds the log2 of C.
7001 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
7002 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7003 Constant::getNullValue(Op1->getType()));
7004 }
7005 break;
7006 }
7007 case ICmpInst::ICMP_UGT: {
7008 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
7009 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7010 const APInt *CmpC;
7011 if (match(Op1, m_APInt(CmpC))) {
7012 // A >u C -> A == C+1 if max(a)-1 == C
7013 if (*CmpC == Op0Max - 1)
7014 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7015 ConstantInt::get(Op1->getType(), *CmpC + 1));
7016 // X >u C --> X != 0, if the number of zero bits in the bottom of X
7017 // exceeds the log2 of C.
7018 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
7019 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
7020 Constant::getNullValue(Op1->getType()));
7021 }
7022 break;
7023 }
7024 case ICmpInst::ICMP_SLT: {
7025 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
7026 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7027 const APInt *CmpC;
7028 if (match(Op1, m_APInt(CmpC))) {
7029 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
7030 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7031 ConstantInt::get(Op1->getType(), *CmpC - 1));
7032 }
7033 break;
7034 }
7035 case ICmpInst::ICMP_SGT: {
7036 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
7037 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7038 const APInt *CmpC;
7039 if (match(Op1, m_APInt(CmpC))) {
7040 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
7041 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7042 ConstantInt::get(Op1->getType(), *CmpC + 1));
7043 }
7044 break;
7045 }
7046 }
7047 }
7048
7049 // Based on the range information we know about the LHS, see if we can
7050 // simplify this comparison. For example, (x&4) < 8 is always true.
7051 switch (Pred) {
7052 default:
7053 break;
7054 case ICmpInst::ICMP_EQ:
7055 case ICmpInst::ICMP_NE: {
7056 // If all bits are known zero except for one, then we know at most one bit
7057 // is set. If the comparison is against zero, then this is a check to see if
7058 // *that* bit is set.
7059 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
7060 if (Op1Known.isZero()) {
7061 // If the LHS is an AND with the same constant, look through it.
7062 Value *LHS = nullptr;
7063 const APInt *LHSC;
7064 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
7065 *LHSC != Op0KnownZeroInverted)
7066 LHS = Op0;
7067
7068 Value *X;
7069 const APInt *C1;
7070 if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
7071 Type *XTy = X->getType();
7072 unsigned Log2C1 = C1->countr_zero();
7073 APInt C2 = Op0KnownZeroInverted;
7074 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
7075 if (C2Pow2.isPowerOf2()) {
7076 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
7077 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
7078 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
7079 unsigned Log2C2 = C2Pow2.countr_zero();
7080 auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
7081 auto NewPred =
7083 return new ICmpInst(NewPred, X, CmpC);
7084 }
7085 }
7086 }
7087
7088 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
7089 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
7090 (Op0Known & Op1Known) == Op0Known)
7091 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
7092 ConstantInt::getNullValue(Op1->getType()));
7093 break;
7094 }
7095 case ICmpInst::ICMP_SGE:
7096 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
7097 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7098 break;
7099 case ICmpInst::ICMP_SLE:
7100 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
7101 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7102 break;
7103 case ICmpInst::ICMP_UGE:
7104 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
7105 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7106 break;
7107 case ICmpInst::ICMP_ULE:
7108 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
7109 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7110 break;
7111 }
7112
7113 // Turn a signed comparison into an unsigned one if both operands are known to
7114 // have the same sign. Set samesign if possible (except for equality
7115 // predicates).
7116 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
7117 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
7118 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
7119 I.setPredicate(I.getUnsignedPredicate());
7120 I.setSameSign();
7121 return &I;
7122 }
7123
7124 return nullptr;
7125}
7126
7127/// If one operand of an icmp is effectively a bool (value range of {0,1}),
7128/// then try to reduce patterns based on that limit.
7130 Value *X, *Y;
7131 CmpPredicate Pred;
7132
7133 // X must be 0 and bool must be true for "ULT":
7134 // X <u (zext i1 Y) --> (X == 0) & Y
7135 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
7136 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
7137 return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
7138
7139 // X must be 0 or bool must be true for "ULE":
7140 // X <=u (sext i1 Y) --> (X == 0) | Y
7141 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
7142 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
7143 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
7144
7145 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
7146 CmpPredicate Pred1, Pred2;
7147 const APInt *C;
7148 Instruction *ExtI;
7149 if (match(&I, m_c_ICmp(Pred1, m_Value(X),
7152 m_APInt(C)))))) &&
7153 ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
7154 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
7155 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(0)->hasOneUse();
7156 auto CreateRangeCheck = [&] {
7157 Value *CmpV1 =
7158 Builder.CreateICmp(Pred1, X, Constant::getNullValue(X->getType()));
7159 Value *CmpV2 = Builder.CreateICmp(
7160 Pred1, X, ConstantInt::getSigned(X->getType(), IsSExt ? -1 : 1));
7162 Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
7163 CmpV1, CmpV2);
7164 };
7165 if (C->isZero()) {
7166 if (Pred2 == ICmpInst::ICMP_EQ) {
7167 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
7168 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
7169 return replaceInstUsesWith(
7170 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7171 } else if (!IsSExt || HasOneUse) {
7172 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
7173 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
7174 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
7175 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X != -1
7176 return CreateRangeCheck();
7177 }
7178 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
7179 if (Pred2 == ICmpInst::ICMP_NE) {
7180 // icmp eq X, (zext (icmp ne X, 1)) --> false
7181 // icmp ne X, (zext (icmp ne X, 1)) --> true
7182 // icmp eq X, (sext (icmp ne X, -1)) --> false
7183 // icmp ne X, (sext (icmp ne X, -1)) --> true
7184 return replaceInstUsesWith(
7185 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7186 } else if (!IsSExt || HasOneUse) {
7187 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
7188 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
7189 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
7190 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
7191 return CreateRangeCheck();
7192 }
7193 } else {
7194 // when C != 0 && C != 1:
7195 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
7196 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
7197 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
7198 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
7199 // when C != 0 && C != -1:
7200 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
7201 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
7202 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
7203 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
7204 return ICmpInst::Create(
7205 Instruction::ICmp, Pred1, X,
7206 ConstantInt::getSigned(X->getType(), Pred2 == ICmpInst::ICMP_NE
7207 ? (IsSExt ? -1 : 1)
7208 : 0));
7209 }
7210 }
7211
7212 return nullptr;
7213}
7214
7215/// If we have an icmp le or icmp ge instruction with a constant operand, turn
7216/// it into the appropriate icmp lt or icmp gt instruction. This transform
7217/// allows them to be folded in visitICmpInst.
7219 ICmpInst::Predicate Pred = I.getPredicate();
7220 if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
7222 return nullptr;
7223
7224 Value *Op0 = I.getOperand(0);
7225 Value *Op1 = I.getOperand(1);
7226 auto *Op1C = dyn_cast<Constant>(Op1);
7227 if (!Op1C)
7228 return nullptr;
7229
7230 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
7231 if (!FlippedStrictness)
7232 return nullptr;
7233
7234 return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7235}
7236
7237/// If we have a comparison with a non-canonical predicate, if we can update
7238/// all the users, invert the predicate and adjust all the users.
7240 // Is the predicate already canonical?
7241 CmpInst::Predicate Pred = I.getPredicate();
7243 return nullptr;
7244
7245 // Can all users be adjusted to predicate inversion?
7246 if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
7247 return nullptr;
7248
7249 // Ok, we can canonicalize comparison!
7250 // Let's first invert the comparison's predicate.
7251 I.setPredicate(CmpInst::getInversePredicate(Pred));
7252 I.setName(I.getName() + ".not");
7253
7254 // And, adapt users.
7256
7257 return &I;
7258}
7259
7260/// Integer compare with boolean values can always be turned into bitwise ops.
7262 InstCombiner::BuilderTy &Builder) {
7263 Value *A = I.getOperand(0), *B = I.getOperand(1);
7264 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
7265
7266 // A boolean compared to true/false can be simplified to Op0/true/false in
7267 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
7268 // Cases not handled by InstSimplify are always 'not' of Op0.
7269 if (match(B, m_Zero())) {
7270 switch (I.getPredicate()) {
7271 case CmpInst::ICMP_EQ: // A == 0 -> !A
7272 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
7273 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7275 default:
7276 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7277 }
7278 } else if (match(B, m_One())) {
7279 switch (I.getPredicate()) {
7280 case CmpInst::ICMP_NE: // A != 1 -> !A
7281 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7282 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7284 default:
7285 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7286 }
7287 }
7288
7289 switch (I.getPredicate()) {
7290 default:
7291 llvm_unreachable("Invalid icmp instruction!");
7292 case ICmpInst::ICMP_EQ:
7293 // icmp eq i1 A, B -> ~(A ^ B)
7294 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
7295
7296 case ICmpInst::ICMP_NE:
7297 // icmp ne i1 A, B -> A ^ B
7298 return BinaryOperator::CreateXor(A, B);
7299
7300 case ICmpInst::ICMP_UGT:
7301 // icmp ugt -> icmp ult
7302 std::swap(A, B);
7303 [[fallthrough]];
7304 case ICmpInst::ICMP_ULT:
7305 // icmp ult i1 A, B -> ~A & B
7306 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
7307
7308 case ICmpInst::ICMP_SGT:
7309 // icmp sgt -> icmp slt
7310 std::swap(A, B);
7311 [[fallthrough]];
7312 case ICmpInst::ICMP_SLT:
7313 // icmp slt i1 A, B -> A & ~B
7314 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
7315
7316 case ICmpInst::ICMP_UGE:
7317 // icmp uge -> icmp ule
7318 std::swap(A, B);
7319 [[fallthrough]];
7320 case ICmpInst::ICMP_ULE:
7321 // icmp ule i1 A, B -> ~A | B
7322 return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
7323
7324 case ICmpInst::ICMP_SGE:
7325 // icmp sge -> icmp sle
7326 std::swap(A, B);
7327 [[fallthrough]];
7328 case ICmpInst::ICMP_SLE:
7329 // icmp sle i1 A, B -> A | ~B
7330 return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
7331 }
7332}
7333
7334// Transform pattern like:
7335// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7336// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7337// Into:
7338// (X l>> Y) != 0
7339// (X l>> Y) == 0
7341 InstCombiner::BuilderTy &Builder) {
7342 CmpPredicate Pred, NewPred;
7343 Value *X, *Y;
7344 if (match(&Cmp,
7345 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
7346 switch (Pred) {
7347 case ICmpInst::ICMP_ULE:
7348 NewPred = ICmpInst::ICMP_NE;
7349 break;
7350 case ICmpInst::ICMP_UGT:
7351 NewPred = ICmpInst::ICMP_EQ;
7352 break;
7353 default:
7354 return nullptr;
7355 }
7356 } else if (match(&Cmp, m_c_ICmp(Pred,
7359 m_Add(m_Shl(m_One(), m_Value(Y)),
7360 m_AllOnes()))),
7361 m_Value(X)))) {
7362 // The variant with 'add' is not canonical, (the variant with 'not' is)
7363 // we only get it because it has extra uses, and can't be canonicalized,
7364
7365 switch (Pred) {
7366 case ICmpInst::ICMP_ULT:
7367 NewPred = ICmpInst::ICMP_NE;
7368 break;
7369 case ICmpInst::ICMP_UGE:
7370 NewPred = ICmpInst::ICMP_EQ;
7371 break;
7372 default:
7373 return nullptr;
7374 }
7375 } else
7376 return nullptr;
7377
7378 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
7379 Constant *Zero = Constant::getNullValue(NewX->getType());
7380 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
7381}
7382
7384 InstCombiner::BuilderTy &Builder) {
7385 const CmpInst::Predicate Pred = Cmp.getPredicate();
7386 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
7387 Value *V1, *V2;
7388
7389 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7390 Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
7391 if (auto *I = dyn_cast<Instruction>(V))
7392 I->copyIRFlags(&Cmp);
7393 Module *M = Cmp.getModule();
7395 M, Intrinsic::vector_reverse, V->getType());
7396 return CallInst::Create(F, V);
7397 };
7398
7399 if (match(LHS, m_VecReverse(m_Value(V1)))) {
7400 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7401 if (match(RHS, m_VecReverse(m_Value(V2))) &&
7402 (LHS->hasOneUse() || RHS->hasOneUse()))
7403 return createCmpReverse(Pred, V1, V2);
7404
7405 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7406 if (LHS->hasOneUse() && isSplatValue(RHS))
7407 return createCmpReverse(Pred, V1, RHS);
7408 }
7409 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7410 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
7411 return createCmpReverse(Pred, LHS, V2);
7412
7413 ArrayRef<int> M;
7414 if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
7415 return nullptr;
7416
7417 // If both arguments of the cmp are shuffles that use the same mask and
7418 // shuffle within a single vector, move the shuffle after the cmp:
7419 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7420 Type *V1Ty = V1->getType();
7421 if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
7422 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7423 Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
7424 return new ShuffleVectorInst(NewCmp, M);
7425 }
7426
7427 // Try to canonicalize compare with splatted operand and splat constant.
7428 // TODO: We could generalize this for more than splats. See/use the code in
7429 // InstCombiner::foldVectorBinop().
7430 Constant *C;
7431 if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
7432 return nullptr;
7433
7434 // Length-changing splats are ok, so adjust the constants as needed:
7435 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7436 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7437 int MaskSplatIndex;
7438 if (ScalarC && match(M, m_SplatOrPoisonMask(MaskSplatIndex))) {
7439 // We allow poison in matching, but this transform removes it for safety.
7440 // Demanded elements analysis should be able to recover some/all of that.
7441 C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
7442 ScalarC);
7443 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7444 Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
7445 return new ShuffleVectorInst(NewCmp, NewM);
7446 }
7447
7448 return nullptr;
7449}
7450
7451// extract(uadd.with.overflow(A, B), 0) ult A
7452// -> extract(uadd.with.overflow(A, B), 1)
7454 CmpInst::Predicate Pred = I.getPredicate();
7455 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7456
7457 Value *UAddOv;
7458 Value *A, *B;
7459 auto UAddOvResultPat = m_ExtractValue<0>(
7461 if (match(Op0, UAddOvResultPat) &&
7462 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7463 (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
7464 (match(A, m_One()) || match(B, m_One()))) ||
7465 (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
7466 (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
7467 // extract(uadd.with.overflow(A, B), 0) < A
7468 // extract(uadd.with.overflow(A, 1), 0) == 0
7469 // extract(uadd.with.overflow(A, -1), 0) != -1
7470 UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
7471 else if (match(Op1, UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7472 (Op0 == A || Op0 == B))
7473 // A > extract(uadd.with.overflow(A, B), 0)
7474 UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
7475 else
7476 return nullptr;
7477
7478 return ExtractValueInst::Create(UAddOv, 1);
7479}
7480
7482 if (!I.getOperand(0)->getType()->isPointerTy() ||
7484 I.getParent()->getParent(),
7485 I.getOperand(0)->getType()->getPointerAddressSpace())) {
7486 return nullptr;
7487 }
7488 Instruction *Op;
7489 if (match(I.getOperand(0), m_Instruction(Op)) &&
7490 match(I.getOperand(1), m_Zero()) &&
7491 Op->isLaunderOrStripInvariantGroup()) {
7492 return ICmpInst::Create(Instruction::ICmp, I.getPredicate(),
7493 Op->getOperand(0), I.getOperand(1));
7494 }
7495 return nullptr;
7496}
7497
7499 IRBuilderBase &Builder) {
7500 if (!ICmpInst::isEquality(I.getPredicate()))
7501 return nullptr;
7502
7503 // The caller puts constants after non-constants.
7504 Value *Op = I.getOperand(0);
7505 Value *Const = I.getOperand(1);
7506
7507 // For Cond an equality condition, fold
7508 //
7509 // icmp (eq|ne) (vreduce_(or|and) Op), (Zero|AllOnes) ->
7510 // icmp (eq|ne) Op, (Zero|AllOnes)
7511 //
7512 // with a bitcast.
7513 Value *Vec;
7514 if ((match(Const, m_ZeroInt()) &&
7516 m_Value(Vec))))) ||
7517 (match(Const, m_AllOnes()) &&
7519 m_Value(Vec)))))) {
7520 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
7521 if (!VecTy)
7522 return nullptr;
7523 Type *VecEltTy = VecTy->getElementType();
7524 unsigned ScalarBW =
7525 DL.getTypeSizeInBits(VecEltTy) * VecTy->getNumElements();
7526 if (!DL.fitsInLegalInteger(ScalarBW))
7527 return nullptr;
7528 Type *ScalarTy = IntegerType::get(I.getContext(), ScalarBW);
7529 Value *NewConst = match(Const, m_ZeroInt())
7530 ? ConstantInt::get(ScalarTy, 0)
7531 : ConstantInt::getAllOnesValue(ScalarTy);
7532 return CmpInst::Create(Instruction::ICmp, I.getPredicate(),
7533 Builder.CreateBitCast(Vec, ScalarTy), NewConst);
7534 }
7535 return nullptr;
7536}
7537
7538/// This function folds patterns produced by lowering of reduce idioms, such as
7539/// llvm.vector.reduce.and which are lowered into instruction chains. This code
7540/// attempts to generate fewer number of scalar comparisons instead of vector
7541/// comparisons when possible.
7543 InstCombiner::BuilderTy &Builder,
7544 const DataLayout &DL) {
7545 if (I.getType()->isVectorTy())
7546 return nullptr;
7547 CmpPredicate OuterPred, InnerPred;
7548 Value *LHS, *RHS;
7549
7550 // Match lowering of @llvm.vector.reduce.and. Turn
7551 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7552 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7553 /// %res = icmp <pred> i8 %scalar_ne, 0
7554 ///
7555 /// into
7556 ///
7557 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7558 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7559 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7560 ///
7561 /// for <pred> in {ne, eq}.
7562 if (!match(&I, m_ICmp(OuterPred,
7564 m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
7565 m_Zero())))
7566 return nullptr;
7567 auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
7568 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7569 return nullptr;
7570 unsigned NumBits =
7571 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7572 // TODO: Relax this to "not wider than max legal integer type"?
7573 if (!DL.isLegalInteger(NumBits))
7574 return nullptr;
7575
7576 if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7577 auto *ScalarTy = Builder.getIntNTy(NumBits);
7578 LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
7579 RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
7580 return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
7581 I.getName());
7582 }
7583
7584 return nullptr;
7585}
7586
7587// This helper will be called with icmp operands in both orders.
7589 Value *Op0, Value *Op1,
7590 ICmpInst &CxtI) {
7591 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7592 if (auto *GEP = dyn_cast<GEPOperator>(Op0))
7593 if (Instruction *NI = foldGEPICmp(GEP, Op1, Pred, CxtI))
7594 return NI;
7595
7596 if (auto *SI = dyn_cast<SelectInst>(Op0))
7597 if (Instruction *NI = foldSelectICmp(Pred, SI, Op1, CxtI))
7598 return NI;
7599
7600 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op0)) {
7601 if (Instruction *Res = foldICmpWithMinMax(CxtI, MinMax, Op1, Pred))
7602 return Res;
7603
7604 if (Instruction *Res = foldICmpWithClamp(CxtI, Op1, MinMax))
7605 return Res;
7606 }
7607
7608 {
7609 Value *X;
7610 const APInt *C;
7611 // icmp X+Cst, X
7612 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
7613 return foldICmpAddOpConst(X, *C, Pred);
7614 }
7615
7616 // abs(X) >= X --> true
7617 // abs(X) u<= X --> true
7618 // abs(X) < X --> false
7619 // abs(X) u> X --> false
7620 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7621 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7622 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7623 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7624 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7625 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7626 {
7627 Value *X;
7628 Constant *C;
7630 match(Op1, m_Specific(X))) {
7631 Value *NullValue = Constant::getNullValue(X->getType());
7632 Value *AllOnesValue = Constant::getAllOnesValue(X->getType());
7633 const APInt SMin =
7634 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits());
7635 bool IsIntMinPosion = C->isAllOnesValue();
7636 switch (Pred) {
7637 case CmpInst::ICMP_ULE:
7638 case CmpInst::ICMP_SGE:
7639 return replaceInstUsesWith(CxtI, ConstantInt::getTrue(CxtI.getType()));
7640 case CmpInst::ICMP_UGT:
7641 case CmpInst::ICMP_SLT:
7643 case CmpInst::ICMP_UGE:
7644 case CmpInst::ICMP_SLE:
7645 case CmpInst::ICMP_EQ: {
7646 return replaceInstUsesWith(
7647 CxtI, IsIntMinPosion
7648 ? Builder.CreateICmpSGT(X, AllOnesValue)
7649 : Builder.CreateICmpULT(
7650 X, ConstantInt::get(X->getType(), SMin + 1)));
7651 }
7652 case CmpInst::ICMP_ULT:
7653 case CmpInst::ICMP_SGT:
7654 case CmpInst::ICMP_NE: {
7655 return replaceInstUsesWith(
7656 CxtI, IsIntMinPosion
7657 ? Builder.CreateICmpSLT(X, NullValue)
7658 : Builder.CreateICmpUGT(
7659 X, ConstantInt::get(X->getType(), SMin)));
7660 }
7661 default:
7662 llvm_unreachable("Invalid predicate!");
7663 }
7664 }
7665 }
7666
7667 const SimplifyQuery Q = SQ.getWithInstruction(&CxtI);
7668 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, *this))
7669 return replaceInstUsesWith(CxtI, V);
7670
7671 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
7672 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(1); };
7673 {
7674 if (match(Op0, m_UDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7675 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7677 }
7678
7679 if (!ICmpInst::isUnsigned(Pred) &&
7680 match(Op0, m_SDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7681 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7683 }
7684 }
7685
7686 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
7687 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
7688 {
7689 if (match(Op0, m_LShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7690 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7692 }
7693
7694 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
7695 match(Op0, m_AShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7696 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7698 }
7699 }
7700
7701 return nullptr;
7702}
7703
7705 bool Changed = false;
7706 const SimplifyQuery Q = SQ.getWithInstruction(&I);
7707 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7708 unsigned Op0Cplxity = getComplexity(Op0);
7709 unsigned Op1Cplxity = getComplexity(Op1);
7710
7711 /// Orders the operands of the compare so that they are listed from most
7712 /// complex to least complex. This puts constants before unary operators,
7713 /// before binary operators.
7714 if (Op0Cplxity < Op1Cplxity) {
7715 I.swapOperands();
7716 std::swap(Op0, Op1);
7717 Changed = true;
7718 }
7719
7720 if (Value *V = simplifyICmpInst(I.getCmpPredicate(), Op0, Op1, Q))
7721 return replaceInstUsesWith(I, V);
7722
7723 // Comparing -val or val with non-zero is the same as just comparing val
7724 // ie, abs(val) != 0 -> val != 0
7725 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
7726 Value *Cond, *SelectTrue, *SelectFalse;
7727 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
7728 m_Value(SelectFalse)))) {
7729 if (Value *V = dyn_castNegVal(SelectTrue)) {
7730 if (V == SelectFalse)
7731 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
7732 } else if (Value *V = dyn_castNegVal(SelectFalse)) {
7733 if (V == SelectTrue)
7734 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
7735 }
7736 }
7737 }
7738
7740 return Res;
7741
7742 if (Op0->getType()->isIntOrIntVectorTy(1))
7744 return Res;
7745
7747 return Res;
7748
7750 return Res;
7751
7753 return Res;
7754
7756 return Res;
7757
7759 return Res;
7760
7762 return Res;
7763
7765 return Res;
7766
7767 // Test if the ICmpInst instruction is used exclusively by a select as
7768 // part of a minimum or maximum operation. If so, refrain from doing
7769 // any other folding. This helps out other analyses which understand
7770 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
7771 // and CodeGen. And in this case, at least one of the comparison
7772 // operands has at least one user besides the compare (the select),
7773 // which would often largely negate the benefit of folding anyway.
7774 //
7775 // Do the same for the other patterns recognized by matchSelectPattern.
7776 if (I.hasOneUse())
7777 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
7778 Value *A, *B;
7780 if (SPR.Flavor != SPF_UNKNOWN)
7781 return nullptr;
7782 }
7783
7784 // Do this after checking for min/max to prevent infinite looping.
7785 if (Instruction *Res = foldICmpWithZero(I))
7786 return Res;
7787
7788 // FIXME: We only do this after checking for min/max to prevent infinite
7789 // looping caused by a reverse canonicalization of these patterns for min/max.
7790 // FIXME: The organization of folds is a mess. These would naturally go into
7791 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
7792 // down here after the min/max restriction.
7793 ICmpInst::Predicate Pred = I.getPredicate();
7794 const APInt *C;
7795 if (match(Op1, m_APInt(C))) {
7796 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
7797 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
7798 Constant *Zero = Constant::getNullValue(Op0->getType());
7799 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
7800 }
7801
7802 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
7803 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
7805 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
7806 }
7807 }
7808
7809 // The folds in here may rely on wrapping flags and special constants, so
7810 // they can break up min/max idioms in some cases but not seemingly similar
7811 // patterns.
7812 // FIXME: It may be possible to enhance select folding to make this
7813 // unnecessary. It may also be moot if we canonicalize to min/max
7814 // intrinsics.
7815 if (Instruction *Res = foldICmpBinOp(I, Q))
7816 return Res;
7817
7819 return Res;
7820
7821 // Try to match comparison as a sign bit test. Intentionally do this after
7822 // foldICmpInstWithConstant() to potentially let other folds to happen first.
7823 if (Instruction *New = foldSignBitTest(I))
7824 return New;
7825
7826 if (auto *PN = dyn_cast<PHINode>(Op0))
7827 if (Instruction *NV = foldOpIntoPhi(I, PN))
7828 return NV;
7829 if (auto *PN = dyn_cast<PHINode>(Op1))
7830 if (Instruction *NV = foldOpIntoPhi(I, PN))
7831 return NV;
7832
7834 return Res;
7835
7836 if (Instruction *Res = foldICmpCommutative(I.getCmpPredicate(), Op0, Op1, I))
7837 return Res;
7838 if (Instruction *Res =
7839 foldICmpCommutative(I.getSwappedCmpPredicate(), Op1, Op0, I))
7840 return Res;
7841
7842 if (I.isCommutative()) {
7843 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
7844 replaceOperand(I, 0, Pair->first);
7845 replaceOperand(I, 1, Pair->second);
7846 return &I;
7847 }
7848 }
7849
7850 // In case of a comparison with two select instructions having the same
7851 // condition, check whether one of the resulting branches can be simplified.
7852 // If so, just compare the other branch and select the appropriate result.
7853 // For example:
7854 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
7855 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
7856 // %cmp2 = icmp slt i32 %tmp2, %tmp1
7857 // The icmp will result false for the false value of selects and the result
7858 // will depend upon the comparison of true values of selects if %cmp is
7859 // true. Thus, transform this into:
7860 // %cmp = icmp slt i32 %y, %z
7861 // %sel = select i1 %cond, i1 %cmp, i1 false
7862 // This handles similar cases to transform.
7863 {
7864 Value *Cond, *A, *B, *C, *D;
7865 if (match(Op0, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
7867 (Op0->hasOneUse() || Op1->hasOneUse())) {
7868 // Check whether comparison of TrueValues can be simplified
7869 if (Value *Res = simplifyICmpInst(Pred, A, C, SQ)) {
7870 Value *NewICMP = Builder.CreateICmp(Pred, B, D);
7871 return SelectInst::Create(
7872 Cond, Res, NewICMP, /*NameStr=*/"", /*InsertBefore=*/nullptr,
7874 }
7875 // Check whether comparison of FalseValues can be simplified
7876 if (Value *Res = simplifyICmpInst(Pred, B, D, SQ)) {
7877 Value *NewICMP = Builder.CreateICmp(Pred, A, C);
7878 return SelectInst::Create(
7879 Cond, NewICMP, Res, /*NameStr=*/"", /*InsertBefore=*/nullptr,
7881 }
7882 }
7883 }
7884
7885 // icmp slt (sub nsw x, y), (add nsw x, y) --> icmp sgt y, 0
7886 // icmp ult (sub nuw x, y), (add nuw x, y) --> icmp ugt y, 0
7887 // icmp eq (sub nsw/nuw x, y), (add nsw/nuw x, y) --> icmp eq y, 0
7888 {
7889 Value *A, *B;
7890 CmpPredicate CmpPred;
7891 if (match(&I, m_c_ICmp(CmpPred, m_Sub(m_Value(A), m_Value(B)),
7893 auto *I0 = cast<OverflowingBinaryOperator>(Op0);
7894 auto *I1 = cast<OverflowingBinaryOperator>(Op1);
7895 bool I0NUW = I0->hasNoUnsignedWrap();
7896 bool I1NUW = I1->hasNoUnsignedWrap();
7897 bool I0NSW = I0->hasNoSignedWrap();
7898 bool I1NSW = I1->hasNoSignedWrap();
7899 if ((ICmpInst::isUnsigned(Pred) && I0NUW && I1NUW) ||
7900 (ICmpInst::isSigned(Pred) && I0NSW && I1NSW) ||
7901 (ICmpInst::isEquality(Pred) &&
7902 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
7903 return new ICmpInst(CmpPredicate::getSwapped(CmpPred), B,
7904 ConstantInt::get(Op0->getType(), 0));
7905 }
7906 }
7907 }
7908
7909 // Try to optimize equality comparisons against alloca-based pointers.
7910 if (Op0->getType()->isPointerTy() && I.isEquality()) {
7911 assert(Op1->getType()->isPointerTy() &&
7912 "Comparing pointer with non-pointer?");
7913 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
7914 if (foldAllocaCmp(Alloca))
7915 return nullptr;
7916 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
7917 if (foldAllocaCmp(Alloca))
7918 return nullptr;
7919 }
7920
7921 if (Instruction *Res = foldICmpBitCast(I))
7922 return Res;
7923
7924 // TODO: Hoist this above the min/max bailout.
7926 return R;
7927
7928 {
7929 Value *X, *Y;
7930 // Transform (X & ~Y) == 0 --> (X & Y) != 0
7931 // and (X & ~Y) != 0 --> (X & Y) == 0
7932 // if A is a power of 2.
7933 if (match(Op0, m_And(m_Value(X), m_Not(m_Value(Y)))) &&
7934 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(X, false, &I) &&
7935 I.isEquality())
7936 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(X, Y),
7937 Op1);
7938
7939 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
7940 if (Op0->getType()->isIntOrIntVectorTy()) {
7941 bool ConsumesOp0, ConsumesOp1;
7942 if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
7943 isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
7944 (ConsumesOp0 || ConsumesOp1)) {
7945 Value *InvOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
7946 Value *InvOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
7947 assert(InvOp0 && InvOp1 &&
7948 "Mismatch between isFreeToInvert and getFreelyInverted");
7949 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
7950 }
7951 }
7952
7953 Instruction *AddI = nullptr;
7955 m_Instruction(AddI))) &&
7956 isa<IntegerType>(X->getType())) {
7957 Value *Result;
7958 Constant *Overflow;
7959 // m_UAddWithOverflow can match patterns that do not include an explicit
7960 // "add" instruction, so check the opcode of the matched op.
7961 if (AddI->getOpcode() == Instruction::Add &&
7962 OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, X, Y, *AddI,
7963 Result, Overflow)) {
7964 replaceInstUsesWith(*AddI, Result);
7965 eraseInstFromFunction(*AddI);
7966 return replaceInstUsesWith(I, Overflow);
7967 }
7968 }
7969
7970 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
7971 if (match(Op0, m_NUWMul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) &&
7972 match(Op1, m_APInt(C))) {
7973 if (Instruction *R = processUMulZExtIdiom(I, Op0, C, *this))
7974 return R;
7975 }
7976
7977 // Signbit test folds
7978 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
7979 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
7980 Instruction *ExtI;
7981 if ((I.isUnsigned() || I.isEquality()) &&
7982 match(Op1,
7984 Y->getType()->getScalarSizeInBits() == 1 &&
7985 (Op0->hasOneUse() || Op1->hasOneUse())) {
7986 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
7987 Instruction *ShiftI;
7988 if (match(Op0, m_CombineAnd(m_Instruction(ShiftI),
7990 OpWidth - 1))))) {
7991 unsigned ExtOpc = ExtI->getOpcode();
7992 unsigned ShiftOpc = ShiftI->getOpcode();
7993 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
7994 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
7995 Value *SLTZero =
7996 Builder.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
7997 Value *Cmp = Builder.CreateICmp(Pred, SLTZero, Y, I.getName());
7998 return replaceInstUsesWith(I, Cmp);
7999 }
8000 }
8001 }
8002 }
8003
8004 if (Instruction *Res = foldICmpEquality(I))
8005 return Res;
8006
8008 return Res;
8009
8010 if (Instruction *Res = foldICmpOfUAddOv(I))
8011 return Res;
8012
8014 return Res;
8015
8016 // The 'cmpxchg' instruction returns an aggregate containing the old value and
8017 // an i1 which indicates whether or not we successfully did the swap.
8018 //
8019 // Replace comparisons between the old value and the expected value with the
8020 // indicator that 'cmpxchg' returns.
8021 //
8022 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
8023 // spuriously fail. In those cases, the old value may equal the expected
8024 // value but it is possible for the swap to not occur.
8025 if (I.getPredicate() == ICmpInst::ICMP_EQ)
8026 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
8027 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
8028 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
8029 !ACXI->isWeak())
8030 return ExtractValueInst::Create(ACXI, 1);
8031
8033 return Res;
8034
8035 if (I.getType()->isVectorTy())
8036 if (Instruction *Res = foldVectorCmp(I, Builder))
8037 return Res;
8038
8040 return Res;
8041
8043 return Res;
8044
8045 {
8046 Value *A;
8047 const APInt *C1, *C2;
8048 ICmpInst::Predicate Pred = I.getPredicate();
8049 if (ICmpInst::isEquality(Pred)) {
8050 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
8051 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
8052 if (match(Op0, m_And(m_SExt(m_Value(A)), m_APInt(C1))) &&
8053 match(Op1, m_APInt(C2))) {
8054 Type *InputTy = A->getType();
8055 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
8056 // c2 must be non-negative at the bitwidth of a.
8057 if (C2->getActiveBits() < InputBitWidth) {
8058 APInt TruncC1 = C1->trunc(InputBitWidth);
8059 // Check if there are 1s in C1 high bits of size InputBitWidth.
8060 if (C1->uge(APInt::getOneBitSet(C1->getBitWidth(), InputBitWidth)))
8061 TruncC1.setBit(InputBitWidth - 1);
8062 Value *AndInst = Builder.CreateAnd(A, TruncC1);
8063 return new ICmpInst(
8064 Pred, AndInst,
8065 ConstantInt::get(InputTy, C2->trunc(InputBitWidth)));
8066 }
8067 }
8068 }
8069 }
8070
8071 return Changed ? &I : nullptr;
8072}
8073
8074/// Fold fcmp ([us]itofp x, cst) if possible.
8076 Instruction *LHSI,
8077 Constant *RHSC) {
8078 const APFloat *RHS;
8079 if (!match(RHSC, m_APFloat(RHS)))
8080 return nullptr;
8081
8082 // Get the width of the mantissa. We don't want to hack on conversions that
8083 // might lose information from the integer, e.g. "i64 -> float"
8084 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8085 if (MantissaWidth == -1)
8086 return nullptr; // Unknown.
8087
8088 Type *IntTy = LHSI->getOperand(0)->getType();
8089 unsigned IntWidth = IntTy->getScalarSizeInBits();
8090 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
8091
8092 if (I.isEquality()) {
8093 FCmpInst::Predicate P = I.getPredicate();
8094 bool IsExact = false;
8095 APSInt RHSCvt(IntWidth, LHSUnsigned);
8096 RHS->convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
8097
8098 // If the floating point constant isn't an integer value, we know if we will
8099 // ever compare equal / not equal to it.
8100 if (!IsExact) {
8101 // TODO: Can never be -0.0 and other non-representable values
8102 APFloat RHSRoundInt(*RHS);
8104 if (*RHS != RHSRoundInt) {
8106 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8107
8109 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8110 }
8111 }
8112
8113 // TODO: If the constant is exactly representable, is it always OK to do
8114 // equality compares as integer?
8115 }
8116
8117 // Check to see that the input is converted from an integer type that is small
8118 // enough that preserves all bits. TODO: check here for "known" sign bits.
8119 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
8120
8121 // Following test does NOT adjust IntWidth downwards for signed inputs,
8122 // because the most negative value still requires all the mantissa bits
8123 // to distinguish it from one less than that value.
8124 if ((int)IntWidth > MantissaWidth) {
8125 // Conversion would lose accuracy. Check if loss can impact comparison.
8126 int Exp = ilogb(*RHS);
8127 if (Exp == APFloat::IEK_Inf) {
8128 int MaxExponent = ilogb(APFloat::getLargest(RHS->getSemantics()));
8129 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
8130 // Conversion could create infinity.
8131 return nullptr;
8132 } else {
8133 // Note that if RHS is zero or NaN, then Exp is negative
8134 // and first condition is trivially false.
8135 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
8136 // Conversion could affect comparison.
8137 return nullptr;
8138 }
8139 }
8140
8141 // Otherwise, we can potentially simplify the comparison. We know that it
8142 // will always come through as an integer value and we know the constant is
8143 // not a NAN (it would have been previously simplified).
8144 assert(!RHS->isNaN() && "NaN comparison not already folded!");
8145
8147 switch (I.getPredicate()) {
8148 default:
8149 llvm_unreachable("Unexpected predicate!");
8150 case FCmpInst::FCMP_UEQ:
8151 case FCmpInst::FCMP_OEQ:
8152 Pred = ICmpInst::ICMP_EQ;
8153 break;
8154 case FCmpInst::FCMP_UGT:
8155 case FCmpInst::FCMP_OGT:
8156 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
8157 break;
8158 case FCmpInst::FCMP_UGE:
8159 case FCmpInst::FCMP_OGE:
8160 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
8161 break;
8162 case FCmpInst::FCMP_ULT:
8163 case FCmpInst::FCMP_OLT:
8164 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
8165 break;
8166 case FCmpInst::FCMP_ULE:
8167 case FCmpInst::FCMP_OLE:
8168 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
8169 break;
8170 case FCmpInst::FCMP_UNE:
8171 case FCmpInst::FCMP_ONE:
8172 Pred = ICmpInst::ICMP_NE;
8173 break;
8174 case FCmpInst::FCMP_ORD:
8175 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8176 case FCmpInst::FCMP_UNO:
8177 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8178 }
8179
8180 // Now we know that the APFloat is a normal number, zero or inf.
8181
8182 // See if the FP constant is too large for the integer. For example,
8183 // comparing an i8 to 300.0.
8184 if (!LHSUnsigned) {
8185 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
8186 // and large values.
8187 APFloat SMax(RHS->getSemantics());
8188 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
8190 if (SMax < *RHS) { // smax < 13123.0
8191 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
8192 Pred == ICmpInst::ICMP_SLE)
8193 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8194 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8195 }
8196 } else {
8197 // If the RHS value is > UnsignedMax, fold the comparison. This handles
8198 // +INF and large values.
8199 APFloat UMax(RHS->getSemantics());
8200 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
8202 if (UMax < *RHS) { // umax < 13123.0
8203 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
8204 Pred == ICmpInst::ICMP_ULE)
8205 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8206 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8207 }
8208 }
8209
8210 if (!LHSUnsigned) {
8211 // See if the RHS value is < SignedMin.
8212 APFloat SMin(RHS->getSemantics());
8213 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
8215 if (SMin > *RHS) { // smin > 12312.0
8216 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
8217 Pred == ICmpInst::ICMP_SGE)
8218 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8219 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8220 }
8221 } else {
8222 // See if the RHS value is < UnsignedMin.
8223 APFloat UMin(RHS->getSemantics());
8224 UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
8226 if (UMin > *RHS) { // umin > 12312.0
8227 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
8228 Pred == ICmpInst::ICMP_UGE)
8229 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8230 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8231 }
8232 }
8233
8234 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
8235 // [0, UMAX], but it may still be fractional. Check whether this is the case
8236 // using the IsExact flag.
8237 // Don't do this for zero, because -0.0 is not fractional.
8238 APSInt RHSInt(IntWidth, LHSUnsigned);
8239 bool IsExact;
8240 RHS->convertToInteger(RHSInt, APFloat::rmTowardZero, &IsExact);
8241 if (!RHS->isZero()) {
8242 if (!IsExact) {
8243 // If we had a comparison against a fractional value, we have to adjust
8244 // the compare predicate and sometimes the value. RHSC is rounded towards
8245 // zero at this point.
8246 switch (Pred) {
8247 default:
8248 llvm_unreachable("Unexpected integer comparison!");
8249 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
8250 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8251 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
8252 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8253 case ICmpInst::ICMP_ULE:
8254 // (float)int <= 4.4 --> int <= 4
8255 // (float)int <= -4.4 --> false
8256 if (RHS->isNegative())
8257 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8258 break;
8259 case ICmpInst::ICMP_SLE:
8260 // (float)int <= 4.4 --> int <= 4
8261 // (float)int <= -4.4 --> int < -4
8262 if (RHS->isNegative())
8263 Pred = ICmpInst::ICMP_SLT;
8264 break;
8265 case ICmpInst::ICMP_ULT:
8266 // (float)int < -4.4 --> false
8267 // (float)int < 4.4 --> int <= 4
8268 if (RHS->isNegative())
8269 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8270 Pred = ICmpInst::ICMP_ULE;
8271 break;
8272 case ICmpInst::ICMP_SLT:
8273 // (float)int < -4.4 --> int < -4
8274 // (float)int < 4.4 --> int <= 4
8275 if (!RHS->isNegative())
8276 Pred = ICmpInst::ICMP_SLE;
8277 break;
8278 case ICmpInst::ICMP_UGT:
8279 // (float)int > 4.4 --> int > 4
8280 // (float)int > -4.4 --> true
8281 if (RHS->isNegative())
8282 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8283 break;
8284 case ICmpInst::ICMP_SGT:
8285 // (float)int > 4.4 --> int > 4
8286 // (float)int > -4.4 --> int >= -4
8287 if (RHS->isNegative())
8288 Pred = ICmpInst::ICMP_SGE;
8289 break;
8290 case ICmpInst::ICMP_UGE:
8291 // (float)int >= -4.4 --> true
8292 // (float)int >= 4.4 --> int > 4
8293 if (RHS->isNegative())
8294 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8295 Pred = ICmpInst::ICMP_UGT;
8296 break;
8297 case ICmpInst::ICMP_SGE:
8298 // (float)int >= -4.4 --> int >= -4
8299 // (float)int >= 4.4 --> int > 4
8300 if (!RHS->isNegative())
8301 Pred = ICmpInst::ICMP_SGT;
8302 break;
8303 }
8304 }
8305 }
8306
8307 // Lower this FP comparison into an appropriate integer version of the
8308 // comparison.
8309 return new ICmpInst(Pred, LHSI->getOperand(0),
8310 ConstantInt::get(LHSI->getOperand(0)->getType(), RHSInt));
8311}
8312
8313/// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
8315 Constant *RHSC) {
8316 // When C is not 0.0 and infinities are not allowed:
8317 // (C / X) < 0.0 is a sign-bit test of X
8318 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
8319 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
8320 //
8321 // Proof:
8322 // Multiply (C / X) < 0.0 by X * X / C.
8323 // - X is non zero, if it is the flag 'ninf' is violated.
8324 // - C defines the sign of X * X * C. Thus it also defines whether to swap
8325 // the predicate. C is also non zero by definition.
8326 //
8327 // Thus X * X / C is non zero and the transformation is valid. [qed]
8328
8329 FCmpInst::Predicate Pred = I.getPredicate();
8330
8331 // Check that predicates are valid.
8332 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
8333 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
8334 return nullptr;
8335
8336 // Check that RHS operand is zero.
8337 if (!match(RHSC, m_AnyZeroFP()))
8338 return nullptr;
8339
8340 // Check fastmath flags ('ninf').
8341 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
8342 return nullptr;
8343
8344 // Check the properties of the dividend. It must not be zero to avoid a
8345 // division by zero (see Proof).
8346 const APFloat *C;
8347 if (!match(LHSI->getOperand(0), m_APFloat(C)))
8348 return nullptr;
8349
8350 if (C->isZero())
8351 return nullptr;
8352
8353 // Get swapped predicate if necessary.
8354 if (C->isNegative())
8355 Pred = I.getSwappedPredicate();
8356
8357 return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
8358}
8359
8360// Transform 'fptrunc(x) cmp C' to 'x cmp ext(C)' if possible.
8361// Patterns include:
8362// fptrunc(x) < C --> x < ext(C)
8363// fptrunc(x) <= C --> x <= ext(C)
8364// fptrunc(x) > C --> x > ext(C)
8365// fptrunc(x) >= C --> x >= ext(C)
8366// where 'ext(C)' is the extension of 'C' to the type of 'x' with a small bias
8367// due to precision loss.
8369 const Constant &C) {
8370 FCmpInst::Predicate Pred = I.getPredicate();
8371 bool RoundDown = false;
8372
8373 if (Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE ||
8374 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT)
8375 RoundDown = true;
8376 else if (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT ||
8377 Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)
8378 RoundDown = false;
8379 else
8380 return nullptr;
8381
8382 const APFloat *CValue;
8383 if (!match(&C, m_APFloat(CValue)))
8384 return nullptr;
8385
8386 if (CValue->isNaN() || CValue->isInfinity())
8387 return nullptr;
8388
8389 auto ConvertFltSema = [](const APFloat &Src, const fltSemantics &Sema) {
8390 bool LosesInfo;
8391 APFloat Dest = Src;
8392 Dest.convert(Sema, APFloat::rmNearestTiesToEven, &LosesInfo);
8393 return Dest;
8394 };
8395
8396 auto NextValue = [](const APFloat &Value, bool RoundDown) {
8397 APFloat NextValue = Value;
8398 NextValue.next(RoundDown);
8399 return NextValue;
8400 };
8401
8402 APFloat NextCValue = NextValue(*CValue, RoundDown);
8403
8404 Type *DestType = FPTrunc.getOperand(0)->getType();
8405 const fltSemantics &DestFltSema =
8406 DestType->getScalarType()->getFltSemantics();
8407
8408 APFloat ExtCValue = ConvertFltSema(*CValue, DestFltSema);
8409 APFloat ExtNextCValue = ConvertFltSema(NextCValue, DestFltSema);
8410
8411 // When 'NextCValue' is infinity, use an imaged 'NextCValue' that equals
8412 // 'CValue + bias' to avoid the infinity after conversion. The bias is
8413 // estimated as 'CValue - PrevCValue', where 'PrevCValue' is the previous
8414 // value of 'CValue'.
8415 if (NextCValue.isInfinity()) {
8416 APFloat PrevCValue = NextValue(*CValue, !RoundDown);
8417 APFloat Bias = ConvertFltSema(*CValue - PrevCValue, DestFltSema);
8418
8419 ExtNextCValue = ExtCValue + Bias;
8420 }
8421
8422 APFloat ExtMidValue =
8423 scalbn(ExtCValue + ExtNextCValue, -1, APFloat::rmNearestTiesToEven);
8424
8425 const fltSemantics &SrcFltSema =
8426 C.getType()->getScalarType()->getFltSemantics();
8427
8428 // 'MidValue' might be rounded to 'NextCValue'. Correct it here.
8429 APFloat MidValue = ConvertFltSema(ExtMidValue, SrcFltSema);
8430 if (MidValue != *CValue)
8431 ExtMidValue.next(!RoundDown);
8432
8433 // Check whether 'ExtMidValue' is a valid result since the assumption on
8434 // imaged 'NextCValue' might not hold for new float types.
8435 // ppc_fp128 can't pass here when converting from max float because of
8436 // APFloat implementation.
8437 if (NextCValue.isInfinity()) {
8438 // ExtMidValue --- narrowed ---> Finite
8439 if (ConvertFltSema(ExtMidValue, SrcFltSema).isInfinity())
8440 return nullptr;
8441
8442 // NextExtMidValue --- narrowed ---> Infinity
8443 APFloat NextExtMidValue = NextValue(ExtMidValue, RoundDown);
8444 if (ConvertFltSema(NextExtMidValue, SrcFltSema).isFinite())
8445 return nullptr;
8446 }
8447
8448 return new FCmpInst(Pred, FPTrunc.getOperand(0),
8449 ConstantFP::get(DestType, ExtMidValue), "", &I);
8450}
8451
8452/// Optimize fabs(X) compared with zero.
8454 Value *X;
8455 if (!match(I.getOperand(0), m_FAbs(m_Value(X))))
8456 return nullptr;
8457
8458 const APFloat *C;
8459 if (!match(I.getOperand(1), m_APFloat(C)))
8460 return nullptr;
8461
8462 if (!C->isPosZero()) {
8463 if (!C->isSmallestNormalized())
8464 return nullptr;
8465
8466 const Function *F = I.getFunction();
8467 DenormalMode Mode = F->getDenormalMode(C->getSemantics());
8468 if (Mode.Input == DenormalMode::PreserveSign ||
8470
8471 auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8472 Constant *Zero = ConstantFP::getZero(X->getType());
8473 return new FCmpInst(P, X, Zero, "", I);
8474 };
8475
8476 switch (I.getPredicate()) {
8477 case FCmpInst::FCMP_OLT:
8478 // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
8479 return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
8480 case FCmpInst::FCMP_UGE:
8481 // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
8482 return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
8483 case FCmpInst::FCMP_OGE:
8484 // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
8485 return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
8486 case FCmpInst::FCMP_ULT:
8487 // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
8488 return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
8489 default:
8490 break;
8491 }
8492 }
8493
8494 return nullptr;
8495 }
8496
8497 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8498 I->setPredicate(P);
8499 return IC.replaceOperand(*I, 0, X);
8500 };
8501
8502 switch (I.getPredicate()) {
8503 case FCmpInst::FCMP_UGE:
8504 case FCmpInst::FCMP_OLT:
8505 // fabs(X) >= 0.0 --> true
8506 // fabs(X) < 0.0 --> false
8507 llvm_unreachable("fcmp should have simplified");
8508
8509 case FCmpInst::FCMP_OGT:
8510 // fabs(X) > 0.0 --> X != 0.0
8511 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
8512
8513 case FCmpInst::FCMP_UGT:
8514 // fabs(X) u> 0.0 --> X u!= 0.0
8515 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
8516
8517 case FCmpInst::FCMP_OLE:
8518 // fabs(X) <= 0.0 --> X == 0.0
8519 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
8520
8521 case FCmpInst::FCMP_ULE:
8522 // fabs(X) u<= 0.0 --> X u== 0.0
8523 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
8524
8525 case FCmpInst::FCMP_OGE:
8526 // fabs(X) >= 0.0 --> !isnan(X)
8527 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8528 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
8529
8530 case FCmpInst::FCMP_ULT:
8531 // fabs(X) u< 0.0 --> isnan(X)
8532 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8533 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
8534
8535 case FCmpInst::FCMP_OEQ:
8536 case FCmpInst::FCMP_UEQ:
8537 case FCmpInst::FCMP_ONE:
8538 case FCmpInst::FCMP_UNE:
8539 case FCmpInst::FCMP_ORD:
8540 case FCmpInst::FCMP_UNO:
8541 // Look through the fabs() because it doesn't change anything but the sign.
8542 // fabs(X) == 0.0 --> X == 0.0,
8543 // fabs(X) != 0.0 --> X != 0.0
8544 // isnan(fabs(X)) --> isnan(X)
8545 // !isnan(fabs(X) --> !isnan(X)
8546 return replacePredAndOp0(&I, I.getPredicate(), X);
8547
8548 default:
8549 return nullptr;
8550 }
8551}
8552
8553/// Optimize sqrt(X) compared with zero.
8555 Value *X;
8556 if (!match(I.getOperand(0), m_Sqrt(m_Value(X))))
8557 return nullptr;
8558
8559 if (!match(I.getOperand(1), m_PosZeroFP()))
8560 return nullptr;
8561
8562 auto ReplacePredAndOp0 = [&](FCmpInst::Predicate P) {
8563 I.setPredicate(P);
8564 return IC.replaceOperand(I, 0, X);
8565 };
8566
8567 // Clear ninf flag if sqrt doesn't have it.
8568 if (!cast<Instruction>(I.getOperand(0))->hasNoInfs())
8569 I.setHasNoInfs(false);
8570
8571 switch (I.getPredicate()) {
8572 case FCmpInst::FCMP_OLT:
8573 case FCmpInst::FCMP_UGE:
8574 // sqrt(X) < 0.0 --> false
8575 // sqrt(X) u>= 0.0 --> true
8576 llvm_unreachable("fcmp should have simplified");
8577 case FCmpInst::FCMP_ULT:
8578 case FCmpInst::FCMP_ULE:
8579 case FCmpInst::FCMP_OGT:
8580 case FCmpInst::FCMP_OGE:
8581 case FCmpInst::FCMP_OEQ:
8582 case FCmpInst::FCMP_UNE:
8583 // sqrt(X) u< 0.0 --> X u< 0.0
8584 // sqrt(X) u<= 0.0 --> X u<= 0.0
8585 // sqrt(X) > 0.0 --> X > 0.0
8586 // sqrt(X) >= 0.0 --> X >= 0.0
8587 // sqrt(X) == 0.0 --> X == 0.0
8588 // sqrt(X) u!= 0.0 --> X u!= 0.0
8589 return IC.replaceOperand(I, 0, X);
8590
8591 case FCmpInst::FCMP_OLE:
8592 // sqrt(X) <= 0.0 --> X == 0.0
8593 return ReplacePredAndOp0(FCmpInst::FCMP_OEQ);
8594 case FCmpInst::FCMP_UGT:
8595 // sqrt(X) u> 0.0 --> X u!= 0.0
8596 return ReplacePredAndOp0(FCmpInst::FCMP_UNE);
8597 case FCmpInst::FCMP_UEQ:
8598 // sqrt(X) u== 0.0 --> X u<= 0.0
8599 return ReplacePredAndOp0(FCmpInst::FCMP_ULE);
8600 case FCmpInst::FCMP_ONE:
8601 // sqrt(X) != 0.0 --> X > 0.0
8602 return ReplacePredAndOp0(FCmpInst::FCMP_OGT);
8603 case FCmpInst::FCMP_ORD:
8604 // !isnan(sqrt(X)) --> X >= 0.0
8605 return ReplacePredAndOp0(FCmpInst::FCMP_OGE);
8606 case FCmpInst::FCMP_UNO:
8607 // isnan(sqrt(X)) --> X u< 0.0
8608 return ReplacePredAndOp0(FCmpInst::FCMP_ULT);
8609 default:
8610 llvm_unreachable("Unexpected predicate!");
8611 }
8612}
8613
8615 CmpInst::Predicate Pred = I.getPredicate();
8616 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8617
8618 // Canonicalize fneg as Op1.
8619 if (match(Op0, m_FNeg(m_Value())) && !match(Op1, m_FNeg(m_Value()))) {
8620 std::swap(Op0, Op1);
8621 Pred = I.getSwappedPredicate();
8622 }
8623
8624 if (!match(Op1, m_FNeg(m_Specific(Op0))))
8625 return nullptr;
8626
8627 // Replace the negated operand with 0.0:
8628 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
8629 Constant *Zero = ConstantFP::getZero(Op0->getType());
8630 return new FCmpInst(Pred, Op0, Zero, "", &I);
8631}
8632
8634 Constant *RHSC, InstCombinerImpl &CI) {
8635 const CmpInst::Predicate Pred = I.getPredicate();
8636 Value *X = LHSI->getOperand(0);
8637 Value *Y = LHSI->getOperand(1);
8638 switch (Pred) {
8639 default:
8640 break;
8641 case FCmpInst::FCMP_UGT:
8642 case FCmpInst::FCMP_ULT:
8643 case FCmpInst::FCMP_UNE:
8644 case FCmpInst::FCMP_OEQ:
8645 case FCmpInst::FCMP_OGE:
8646 case FCmpInst::FCMP_OLE:
8647 // The optimization is not valid if X and Y are infinities of the same
8648 // sign, i.e. the inf - inf = nan case. If the fsub has the ninf or nnan
8649 // flag then we can assume we do not have that case. Otherwise we might be
8650 // able to prove that either X or Y is not infinity.
8651 if (!LHSI->hasNoNaNs() && !LHSI->hasNoInfs() &&
8655 break;
8656
8657 [[fallthrough]];
8658 case FCmpInst::FCMP_OGT:
8659 case FCmpInst::FCMP_OLT:
8660 case FCmpInst::FCMP_ONE:
8661 case FCmpInst::FCMP_UEQ:
8662 case FCmpInst::FCMP_UGE:
8663 case FCmpInst::FCMP_ULE:
8664 // fcmp pred (x - y), 0 --> fcmp pred x, y
8665 if (match(RHSC, m_AnyZeroFP()) &&
8666 I.getFunction()->getDenormalMode(
8667 LHSI->getType()->getScalarType()->getFltSemantics()) ==
8669 CI.replaceOperand(I, 0, X);
8670 CI.replaceOperand(I, 1, Y);
8671 I.setHasNoInfs(LHSI->hasNoInfs());
8672 if (LHSI->hasNoNaNs())
8673 I.setHasNoNaNs(true);
8674 return &I;
8675 }
8676 break;
8677 }
8678
8679 return nullptr;
8680}
8681
8683 InstCombinerImpl &IC) {
8684 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
8685 Type *OpType = LHS->getType();
8686 CmpInst::Predicate Pred = I.getPredicate();
8687
8690
8691 if (!FloorX && !CeilX) {
8694 std::swap(LHS, RHS);
8695 Pred = I.getSwappedPredicate();
8696 }
8697 }
8698
8699 switch (Pred) {
8700 case FCmpInst::FCMP_OLE:
8701 // fcmp ole floor(x), x => fcmp ord x, 0
8702 if (FloorX)
8704 "", &I);
8705 break;
8706 case FCmpInst::FCMP_OGT:
8707 // fcmp ogt floor(x), x => false
8708 if (FloorX)
8709 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8710 break;
8711 case FCmpInst::FCMP_OGE:
8712 // fcmp oge ceil(x), x => fcmp ord x, 0
8713 if (CeilX)
8715 "", &I);
8716 break;
8717 case FCmpInst::FCMP_OLT:
8718 // fcmp olt ceil(x), x => false
8719 if (CeilX)
8720 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8721 break;
8722 case FCmpInst::FCMP_ULE:
8723 // fcmp ule floor(x), x => true
8724 if (FloorX)
8725 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8726 break;
8727 case FCmpInst::FCMP_UGT:
8728 // fcmp ugt floor(x), x => fcmp uno x, 0
8729 if (FloorX)
8731 "", &I);
8732 break;
8733 case FCmpInst::FCMP_UGE:
8734 // fcmp uge ceil(x), x => true
8735 if (CeilX)
8736 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8737 break;
8738 case FCmpInst::FCMP_ULT:
8739 // fcmp ult ceil(x), x => fcmp uno x, 0
8740 if (CeilX)
8742 "", &I);
8743 break;
8744 default:
8745 break;
8746 }
8747
8748 return nullptr;
8749}
8750
8751/// Returns true if a select that implements a min/max is redundant and
8752/// select result can be replaced with its non-constant operand, e.g.,
8753/// select ( (si/ui-to-fp A) <= C ), C, (si/ui-to-fp A)
8754/// where C is the FP constant equal to the minimum integer value
8755/// representable by A.
8757 Value *B) {
8758 const APFloat *APF;
8759 if (!match(B, m_APFloat(APF)))
8760 return false;
8761
8762 auto *I = dyn_cast<Instruction>(A);
8763 if (!I || !(I->getOpcode() == Instruction::SIToFP ||
8764 I->getOpcode() == Instruction::UIToFP))
8765 return false;
8766
8767 bool IsUnsigned = I->getOpcode() == Instruction::UIToFP;
8768 unsigned BitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
8769 APSInt IntBoundary = (Flavor == SPF_FMAXNUM)
8770 ? APSInt::getMinValue(BitWidth, IsUnsigned)
8771 : APSInt::getMaxValue(BitWidth, IsUnsigned);
8772 APSInt ConvertedInt(BitWidth, IsUnsigned);
8773 bool IsExact;
8775 APF->convertToInteger(ConvertedInt, APFloat::rmTowardZero, &IsExact);
8776 return Status == APFloat::opOK && IsExact && ConvertedInt == IntBoundary;
8777}
8778
8780 bool Changed = false;
8781
8782 /// Orders the operands of the compare so that they are listed from most
8783 /// complex to least complex. This puts constants before unary operators,
8784 /// before binary operators.
8785 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
8786 I.swapOperands();
8787 Changed = true;
8788 }
8789
8790 const CmpInst::Predicate Pred = I.getPredicate();
8791 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8792 if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
8793 SQ.getWithInstruction(&I)))
8794 return replaceInstUsesWith(I, V);
8795
8796 // Simplify 'fcmp pred X, X'
8797 Type *OpType = Op0->getType();
8798 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
8799 if (Op0 == Op1) {
8800 switch (Pred) {
8801 default:
8802 break;
8803 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
8804 case FCmpInst::FCMP_ULT: // True if unordered or less than
8805 case FCmpInst::FCMP_UGT: // True if unordered or greater than
8806 case FCmpInst::FCMP_UNE: // True if unordered or not equal
8807 // Canonicalize these to be 'fcmp uno %X, 0.0'.
8808 I.setPredicate(FCmpInst::FCMP_UNO);
8809 I.setOperand(1, Constant::getNullValue(OpType));
8810 return &I;
8811
8812 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
8813 case FCmpInst::FCMP_OEQ: // True if ordered and equal
8814 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
8815 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
8816 // Canonicalize these to be 'fcmp ord %X, 0.0'.
8817 I.setPredicate(FCmpInst::FCMP_ORD);
8818 I.setOperand(1, Constant::getNullValue(OpType));
8819 return &I;
8820 }
8821 }
8822
8823 if (I.isCommutative()) {
8824 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
8825 replaceOperand(I, 0, Pair->first);
8826 replaceOperand(I, 1, Pair->second);
8827 return &I;
8828 }
8829 }
8830
8831 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
8832 // then canonicalize the operand to 0.0.
8833 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
8834 if (!match(Op0, m_PosZeroFP()) &&
8835 isKnownNeverNaN(Op0, getSimplifyQuery().getWithInstruction(&I)))
8836 return replaceOperand(I, 0, ConstantFP::getZero(OpType));
8837
8838 if (!match(Op1, m_PosZeroFP()) &&
8839 isKnownNeverNaN(Op1, getSimplifyQuery().getWithInstruction(&I)))
8840 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
8841 }
8842
8843 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
8844 Value *X, *Y;
8845 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
8846 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
8847
8849 return R;
8850
8851 // Test if the FCmpInst instruction is used exclusively by a select as
8852 // part of a minimum or maximum operation. If so, refrain from doing
8853 // any other folding. This helps out other analyses which understand
8854 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
8855 // and CodeGen. And in this case, at least one of the comparison
8856 // operands has at least one user besides the compare (the select),
8857 // which would often largely negate the benefit of folding anyway.
8858 if (I.hasOneUse())
8859 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
8860 Value *A, *B;
8862 bool IsRedundantMinMaxClamp =
8863 (SPR.Flavor == SPF_FMAXNUM || SPR.Flavor == SPF_FMINNUM) &&
8865 if (SPR.Flavor != SPF_UNKNOWN && !IsRedundantMinMaxClamp)
8866 return nullptr;
8867 }
8868
8869 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
8870 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
8871 if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP()))
8872 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
8873
8874 // Canonicalize:
8875 // fcmp olt X, +inf -> fcmp one X, +inf
8876 // fcmp ole X, +inf -> fcmp ord X, 0
8877 // fcmp ogt X, +inf -> false
8878 // fcmp oge X, +inf -> fcmp oeq X, +inf
8879 // fcmp ult X, +inf -> fcmp une X, +inf
8880 // fcmp ule X, +inf -> true
8881 // fcmp ugt X, +inf -> fcmp uno X, 0
8882 // fcmp uge X, +inf -> fcmp ueq X, +inf
8883 // fcmp olt X, -inf -> false
8884 // fcmp ole X, -inf -> fcmp oeq X, -inf
8885 // fcmp ogt X, -inf -> fcmp one X, -inf
8886 // fcmp oge X, -inf -> fcmp ord X, 0
8887 // fcmp ult X, -inf -> fcmp uno X, 0
8888 // fcmp ule X, -inf -> fcmp ueq X, -inf
8889 // fcmp ugt X, -inf -> fcmp une X, -inf
8890 // fcmp uge X, -inf -> true
8891 const APFloat *C;
8892 if (match(Op1, m_APFloat(C)) && C->isInfinity()) {
8893 switch (C->isNegative() ? FCmpInst::getSwappedPredicate(Pred) : Pred) {
8894 default:
8895 break;
8896 case FCmpInst::FCMP_ORD:
8897 case FCmpInst::FCMP_UNO:
8900 case FCmpInst::FCMP_OGT:
8901 case FCmpInst::FCMP_ULE:
8902 llvm_unreachable("Should be simplified by InstSimplify");
8903 case FCmpInst::FCMP_OLT:
8904 return new FCmpInst(FCmpInst::FCMP_ONE, Op0, Op1, "", &I);
8905 case FCmpInst::FCMP_OLE:
8906 return new FCmpInst(FCmpInst::FCMP_ORD, Op0, ConstantFP::getZero(OpType),
8907 "", &I);
8908 case FCmpInst::FCMP_OGE:
8909 return new FCmpInst(FCmpInst::FCMP_OEQ, Op0, Op1, "", &I);
8910 case FCmpInst::FCMP_ULT:
8911 return new FCmpInst(FCmpInst::FCMP_UNE, Op0, Op1, "", &I);
8912 case FCmpInst::FCMP_UGT:
8913 return new FCmpInst(FCmpInst::FCMP_UNO, Op0, ConstantFP::getZero(OpType),
8914 "", &I);
8915 case FCmpInst::FCMP_UGE:
8916 return new FCmpInst(FCmpInst::FCMP_UEQ, Op0, Op1, "", &I);
8917 }
8918 }
8919
8920 // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
8921 // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
8922 if (match(Op1, m_PosZeroFP()) &&
8924 !F.getDenormalMode(Op1->getType()->getScalarType()->getFltSemantics())
8925 .inputsMayBeZero()) {
8927 if (Pred == FCmpInst::FCMP_OEQ)
8928 IntPred = ICmpInst::ICMP_EQ;
8929 else if (Pred == FCmpInst::FCMP_UNE)
8930 IntPred = ICmpInst::ICMP_NE;
8931
8932 if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
8933 Type *IntTy = X->getType();
8934 const APInt &SignMask = ~APInt::getSignMask(IntTy->getScalarSizeInBits());
8935 Value *MaskX = Builder.CreateAnd(X, ConstantInt::get(IntTy, SignMask));
8936 return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(IntTy));
8937 }
8938 }
8939
8940 // Handle fcmp with instruction LHS and constant RHS.
8941 Instruction *LHSI;
8942 Constant *RHSC;
8943 if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
8944 switch (LHSI->getOpcode()) {
8945 case Instruction::Select:
8946 // fcmp eq (cond ? x : -x), 0 --> fcmp eq x, 0
8947 if (FCmpInst::isEquality(Pred) && match(RHSC, m_AnyZeroFP()) &&
8949 return replaceOperand(I, 0, X);
8951 return NV;
8952 break;
8953 case Instruction::FSub:
8954 if (LHSI->hasOneUse())
8955 if (Instruction *NV = foldFCmpFSubIntoFCmp(I, LHSI, RHSC, *this))
8956 return NV;
8957 break;
8958 case Instruction::PHI:
8959 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
8960 return NV;
8961 break;
8962 case Instruction::SIToFP:
8963 case Instruction::UIToFP:
8964 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
8965 return NV;
8966 break;
8967 case Instruction::FDiv:
8968 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
8969 return NV;
8970 break;
8971 case Instruction::Load:
8972 if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
8973 if (Instruction *Res =
8975 return Res;
8976 break;
8977 case Instruction::FPTrunc:
8978 if (Instruction *NV = foldFCmpFpTrunc(I, *LHSI, *RHSC))
8979 return NV;
8980 break;
8981 }
8982 }
8983
8984 if (Instruction *R = foldFabsWithFcmpZero(I, *this))
8985 return R;
8986
8987 if (Instruction *R = foldSqrtWithFcmpZero(I, *this))
8988 return R;
8989
8990 if (Instruction *R = foldFCmpWithFloorAndCeil(I, *this))
8991 return R;
8992
8993 if (match(Op0, m_FNeg(m_Value(X)))) {
8994 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
8995 Constant *C;
8996 if (match(Op1, m_Constant(C)))
8997 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
8998 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
8999 }
9000
9001 // fcmp (fadd X, 0.0), Y --> fcmp X, Y
9002 if (match(Op0, m_FAdd(m_Value(X), m_AnyZeroFP())))
9003 return new FCmpInst(Pred, X, Op1, "", &I);
9004
9005 // fcmp X, (fadd Y, 0.0) --> fcmp X, Y
9006 if (match(Op1, m_FAdd(m_Value(Y), m_AnyZeroFP())))
9007 return new FCmpInst(Pred, Op0, Y, "", &I);
9008
9009 if (match(Op0, m_FPExt(m_Value(X)))) {
9010 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
9011 if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
9012 return new FCmpInst(Pred, X, Y, "", &I);
9013
9014 const APFloat *C;
9015 if (match(Op1, m_APFloat(C))) {
9016 const fltSemantics &FPSem =
9017 X->getType()->getScalarType()->getFltSemantics();
9018 bool Lossy;
9019 APFloat TruncC = *C;
9020 TruncC.convert(FPSem, APFloat::rmNearestTiesToEven, &Lossy);
9021
9022 if (Lossy) {
9023 // X can't possibly equal the higher-precision constant, so reduce any
9024 // equality comparison.
9025 // TODO: Other predicates can be handled via getFCmpCode().
9026 switch (Pred) {
9027 case FCmpInst::FCMP_OEQ:
9028 // X is ordered and equal to an impossible constant --> false
9029 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9030 case FCmpInst::FCMP_ONE:
9031 // X is ordered and not equal to an impossible constant --> ordered
9032 return new FCmpInst(FCmpInst::FCMP_ORD, X,
9033 ConstantFP::getZero(X->getType()));
9034 case FCmpInst::FCMP_UEQ:
9035 // X is unordered or equal to an impossible constant --> unordered
9036 return new FCmpInst(FCmpInst::FCMP_UNO, X,
9037 ConstantFP::getZero(X->getType()));
9038 case FCmpInst::FCMP_UNE:
9039 // X is unordered or not equal to an impossible constant --> true
9040 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9041 default:
9042 break;
9043 }
9044 }
9045
9046 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
9047 // Avoid lossy conversions and denormals.
9048 // Zero is a special case that's OK to convert.
9049 APFloat Fabs = TruncC;
9050 Fabs.clearSign();
9051 if (!Lossy &&
9052 (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(FPSem)))) {
9053 Constant *NewC = ConstantFP::get(X->getType(), TruncC);
9054 return new FCmpInst(Pred, X, NewC, "", &I);
9055 }
9056 }
9057 }
9058
9059 // Convert a sign-bit test of an FP value into a cast and integer compare.
9060 // TODO: Simplify if the copysign constant is 0.0 or NaN.
9061 // TODO: Handle non-zero compare constants.
9062 // TODO: Handle other predicates.
9064 m_Value(X)))) &&
9065 match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
9066 Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits());
9067 if (auto *VecTy = dyn_cast<VectorType>(OpType))
9068 IntType = VectorType::get(IntType, VecTy->getElementCount());
9069
9070 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
9071 if (Pred == FCmpInst::FCMP_OLT) {
9072 Value *IntX = Builder.CreateBitCast(X, IntType);
9073 return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
9074 ConstantInt::getNullValue(IntType));
9075 }
9076 }
9077
9078 {
9079 Value *CanonLHS = nullptr;
9081 // (canonicalize(x) == x) => (x == x)
9082 if (CanonLHS == Op1)
9083 return new FCmpInst(Pred, Op1, Op1, "", &I);
9084
9085 Value *CanonRHS = nullptr;
9087 // (x == canonicalize(x)) => (x == x)
9088 if (CanonRHS == Op0)
9089 return new FCmpInst(Pred, Op0, Op0, "", &I);
9090
9091 // (canonicalize(x) == canonicalize(y)) => (x == y)
9092 if (CanonLHS && CanonRHS)
9093 return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
9094 }
9095
9096 if (I.getType()->isVectorTy())
9097 if (Instruction *Res = foldVectorCmp(I, Builder))
9098 return Res;
9099
9100 return Changed ? &I : nullptr;
9101}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
Rewrite undef for PHI
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define Check(C,...)
Hexagon Common GEP
static Instruction * foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI, Constant *RHSC)
Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
static Instruction * foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC)
Optimize fabs(X) compared with zero.
static void collectOffsetOp(Value *V, SmallVectorImpl< OffsetOp > &Offsets, bool AllowRecursion)
static Value * rewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags NW, const DataLayout &DL, SetVector< Value * > &Explored, InstCombiner &IC)
Returns a re-written value of Start as an indexed GEP using Base as a pointer.
static bool isMinMaxCmpSelectEliminable(SelectPatternFlavor Flavor, Value *A, Value *B)
Returns true if a select that implements a min/max is redundant and select result can be replaced wit...
static Instruction * foldICmpEqualityWithOffset(ICmpInst &I, InstCombiner::BuilderTy &Builder, const SimplifyQuery &SQ)
Offset both sides of an equality icmp to see if we can save some instructions: icmp eq/ne X,...
static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2, bool IsSigned=false)
Compute Result = In1+In2, returning true if the result overflowed for this type.
static Instruction * foldICmpOfVectorReduce(ICmpInst &I, const DataLayout &DL, IRBuilderBase &Builder)
static Instruction * foldICmpAndXX(ICmpInst &I, const SimplifyQuery &Q, InstCombinerImpl &IC)
static Instruction * foldVectorCmp(CmpInst &Cmp, InstCombiner::BuilderTy &Builder)
static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q, unsigned Depth=0)
static Value * createLogicFromTable(const std::bitset< 4 > &Table, Value *Op0, Value *Op1, IRBuilderBase &Builder, bool HasOneUse)
static Instruction * foldICmpOfUAddOv(ICmpInst &I)
static bool isChainSelectCmpBranch(const SelectInst *SI)
Return true when the instruction sequence within a block is select-cmp-br.
static Instruction * foldICmpInvariantGroup(ICmpInst &I)
std::pair< Instruction::BinaryOps, Value * > OffsetOp
Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
static Instruction * foldReductionIdiom(ICmpInst &I, InstCombiner::BuilderTy &Builder, const DataLayout &DL)
This function folds patterns produced by lowering of reduce idioms, such as llvm.vector....
static Instruction * canonicalizeICmpBool(ICmpInst &I, InstCombiner::BuilderTy &Builder)
Integer compare with boolean values can always be turned into bitwise ops.
static Instruction * foldFCmpFSubIntoFCmp(FCmpInst &I, Instruction *LHSI, Constant *RHSC, InstCombinerImpl &CI)
static Value * foldICmpOrXorSubChain(ICmpInst &Cmp, BinaryOperator *Or, InstCombiner::BuilderTy &Builder)
Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
static bool hasBranchUse(ICmpInst &I)
Given an icmp instruction, return true if any use of this comparison is a branch on sign bit comparis...
static Value * foldICmpWithLowBitMaskedVal(CmpPredicate Pred, Value *Op0, Value *Op1, const SimplifyQuery &Q, InstCombiner &IC)
Some comparisons can be simplified.
static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth)
When performing a comparison against a constant, it is possible that not all the bits in the LHS are ...
static Instruction * foldICmpShlLHSC(ICmpInst &Cmp, Instruction *Shl, const APInt &C)
Fold icmp (shl nuw C2, Y), C.
static Instruction * foldFCmpWithFloorAndCeil(FCmpInst &I, InstCombinerImpl &IC)
static Instruction * foldICmpXorXX(ICmpInst &I, const SimplifyQuery &Q, InstCombinerImpl &IC)
static Instruction * foldICmpOfCmpIntrinsicWithConstant(CmpPredicate Pred, IntrinsicInst *I, const APInt &C, InstCombiner::BuilderTy &Builder)
static Instruction * processUMulZExtIdiom(ICmpInst &I, Value *MulVal, const APInt *OtherVal, InstCombinerImpl &IC)
Recognize and process idiom involving test for multiplication overflow.
static Instruction * foldSqrtWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC)
Optimize sqrt(X) compared with zero.
static Instruction * foldFCmpFNegCommonOp(FCmpInst &I)
static Instruction * foldICmpWithHighBitMask(ICmpInst &Cmp, InstCombiner::BuilderTy &Builder)
static ICmpInst * canonicalizeCmpWithConstant(ICmpInst &I)
If we have an icmp le or icmp ge instruction with a constant operand, turn it into the appropriate ic...
static Instruction * foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp, InstCombiner::BuilderTy &Builder)
Fold an icmp with LLVM intrinsics.
static Instruction * foldICmpUSubSatOrUAddSatWithConstant(CmpPredicate Pred, SaturatingInst *II, const APInt &C, InstCombiner::BuilderTy &Builder)
static Instruction * foldICmpPow2Test(ICmpInst &I, InstCombiner::BuilderTy &Builder)
static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2, bool IsSigned=false)
Compute Result = In1-In2, returning true if the result overflowed for this type.
static bool canRewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags &NW, const DataLayout &DL, SetVector< Value * > &Explored)
Returns true if we can rewrite Start as a GEP with pointer Base and some integer offset.
static Instruction * foldFCmpFpTrunc(FCmpInst &I, const Instruction &FPTrunc, const Constant &C)
static Instruction * foldICmpXNegX(ICmpInst &I, InstCombiner::BuilderTy &Builder)
static Instruction * processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B, ConstantInt *CI2, ConstantInt *CI1, InstCombinerImpl &IC)
The caller has matched a pattern of the form: I = icmp ugt (add (add A, B), CI2), CI1 If this is of t...
static Value * foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ, InstCombiner::BuilderTy &Builder)
static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C)
Returns true if the exploded icmp can be expressed as a signed comparison to zero and updates the pre...
static Instruction * transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS, CmpPredicate Cond, const DataLayout &DL, InstCombiner &IC)
Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
static Instruction * foldCtpopPow2Test(ICmpInst &I, IntrinsicInst *CtpopLhs, const APInt &CRhs, InstCombiner::BuilderTy &Builder, const SimplifyQuery &Q)
static void setInsertionPoint(IRBuilder<> &Builder, Value *V, bool Before=true)
static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS, bool IsSigned)
static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q)
Return true if X is a multiple of C.
static Value * foldICmpWithTruncSignExtendedVal(ICmpInst &I, InstCombiner::BuilderTy &Builder)
Some comparisons can be simplified.
static Instruction * foldICmpOrXX(ICmpInst &I, const SimplifyQuery &Q, InstCombinerImpl &IC)
This file provides internal interfaces used to implement the InstCombine.
This file provides the interface for the instcombine pass implementation.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:539
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T1
uint64_t IntrinsicInst * II
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file implements a set that has insertion order iteration characteristics.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
BinaryOperator * Mul
static constexpr roundingMode rmTowardZero
Definition APFloat.h:348
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:344
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:360
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:5976
void clearSign()
Definition APFloat.h:1353
bool isNaN() const
Definition APFloat.h:1514
bool isZero() const
Definition APFloat.h:1512
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1213
APInt bitcastToAPInt() const
Definition APFloat.h:1408
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1193
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1387
opStatus next(bool nextDown)
Definition APFloat.h:1309
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1153
LLVM_ABI FPClassTest classify() const
Return the FPClassTest which will return true for the value.
Definition APFloat.cpp:5905
opStatus roundToIntegral(roundingMode RM)
Definition APFloat.h:1303
bool isInfinity() const
Definition APFloat.h:1513
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1584
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1769
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:450
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1023
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:230
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:424
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1555
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1527
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:936
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:207
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1345
APInt abs() const
Get the absolute value.
Definition APInt.h:1810
unsigned ceilLogBase2() const
Definition APInt.h:1779
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1208
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
LLVM_ABI APInt usub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1959
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1189
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:467
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1503
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1118
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:217
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1939
bool eq(const APInt &RHS) const
Equality comparison.
Definition APInt.h:1086
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1655
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1946
void negate()
Negate this APInt in place.
Definition APInt.h:1483
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1654
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1613
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:357
void flipAllBits()
Toggle every bit to its opposite value.
Definition APInt.h:1467
unsigned countl_one() const
Count the number of leading one bits.
Definition APInt.h:1630
unsigned logBase2() const
Definition APInt.h:1776
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:476
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:834
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:406
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1157
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:880
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:297
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1244
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1952
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:390
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:287
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:858
unsigned countr_one() const
Count the number of trailing one bits.
Definition APInt.h:1671
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1228
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
static APSInt getMinValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the minimum integer value with the given bit width and signedness.
Definition APSInt.h:310
static APSInt getMaxValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the maximum integer value with the given bit width and signedness.
Definition APSInt.h:302
an instruction to allocate memory on the stack
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
BinaryOps getOpcode() const
Definition InstrTypes.h:374
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Conditional or Unconditional Branch instruction.
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This class is the base class for the comparison instructions.
Definition InstrTypes.h:664
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition InstrTypes.h:982
Predicate getStrictPredicate() const
For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT.
Definition InstrTypes.h:858
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:679
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:693
@ ICMP_SLT
signed less than
Definition InstrTypes.h:705
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:706
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:682
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:691
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:680
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:681
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:700
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:690
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:684
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:687
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:688
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:683
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:685
@ ICMP_NE
not equal
Definition InstrTypes.h:698
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:704
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:692
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:702
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:689
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:678
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:686
bool isSigned() const
Definition InstrTypes.h:930
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:827
bool isTrueWhenEqual() const
This is just a convenience.
Definition InstrTypes.h:942
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition InstrTypes.h:871
static LLVM_ABI bool isStrictPredicate(Predicate predicate)
This is a static version that you can use without an instruction available.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:789
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:765
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:776
bool isUnsigned() const
Definition InstrTypes.h:936
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI CmpPredicate getSwapped(CmpPredicate P)
Get the swapped predicate of a CmpPredicate.
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getXor(Constant *C1, Constant *C2)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI Constant * getZero(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI std::optional< ConstantRange > exactUnionWith(const ConstantRange &CR) const
Union the two ranges and return the result if it can be represented exactly, otherwise return std::nu...
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
LLVM_ABI ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
LLVM_ABI ConstantRange difference(const ConstantRange &CR) const
Subtract the specified range from this range (aka relative complement of the sets).
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
LLVM_ABI std::optional< ConstantRange > exactIntersectWith(const ConstantRange &CR) const
Intersect the two ranges and return the result if it can be represented exactly, otherwise return std...
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI const APInt & getUniqueInteger() const
If C is a constant integer then return its value, otherwise C must be a vector of constant integers,...
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constants.cpp:74
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
iterator end()
Definition DenseMap.h:81
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:169
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This instruction compares its operands according to the predicate given to the constructor.
static bool isEquality(Predicate Pred)
Represents flags for the getelementptr instruction/expression.
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
bool isInBounds() const
GEPNoWrapFlags intersectForOffsetAdd(GEPNoWrapFlags Other) const
Given (gep (gep p, x), y), determine the nowrap flags for (gep p, x+y).
static GEPNoWrapFlags none()
bool isInBounds() const
Test whether this is an inbounds GEP, as defined by LangRef.html.
Definition Operator.h:430
LLVM_ABI Type * getSourceElementType() const
Definition Operator.cpp:82
Value * getPointerOperand()
Definition Operator.h:457
GEPNoWrapFlags getNoWrapFlags() const
Definition Operator.h:425
bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
Definition Operator.h:504
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
This instruction compares its operands according to the predicate given to the constructor.
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1554
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:207
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2418
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1576
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition IRBuilder.h:537
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2788
Instruction * foldICmpShrConstant(ICmpInst &Cmp, BinaryOperator *Shr, const APInt &C)
Fold icmp ({al}shr X, Y), C.
Instruction * foldICmpWithZextOrSext(ICmpInst &ICmp)
Instruction * foldICmpSelectConstant(ICmpInst &Cmp, SelectInst *Select, ConstantInt *C)
Instruction * foldICmpSRemConstant(ICmpInst &Cmp, BinaryOperator *UDiv, const APInt &C)
Instruction * foldICmpBinOpWithConstant(ICmpInst &Cmp, BinaryOperator *BO, const APInt &C)
Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
Instruction * foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or, const APInt &C)
Fold icmp (or X, Y), C.
Instruction * foldICmpTruncWithTruncOrExt(ICmpInst &Cmp, const SimplifyQuery &Q)
Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
Instruction * foldSignBitTest(ICmpInst &I)
Fold equality-comparison between zero and any (maybe truncated) right-shift by one-less-than-bitwidth...
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN, bool AllowMultipleUses=false)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Value * insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi, bool isSigned, bool Inside)
Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise (V < Lo || V >= Hi).
Instruction * foldICmpBinOp(ICmpInst &Cmp, const SimplifyQuery &SQ)
Try to fold icmp (binop), X or icmp X, (binop).
Instruction * foldCmpLoadFromIndexedGlobal(LoadInst *LI, GetElementPtrInst *GEP, CmpInst &ICI, ConstantInt *AndCst=nullptr)
This is called when we see this pattern: cmp pred (load (gep GV, ...)), cmpcst where GV is a global v...
Instruction * foldICmpSubConstant(ICmpInst &Cmp, BinaryOperator *Sub, const APInt &C)
Fold icmp (sub X, Y), C.
Instruction * foldICmpWithClamp(ICmpInst &Cmp, Value *X, MinMaxIntrinsic *Min)
Match and fold patterns like: icmp eq/ne X, min(max(X, Lo), Hi) which represents a range check and ca...
Instruction * foldICmpInstWithConstantNotInt(ICmpInst &Cmp)
Handle icmp with constant (but not simple integer constant) RHS.
bool SimplifyDemandedBits(Instruction *I, unsigned Op, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0) override
This form of SimplifyDemandedBits simplifies the specified instruction operand if possible,...
Instruction * foldICmpShlConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1, const APInt &C2)
Handle "(icmp eq/ne (shl AP2, A), AP1)" -> (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
Value * reassociateShiftAmtsOfTwoSameDirectionShifts(BinaryOperator *Sh0, const SimplifyQuery &SQ, bool AnalyzeForSignBitExtraction=false)
Instruction * foldICmpEqIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II, const APInt &C)
Fold an equality icmp with LLVM intrinsic and constant operand.
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false, bool SimplifyBothArms=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Value * foldMultiplicationOverflowCheck(ICmpInst &Cmp)
Fold (-1 u/ x) u< y ((x * y) ?
Instruction * foldICmpWithConstant(ICmpInst &Cmp)
Fold icmp Pred X, C.
CmpInst * canonicalizeICmpPredicate(CmpInst &I)
If we have a comparison with a non-canonical predicate, if we can update all the users,...
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * foldICmpWithZero(ICmpInst &Cmp)
Instruction * foldICmpCommutative(CmpPredicate Pred, Value *Op0, Value *Op1, ICmpInst &CxtI)
Instruction * foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp, BinaryOperator *BO, const APInt &C)
Fold an icmp equality instruction with binary operator LHS and constant RHS: icmp eq/ne BO,...
Instruction * foldICmpUsingBoolRange(ICmpInst &I)
If one operand of an icmp is effectively a bool (value range of {0,1}), then try to reduce patterns b...
Instruction * foldICmpWithTrunc(ICmpInst &Cmp)
Instruction * foldICmpIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II, const APInt &C)
Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
bool matchThreeWayIntCompare(SelectInst *SI, Value *&LHS, Value *&RHS, ConstantInt *&Less, ConstantInt *&Equal, ConstantInt *&Greater)
Match a select chain which produces one of three values based on whether the LHS is less than,...
Instruction * visitFCmpInst(FCmpInst &I)
Instruction * foldICmpUsingKnownBits(ICmpInst &Cmp)
Try to fold the comparison based on range information we can get by checking whether bits are known t...
Instruction * foldICmpDivConstant(ICmpInst &Cmp, BinaryOperator *Div, const APInt &C)
Fold icmp ({su}div X, Y), C.
Instruction * foldIRemByPowerOfTwoToBitTest(ICmpInst &I)
If we have: icmp eq/ne (urem/srem x, y), 0 iff y is a power-of-two, we can replace this with a bit te...
Instruction * foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI, Constant *RHSC)
Fold fcmp ([us]itofp x, cst) if possible.
Instruction * foldICmpUDivConstant(ICmpInst &Cmp, BinaryOperator *UDiv, const APInt &C)
Fold icmp (udiv X, Y), C.
Instruction * foldICmpAddOpConst(Value *X, const APInt &C, CmpPredicate Pred)
Fold "icmp pred (X+C), X".
Instruction * foldICmpWithCastOp(ICmpInst &ICmp)
Handle icmp (cast x), (cast or constant).
Instruction * foldICmpTruncConstant(ICmpInst &Cmp, TruncInst *Trunc, const APInt &C)
Fold icmp (trunc X), C.
Instruction * foldICmpAddConstant(ICmpInst &Cmp, BinaryOperator *Add, const APInt &C)
Fold icmp (add X, Y), C.
Instruction * foldICmpMulConstant(ICmpInst &Cmp, BinaryOperator *Mul, const APInt &C)
Fold icmp (mul X, Y), C.
Instruction * tryFoldInstWithCtpopWithNot(Instruction *I)
Instruction * foldICmpXorConstant(ICmpInst &Cmp, BinaryOperator *Xor, const APInt &C)
Fold icmp (xor X, Y), C.
Instruction * foldSelectICmp(CmpPredicate Pred, SelectInst *SI, Value *RHS, const ICmpInst &I)
Instruction * foldICmpInstWithConstantAllowPoison(ICmpInst &Cmp, const APInt &C)
Try to fold integer comparisons with a constant operand: icmp Pred X, C where X is some kind of instr...
Instruction * foldIsMultipleOfAPowerOfTwo(ICmpInst &Cmp)
Fold icmp eq (num + mask) & ~mask, num to icmp eq (and num, mask), 0 Where mask is a low bit mask.
Instruction * foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And, const APInt &C1, const APInt &C2)
Fold icmp (and (sh X, Y), C2), C1.
Instruction * foldICmpBinOpWithConstantViaTruthTable(ICmpInst &Cmp, BinaryOperator *BO, const APInt &C)
Instruction * foldICmpInstWithConstant(ICmpInst &Cmp)
Try to fold integer comparisons with a constant operand: icmp Pred X, C where X is some kind of instr...
Instruction * foldICmpXorShiftConst(ICmpInst &Cmp, BinaryOperator *Xor, const APInt &C)
For power-of-2 C: ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1) ((X s>> ShiftC) ^ X) u> (C - 1) -...
Instruction * foldICmpShlConstant(ICmpInst &Cmp, BinaryOperator *Shl, const APInt &C)
Fold icmp (shl X, Y), C.
Instruction * foldICmpAndConstant(ICmpInst &Cmp, BinaryOperator *And, const APInt &C)
Fold icmp (and X, Y), C.
Instruction * foldICmpEquality(ICmpInst &Cmp)
Instruction * foldICmpWithMinMax(Instruction &I, MinMaxIntrinsic *MinMax, Value *Z, CmpPredicate Pred)
Fold icmp Pred min|max(X, Y), Z.
bool dominatesAllUses(const Instruction *DI, const Instruction *UI, const BasicBlock *DB) const
True when DB dominates all uses of DI except UI.
bool foldAllocaCmp(AllocaInst *Alloca)
Instruction * visitICmpInst(ICmpInst &I)
OverflowResult computeOverflow(Instruction::BinaryOps BinaryOp, bool IsSigned, Value *LHS, Value *RHS, Instruction *CxtI) const
Instruction * foldICmpWithDominatingICmp(ICmpInst &Cmp)
Canonicalize icmp instructions based on dominating conditions.
bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp, const unsigned SIOpd)
Try to replace select with select operand SIOpd in SI-ICmp sequence.
Instruction * foldICmpShrConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1, const APInt &C2)
Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" -> (icmp eq/ne A, Log2(AP2/AP1)) -> (icmp eq/ne A,...
void freelyInvertAllUsersOf(Value *V, Value *IgnoredUser=nullptr)
Freely adapt every user of V as-if V was changed to !V.
Instruction * foldICmpAndConstConst(ICmpInst &Cmp, BinaryOperator *And, const APInt &C1)
Fold icmp (and X, C2), C1.
Instruction * foldICmpBitCast(ICmpInst &Cmp)
Instruction * foldGEPICmp(GEPOperator *GEPLHS, Value *RHS, CmpPredicate Cond, Instruction &I)
Fold comparisons between a GEP instruction and something else.
The core instruction combiner logic.
OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
SimplifyQuery SQ
unsigned ComputeMaxSignificantBits(const Value *Op, const Instruction *CxtI=nullptr, unsigned Depth=0) const
IRBuilder< TargetFolder, IRBuilderCallbackInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
bool isFreeToInvert(Value *V, bool WillInvertAllUses, bool &DoesConsume)
Return true if the specified value is free to invert (apply ~ to).
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const Instruction *CxtI, bool IsNSW=false) const
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
TargetLibraryInfo & TLI
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
uint64_t MaxArraySizeForCombine
Maximum size of array considered when transforming.
OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const Instruction *CxtI) const
static Constant * SubOne(Constant *C)
Subtract one from a Constant.
OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
static bool isCanonicalPredicate(CmpPredicate Pred)
Predicate canonicalization reduces the number of patterns that need to be matched by other transforms...
const DataLayout & DL
DomConditionCache DC
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CxtI, unsigned Depth=0) const
bool canFreelyInvertAllUsersOf(Instruction *V, Value *IgnoredUser)
Given i1 V, can every user of V be freely adapted if V is changed to !V ?
void addToWorklist(Instruction *I)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
DominatorTree & DT
OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
BuilderTy & Builder
OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const Instruction *CxtI) const
Value * getFreelyInverted(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume)
const SimplifyQuery & getSimplifyQuery() const
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, const Instruction *CxtI=nullptr, unsigned Depth=0)
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoInfs() const LLVM_READONLY
Determine whether the no-infs flag is set.
bool isArithmeticShift() const
Return true if this is an arithmetic shift right.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isShift() const
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:318
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
An instruction for reading from memory.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
This class represents min/max intrinsics.
Value * getLHS() const
Value * getRHS() const
static bool isMin(Intrinsic::ID ID)
Whether the intrinsic is a smin or umin.
static bool isSigned(Intrinsic::ID ID)
Whether the intrinsic is signed or unsigned.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
Represents a saturating add/sub intrinsic.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:252
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
This instruction constructs a fixed permutation of two input vectors.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class represents a truncation of integer types.
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:246
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition Type.h:165
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:230
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:293
LLVM_ABI int getFPMantissaWidth() const
Return the width of the mantissa of this type.
Definition Type.cpp:235
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:106
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:440
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:259
iterator_range< user_iterator > users()
Definition Value.h:427
LLVM_ABI bool hasNUsesOrMore(unsigned N) const
Return true if this value has N uses or more.
Definition Value.cpp:158
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
iterator_range< use_iterator > uses()
Definition Value.h:381
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:403
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A unsign-divided by B, rounded by the given rounding mode.
Definition APInt.cpp:2774
LLVM_ABI APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A sign-divided by B, rounded by the given rounding mode.
Definition APInt.cpp:2792
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
cst_pred_ty< is_negative > m_Negative()
Match an integer or vector of negative values.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
match_combine_or< CastInst_match< OpTy, ZExtInst >, OpTy > m_ZExtOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWNeg(const ValTy &V)
Matches a 'Neg' as 'sub nsw 0, V'.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
BinOpPred_match< LHS, RHS, is_logical_shift_op > m_LogicalShift(const LHS &L, const RHS &R)
Matches logical shift operations.
match_combine_and< LTy, RTy > m_CombineAnd(const LTy &L, const RTy &R)
Combine two pattern matchers matching L && R.
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty > m_SMin(const LHS &L, const RHS &R)
m_Intrinsic_Ty< Opnd0 >::Ty m_Sqrt(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
deferredval_ty< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
NoWrapTrunc_match< OpTy, TruncInst::NoSignedWrap > m_NSWTrunc(const OpTy &Op)
Matches trunc nsw.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
MaxMin_match< ICmpInst, LHS, RHS, umax_pred_ty > m_UMax(const LHS &L, const RHS &R)
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
cst_pred_ty< is_negated_power2_or_zero > m_NegatedPower2OrZero()
Match a integer or vector negated power-of-2.
NoWrapTrunc_match< OpTy, TruncInst::NoUnsignedWrap > m_NUWTrunc(const OpTy &Op)
Matches trunc nuw.
cst_pred_ty< custom_checkfn< APInt > > m_CheckedInt(function_ref< bool(const APInt &)> CheckFn)
Match an integer or vector where CheckFn(ele) for each element is true.
SelectLike_match< CondTy, LTy, RTy > m_SelectLike(const CondTy &C, const LTy &TrueC, const RTy &FalseC)
Matches a value that behaves like a boolean-controlled select, i.e.
cst_pred_ty< is_lowbit_mask_or_zero > m_LowBitMaskOrZero()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastInst_match< OpTy, UIToFPInst > m_UIToFP(const OpTy &Op)
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty > m_SMax(const LHS &L, const RHS &R)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Signum_match< Val_t > m_Signum(const Val_t &V)
Matches a signum pattern.
CastInst_match< OpTy, SIToFPInst > m_SIToFP(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
cstfp_pred_ty< is_pos_zero_fp > m_PosZeroFP()
Match a floating-point positive zero.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
UAddWithOverflow_match< LHS_t, RHS_t, Sum_t > m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S)
Match an icmp instruction checking for unsigned overflow on addition.
m_Intrinsic_Ty< Opnd0 >::Ty m_VecReverse(const Opnd0 &Op0)
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
match_combine_or< match_combine_or< MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty >, MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty > >, match_combine_or< MaxMin_match< ICmpInst, LHS, RHS, umax_pred_ty >, MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty > > > m_MaxOrMin(const LHS &L, const RHS &R)
CastInst_match< OpTy, FPTruncInst > m_FPTrunc(const OpTy &Op)
auto m_Undef()
Match an arbitrary undef constant.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
m_Intrinsic_Ty< Opnd0 >::Ty m_FAbs(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
match_unless< Ty > m_Unless(const Ty &M)
Match if the inner matcher does NOT match.
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
cst_pred_ty< icmp_pred_with_threshold > m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold)
Match an integer or vector with every element comparing 'pred' (eg/ne/...) to Threshold.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
@ Offset
Definition DWP.cpp:532
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:831
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
cl::opt< bool > ProfcheckDisableMetadataFixes
Definition Metadata.cpp:64
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI Value * stripNullTest(Value *V)
Returns the inner value X if the expression has the form f(X) where f(X) == 0 if and only if X == 0,...
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:634
LLVM_ABI Value * simplifyFCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q)
Given operands for an FCmpInst, fold the result or return null.
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1601
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, bool UseInstrInfo=true, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:331
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:236
LLVM_ABI Value * emitGEPOffset(IRBuilderBase *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
Definition Local.cpp:22
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
LLVM_ABI bool isKnownNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UNKNOWN
@ SPF_FMINNUM
Unsigned maximum.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI LinearExpression decomposeLinearExpression(const DataLayout &DL, Value *Ptr)
Decompose a pointer into a linear expression.
Definition Loads.cpp:907
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM)
Returns: X * 2^Exp for integral exponents.
Definition APFloat.h:1610
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
LLVM_ABI Value * simplifyICmpInst(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:394
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ Xor
Bitwise or logical XOR of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
constexpr unsigned BitWidth
LLVM_ABI Constant * getLosslessInvCast(Constant *C, Type *InvCastTo, unsigned CastOp, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
Try to cast C to InvC losslessly, satisfying CastOp(InvC) equals C, or CastOp(InvC) is a refined valu...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2166
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
@ Continue
Definition DWP.h:22
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
std::optional< DecomposedBitTest > decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate Pred, bool LookThroughTrunc=true, bool AllowNonZeroC=false, bool DecomposeAnd=false)
Decompose an icmp into the form ((X & Mask) pred C) if possible.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
#define NC
Definition regutils.h:42
Value * materialize(InstCombiner::BuilderTy &Builder) const
static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV, Instruction *MDFrom)
static OffsetResult value(Value *V)
static OffsetResult invalid()
This callback is used in conjunction with PointerMayBeCaptured.
static CommonPointerBase compute(Value *LHS, Value *RHS)
Represent subnormal handling kind for floating point instruction inputs and outputs.
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
static constexpr DenormalMode getIEEE()
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:108
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:80
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:258
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:290
APInt getSignedMaxValue() const
Return the maximal signed value possible given these KnownBits.
Definition KnownBits.h:154
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:305
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:264
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:148
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:132
bool isStrictlyPositive() const
Returns true if this value is known to be positive.
Definition KnownBits.h:114
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:105
unsigned countMinPopulation() const
Returns the number of bits known to be one.
Definition KnownBits.h:302
APInt getSignedMinValue() const
Return the minimal signed value possible given these KnownBits.
Definition KnownBits.h:138
const APInt & getConstant() const
Returns the value when all bits have a known value.
Definition KnownBits.h:60
Linear expression BasePtr + Index * Scale + Offset.
Definition Loads.h:211
GEPNoWrapFlags Flags
Definition Loads.h:216
Matching combinators.
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
const DataLayout & DL
const Instruction * CxtI
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:276
Capture information for a specific Use.