LLVM 24.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/APInt.h"
16#include "llvm/ADT/APSInt.h"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/Loads.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/InstrTypes.h"
30#include "llvm/IR/Instruction.h"
36#include <bitset>
37
38using namespace llvm;
39using namespace PatternMatch;
40
41#define DEBUG_TYPE "instcombine"
42
43// How many times is a select replaced by one of its operands?
44STATISTIC(NumSel, "Number of select opts");
45
46/// Compute Result = In1+In2, returning true if the result overflowed for this
47/// type.
48static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
49 bool IsSigned = false) {
50 bool Overflow;
51 if (IsSigned)
52 Result = In1.sadd_ov(In2, Overflow);
53 else
54 Result = In1.uadd_ov(In2, Overflow);
55
56 return Overflow;
57}
58
59/// Compute Result = In1-In2, returning true if the result overflowed for this
60/// type.
61static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
62 bool IsSigned = false) {
63 bool Overflow;
64 if (IsSigned)
65 Result = In1.ssub_ov(In2, Overflow);
66 else
67 Result = In1.usub_ov(In2, Overflow);
68
69 return Overflow;
70}
71
72/// Given an icmp instruction, return true if any use of this comparison is a
73/// branch on sign bit comparison.
74static bool hasBranchUse(ICmpInst &I) {
75 for (auto *U : I.users())
76 if (isa<CondBrInst>(U))
77 return true;
78 return false;
79}
80
81/// Returns true if the exploded icmp can be expressed as a signed comparison
82/// to zero and updates the predicate accordingly.
83/// The signedness of the comparison is preserved.
84/// TODO: Refactor with decomposeBitTestICmp()?
85static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
86 if (!ICmpInst::isSigned(Pred))
87 return false;
88
89 if (C.isZero())
90 return ICmpInst::isRelational(Pred);
91
92 if (C.isOne()) {
93 if (Pred == ICmpInst::ICMP_SLT) {
94 Pred = ICmpInst::ICMP_SLE;
95 return true;
96 }
97 } else if (C.isAllOnes()) {
98 if (Pred == ICmpInst::ICMP_SGT) {
99 Pred = ICmpInst::ICMP_SGE;
100 return true;
101 }
102 }
103
104 return false;
105}
106
107/// This is called when we see this pattern:
108/// cmp pred (load (gep GV, ...)), cmpcst
109/// where GV is a global variable with a constant initializer. Try to simplify
110/// this into some simple computation that does not need the load. For example
111/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
112///
113/// If AndCst is non-null, then the loaded value is masked with that constant
114/// before doing the comparison. This handles cases like "A[i]&4 == 0".
115///
116/// We allow multi-use cases in this fold, even though it can increase
117/// instruction count, because it appears to be mostly beneficial in practice.
118/// Even if there are multiple uses, they can often be sunk into the block
119/// guarded by the icmp.
121 LoadInst *LI, GetElementPtrInst *GEP, CmpInst &ICI, ConstantInt *AndCst) {
123 if (LI->isVolatile() || !GV || !GV->isConstant() ||
124 !GV->hasDefinitiveInitializer())
125 return nullptr;
126
127 Type *EltTy = LI->getType();
128 TypeSize EltSize = DL.getTypeStoreSize(EltTy);
129 if (EltSize.isScalable())
130 return nullptr;
131
133 if (!Expr.Index || Expr.BasePtr != GV || Expr.Offset.getBitWidth() > 64)
134 return nullptr;
135
136 Constant *Init = GV->getInitializer();
137 TypeSize GlobalSize = DL.getTypeAllocSize(Init->getType());
138
139 Value *Idx = Expr.Index;
140 const APInt &Stride = Expr.Scale;
141 const APInt &ConstOffset = Expr.Offset;
142
143 // Allow an additional context offset, but only within the stride.
144 if (!ConstOffset.ult(Stride))
145 return nullptr;
146
147 // Don't handle overlapping loads for now.
148 if (!Stride.uge(EltSize.getFixedValue()))
149 return nullptr;
150
151 // Don't blow up on huge arrays.
152 uint64_t ArrayElementCount =
153 divideCeil((GlobalSize.getFixedValue() - ConstOffset.getZExtValue()),
154 Stride.getZExtValue());
155 if (ArrayElementCount > CLOpts.maxarray_size)
156 return nullptr;
157
158 enum { Overdefined = -3, Undefined = -2 };
159
160 // Variables for our state machines.
161
162 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
163 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
164 // and 87 is the second (and last) index. FirstTrueElement is -2 when
165 // undefined, otherwise set to the first true element. SecondTrueElement is
166 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
167 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
168
169 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
170 // form "i != 47 & i != 87". Same state transitions as for true elements.
171 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
172
173 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
174 /// define a state machine that triggers for ranges of values that the index
175 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
176 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
177 /// index in the range (inclusive). We use -2 for undefined here because we
178 /// use relative comparisons and don't want 0-1 to match -1.
179 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
180
181 // MagicBitvector - This is a magic bitvector where we set a bit if the
182 // comparison is true for element 'i'. If there are 64 elements or less in
183 // the array, this will fully represent all the comparison results.
184 uint64_t MagicBitvector = 0;
185
186 // Scan the array and see if one of our patterns matches.
187 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
188 APInt Offset = ConstOffset;
189 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i, Offset += Stride) {
191 if (!Elt)
192 return nullptr;
193
194 // If the element is masked, handle it.
195 if (AndCst) {
196 Elt = ConstantFoldBinaryOpOperands(Instruction::And, Elt, AndCst, DL);
197 if (!Elt)
198 return nullptr;
199 }
200
201 // Find out if the comparison would be true or false for the i'th element.
203 CompareRHS, DL, &TLI);
204 if (!C)
205 return nullptr;
206
207 // If the result is undef for this element, ignore it.
208 if (isa<UndefValue>(C)) {
209 // Extend range state machines to cover this element in case there is an
210 // undef in the middle of the range.
211 if (TrueRangeEnd == (int)i - 1)
212 TrueRangeEnd = i;
213 if (FalseRangeEnd == (int)i - 1)
214 FalseRangeEnd = i;
215 continue;
216 }
217
218 // If we can't compute the result for any of the elements, we have to give
219 // up evaluating the entire conditional.
220 if (!isa<ConstantInt>(C))
221 return nullptr;
222
223 // Otherwise, we know if the comparison is true or false for this element,
224 // update our state machines.
225 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
226
227 // State machine for single/double/range index comparison.
228 if (IsTrueForElt) {
229 // Update the TrueElement state machine.
230 if (FirstTrueElement == Undefined)
231 FirstTrueElement = TrueRangeEnd = i; // First true element.
232 else {
233 // Update double-compare state machine.
234 if (SecondTrueElement == Undefined)
235 SecondTrueElement = i;
236 else
237 SecondTrueElement = Overdefined;
238
239 // Update range state machine.
240 if (TrueRangeEnd == (int)i - 1)
241 TrueRangeEnd = i;
242 else
243 TrueRangeEnd = Overdefined;
244 }
245 } else {
246 // Update the FalseElement state machine.
247 if (FirstFalseElement == Undefined)
248 FirstFalseElement = FalseRangeEnd = i; // First false element.
249 else {
250 // Update double-compare state machine.
251 if (SecondFalseElement == Undefined)
252 SecondFalseElement = i;
253 else
254 SecondFalseElement = Overdefined;
255
256 // Update range state machine.
257 if (FalseRangeEnd == (int)i - 1)
258 FalseRangeEnd = i;
259 else
260 FalseRangeEnd = Overdefined;
261 }
262 }
263
264 // If this element is in range, update our magic bitvector.
265 if (i < 64 && IsTrueForElt)
266 MagicBitvector |= 1ULL << i;
267
268 // If all of our states become overdefined, bail out early. Since the
269 // predicate is expensive, only check it every 8 elements. This is only
270 // really useful for really huge arrays.
271 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
272 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
273 FalseRangeEnd == Overdefined)
274 return nullptr;
275 }
276
277 // Now that we've scanned the entire array, emit our new comparison(s). We
278 // order the state machines in complexity of the generated code.
279
280 // If inbounds keyword is not present, Idx * Stride can overflow.
281 // Let's assume that Stride is 2 and the wanted value is at offset 0.
282 // Then, there are two possible values for Idx to match offset 0:
283 // 0x00..00, 0x80..00.
284 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
285 // comparison is false if Idx was 0x80..00.
286 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
287 auto MaskIdx = [&](Value *Idx) {
288 if (!Expr.Flags.isInBounds() && Stride.countr_zero() != 0) {
290 Mask = Builder.CreateLShr(Mask, Stride.countr_zero());
291 Idx = Builder.CreateAnd(Idx, Mask);
292 }
293 return Idx;
294 };
295
296 // If the comparison is only true for one or two elements, emit direct
297 // comparisons.
298 if (SecondTrueElement != Overdefined) {
299 Idx = MaskIdx(Idx);
300 // None true -> false.
301 if (FirstTrueElement == Undefined)
302 return replaceInstUsesWith(ICI, Builder.getFalse());
303
304 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
305
306 // True for one element -> 'i == 47'.
307 if (SecondTrueElement == Undefined)
308 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
309
310 // True for two elements -> 'i == 47 | i == 72'.
311 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
312 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
313 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
314 return BinaryOperator::CreateOr(C1, C2);
315 }
316
317 // If the comparison is only false for one or two elements, emit direct
318 // comparisons.
319 if (SecondFalseElement != Overdefined) {
320 Idx = MaskIdx(Idx);
321 // None false -> true.
322 if (FirstFalseElement == Undefined)
323 return replaceInstUsesWith(ICI, Builder.getTrue());
324
325 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
326
327 // False for one element -> 'i != 47'.
328 if (SecondFalseElement == Undefined)
329 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
330
331 // False for two elements -> 'i != 47 & i != 72'.
332 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
333 Value *SecondFalseIdx =
334 ConstantInt::get(Idx->getType(), SecondFalseElement);
335 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
336 return BinaryOperator::CreateAnd(C1, C2);
337 }
338
339 // If the comparison can be replaced with a range comparison for the elements
340 // where it is true, emit the range check.
341 if (TrueRangeEnd != Overdefined) {
342 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
343 Idx = MaskIdx(Idx);
344
345 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
346 if (FirstTrueElement) {
347 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstTrueElement);
348 Idx = Builder.CreateAdd(Idx, Offs);
349 }
350
351 Value *End =
352 ConstantInt::get(Idx->getType(), TrueRangeEnd - FirstTrueElement + 1);
353 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
354 }
355
356 // False range check.
357 if (FalseRangeEnd != Overdefined) {
358 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
359 Idx = MaskIdx(Idx);
360 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
361 if (FirstFalseElement) {
362 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstFalseElement);
363 Idx = Builder.CreateAdd(Idx, Offs);
364 }
365
366 Value *End =
367 ConstantInt::get(Idx->getType(), FalseRangeEnd - FirstFalseElement);
368 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
369 }
370
371 // If a magic bitvector captures the entire comparison state
372 // of this load, replace it with computation that does:
373 // ((magic_cst >> i) & 1) != 0
374 {
375 Type *Ty = nullptr;
376
377 // Look for an appropriate type:
378 // - The type of Idx if the magic fits
379 // - The smallest fitting legal type
380 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
381 Ty = Idx->getType();
382 else
383 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
384
385 if (Ty) {
386 Idx = MaskIdx(Idx);
387 Value *V = Builder.CreateIntCast(Idx, Ty, false);
388 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
389 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
390 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
391 }
392 }
393
394 return nullptr;
395}
396
397/// Returns true if we can rewrite Start as a GEP with pointer Base
398/// and some integer offset. The nodes that need to be re-written
399/// for this transformation will be added to Explored.
401 const DataLayout &DL,
402 SetVector<Value *> &Explored) {
403 SmallVector<Value *, 16> WorkList(1, Start);
404 Explored.insert(Base);
405
406 // The following traversal gives us an order which can be used
407 // when doing the final transformation. Since in the final
408 // transformation we create the PHI replacement instructions first,
409 // we don't have to get them in any particular order.
410 //
411 // However, for other instructions we will have to traverse the
412 // operands of an instruction first, which means that we have to
413 // do a post-order traversal.
414 while (!WorkList.empty()) {
416
417 while (!WorkList.empty()) {
418 if (Explored.size() >= 100)
419 return false;
420
421 Value *V = WorkList.back();
422
423 if (Explored.contains(V)) {
424 WorkList.pop_back();
425 continue;
426 }
427
429 // We've found some value that we can't explore which is different from
430 // the base. Therefore we can't do this transformation.
431 return false;
432
433 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
434 // Only allow inbounds GEPs with at most one variable offset.
435 auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(V); };
436 if (!GEP->isInBounds() || count_if(GEP->indices(), IsNonConst) > 1)
437 return false;
438
439 NW = NW.intersectForOffsetAdd(GEP->getNoWrapFlags());
440 if (!Explored.contains(GEP->getOperand(0)))
441 WorkList.push_back(GEP->getOperand(0));
442 }
443
444 if (WorkList.back() == V) {
445 WorkList.pop_back();
446 // We've finished visiting this node, mark it as such.
447 Explored.insert(V);
448 }
449
450 if (auto *PN = dyn_cast<PHINode>(V)) {
451 // We cannot transform PHIs on unsplittable basic blocks.
452 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
453 return false;
454 Explored.insert(PN);
455 PHIs.insert(PN);
456 }
457 }
458
459 // Explore the PHI nodes further.
460 for (auto *PN : PHIs)
461 for (Value *Op : PN->incoming_values())
462 if (!Explored.contains(Op))
463 WorkList.push_back(Op);
464 }
465
466 // Make sure that we can do this. Since we can't insert GEPs in a basic
467 // block before a PHI node, we can't easily do this transformation if
468 // we have PHI node users of transformed instructions.
469 for (Value *Val : Explored) {
470 for (Value *Use : Val->uses()) {
471
472 auto *PHI = dyn_cast<PHINode>(Use);
473 auto *Inst = dyn_cast<Instruction>(Val);
474
475 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
476 !Explored.contains(PHI))
477 continue;
478
479 if (PHI->getParent() == Inst->getParent())
480 return false;
481 }
482 }
483 return true;
484}
485
486// Sets the appropriate insert point on Builder where we can add
487// a replacement Instruction for V (if that is possible).
488static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
489 bool Before = true) {
490 if (auto *PHI = dyn_cast<PHINode>(V)) {
491 BasicBlock *Parent = PHI->getParent();
492 Builder.SetInsertPoint(Parent->getFirstInsertionPt());
493 return;
494 }
495 if (auto *I = dyn_cast<Instruction>(V)) {
496 if (!Before)
497 I = &*std::next(I->getIterator());
498 Builder.SetInsertPoint(I);
499 return;
500 }
501 if (auto *A = dyn_cast<Argument>(V)) {
502 // Set the insertion point in the entry block.
503 BasicBlock &Entry = A->getParent()->getEntryBlock();
504 Builder.SetInsertPoint(Entry.getFirstInsertionPt());
505 return;
506 }
507 // Otherwise, this is a constant and we don't need to set a new
508 // insertion point.
509 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
510}
511
512/// Returns a re-written value of Start as an indexed GEP using Base as a
513/// pointer.
515 const DataLayout &DL,
516 SetVector<Value *> &Explored,
517 InstCombiner &IC) {
518 // Perform all the substitutions. This is a bit tricky because we can
519 // have cycles in our use-def chains.
520 // 1. Create the PHI nodes without any incoming values.
521 // 2. Create all the other values.
522 // 3. Add the edges for the PHI nodes.
523 // 4. Emit GEPs to get the original pointers.
524 // 5. Remove the original instructions.
525 Type *IndexType = IntegerType::get(
526 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
527
529 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
530
531 // Create the new PHI nodes, without adding any incoming values.
532 for (Value *Val : Explored) {
533 if (Val == Base)
534 continue;
535 // Create empty phi nodes. This avoids cyclic dependencies when creating
536 // the remaining instructions.
537 if (auto *PHI = dyn_cast<PHINode>(Val))
538 NewInsts[PHI] =
539 PHINode::Create(IndexType, PHI->getNumIncomingValues(),
540 PHI->getName() + ".idx", PHI->getIterator());
541 }
542 IRBuilder<> Builder(IC.getModule());
543
544 // Create all the other instructions.
545 for (Value *Val : Explored) {
546 if (NewInsts.contains(Val))
547 continue;
548
549 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
550 setInsertionPoint(Builder, GEP);
551 Value *Op = NewInsts[GEP->getOperand(0)];
552 Value *OffsetV = emitGEPOffset(&Builder, DL, GEP);
554 NewInsts[GEP] = OffsetV;
555 else
556 NewInsts[GEP] = Builder.CreateAdd(
557 Op, OffsetV, GEP->getOperand(0)->getName() + ".add",
558 /*NUW=*/NW.hasNoUnsignedWrap(),
559 /*NSW=*/NW.hasNoUnsignedSignedWrap());
560 continue;
561 }
562 if (isa<PHINode>(Val))
563 continue;
564
565 llvm_unreachable("Unexpected instruction type");
566 }
567
568 // Add the incoming values to the PHI nodes.
569 for (Value *Val : Explored) {
570 if (Val == Base)
571 continue;
572 // All the instructions have been created, we can now add edges to the
573 // phi nodes.
574 if (auto *PHI = dyn_cast<PHINode>(Val)) {
575 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
576 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
577 Value *NewIncoming = PHI->getIncomingValue(I);
578
579 auto It = NewInsts.find(NewIncoming);
580 if (It != NewInsts.end())
581 NewIncoming = It->second;
582
583 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
584 }
585 }
586 }
587
588 for (Value *Val : Explored) {
589 if (Val == Base)
590 continue;
591
592 setInsertionPoint(Builder, Val, false);
593 // Create GEP for external users.
594 Value *NewVal = Builder.CreateGEP(Builder.getInt8Ty(), Base, NewInsts[Val],
595 Val->getName() + ".ptr", NW);
596 IC.replaceInstUsesWith(*cast<Instruction>(Val), NewVal);
597 // Add old instruction to worklist for DCE. We don't directly remove it
598 // here because the original compare is one of the users.
600 }
601
602 return NewInsts[Start];
603}
604
605/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
606/// We can look through PHIs, GEPs and casts in order to determine a common base
607/// between GEPLHS and RHS.
610 const DataLayout &DL,
611 InstCombiner &IC) {
612 // FIXME: Support vector of pointers.
613 if (GEPLHS->getType()->isVectorTy())
614 return nullptr;
615
616 if (!GEPLHS->hasAllConstantIndices())
617 return nullptr;
618
619 APInt Offset(DL.getIndexTypeSizeInBits(GEPLHS->getType()), 0);
620 Value *PtrBase =
622 /*AllowNonInbounds*/ false);
623
624 // Bail if we looked through addrspacecast.
625 if (PtrBase->getType() != GEPLHS->getType())
626 return nullptr;
627
628 // The set of nodes that will take part in this transformation.
629 SetVector<Value *> Nodes;
630 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags();
631 if (!canRewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes))
632 return nullptr;
633
634 // We know we can re-write this as
635 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
636 // Since we've only looked through inbouds GEPs we know that we
637 // can't have overflow on either side. We can therefore re-write
638 // this as:
639 // OFFSET1 cmp OFFSET2
640 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes, IC);
641
642 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
643 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
644 // offset. Since Index is the offset of LHS to the base pointer, we will now
645 // compare the offsets instead of comparing the pointers.
647 IC.Builder.getInt(Offset), NewRHS);
648}
649
650/// Fold comparisons between a GEP instruction and something else. At this point
651/// we know that the GEP is on the LHS of the comparison.
654 // Don't transform signed compares of GEPs into index compares. Even if the
655 // GEP is inbounds, the final add of the base pointer can have signed overflow
656 // and would change the result of the icmp.
657 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
658 // the maximum signed value for the pointer type.
660 return nullptr;
661
662 // Look through bitcasts and addrspacecasts. We do not however want to remove
663 // 0 GEPs.
664 if (!isa<GetElementPtrInst>(RHS))
665 RHS = RHS->stripPointerCasts();
666
667 auto CanFold = [Cond](GEPNoWrapFlags NW) {
669 return true;
670
671 // Unsigned predicates can be folded if the GEPs have *any* nowrap flags.
673 return NW != GEPNoWrapFlags::none();
674 };
675
676 auto NewICmp = [Cond](GEPNoWrapFlags NW, Value *Op1, Value *Op2) {
677 if (!NW.hasNoUnsignedWrap()) {
678 // Convert signed to unsigned comparison.
679 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Op1, Op2);
680 }
681
682 auto *I = new ICmpInst(Cond, Op1, Op2);
683 I->setSameSign(NW.hasNoUnsignedSignedWrap());
684 return I;
685 };
686
688 if (Base.Ptr == RHS && CanFold(Base.LHSNW) && !Base.isExpensive()) {
689 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
690 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
691 Value *Offset =
692 EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy, /*RewriteGEPs=*/true);
693 return NewICmp(Base.LHSNW, Offset,
694 Constant::getNullValue(Offset->getType()));
695 }
696
697 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
699 !NullPointerIsDefined(I.getFunction(),
700 RHS->getType()->getPointerAddressSpace())) {
701 // For most address spaces, an allocation can't be placed at null, but null
702 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
703 // the only valid inbounds address derived from null, is null itself.
704 // Thus, we have four cases to consider:
705 // 1) Base == nullptr, Offset == 0 -> inbounds, null
706 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
707 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
708 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
709 //
710 // (Note if we're indexing a type of size 0, that simply collapses into one
711 // of the buckets above.)
712 //
713 // In general, we're allowed to make values less poison (i.e. remove
714 // sources of full UB), so in this case, we just select between the two
715 // non-poison cases (1 and 4 above).
716 //
717 // For vectors, we apply the same reasoning on a per-lane basis.
718 auto *Base = GEPLHS->getPointerOperand();
719 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
720 auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
721 Base = Builder.CreateVectorSplat(EC, Base);
722 }
723 return new ICmpInst(Cond, Base,
725 cast<Constant>(RHS), Base->getType()));
726 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
727 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags() & GEPRHS->getNoWrapFlags();
728
729 // If the base pointers are different, but the indices are the same, just
730 // compare the base pointer.
731 if (GEPLHS->getOperand(0) != GEPRHS->getOperand(0)) {
732 bool IndicesTheSame =
733 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
734 GEPLHS->getPointerOperand()->getType() ==
735 GEPRHS->getPointerOperand()->getType() &&
736 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
737 if (IndicesTheSame)
738 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
739 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
740 IndicesTheSame = false;
741 break;
742 }
743
744 // If all indices are the same, just compare the base pointers.
745 Type *BaseType = GEPLHS->getOperand(0)->getType();
746 if (IndicesTheSame &&
747 CmpInst::makeCmpResultType(BaseType) == I.getType() && CanFold(NW))
748 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
749
750 // If we're comparing GEPs with two base pointers that only differ in type
751 // and both GEPs have only constant indices or just one use, then fold
752 // the compare with the adjusted indices.
753 // FIXME: Support vector of pointers.
754 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
755 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
756 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
757 GEPLHS->getOperand(0)->stripPointerCasts() ==
758 GEPRHS->getOperand(0)->stripPointerCasts() &&
759 !GEPLHS->getType()->isVectorTy()) {
760 Value *LOffset = EmitGEPOffset(GEPLHS);
761 Value *ROffset = EmitGEPOffset(GEPRHS);
762
763 // If we looked through an addrspacecast between different sized address
764 // spaces, the LHS and RHS pointers are different sized
765 // integers. Truncate to the smaller one.
766 Type *LHSIndexTy = LOffset->getType();
767 Type *RHSIndexTy = ROffset->getType();
768 if (LHSIndexTy != RHSIndexTy) {
769 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
770 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
771 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
772 } else
773 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
774 }
775
777 LOffset, ROffset);
778 return replaceInstUsesWith(I, Cmp);
779 }
780 }
781
782 if (GEPLHS->getOperand(0) == GEPRHS->getOperand(0) &&
783 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
784 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
785 // If the GEPs only differ by one index, compare it.
786 unsigned NumDifferences = 0; // Keep track of # differences.
787 unsigned DiffOperand = 0; // The operand that differs.
788 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
789 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
790 Type *LHSType = GEPLHS->getOperand(i)->getType();
791 Type *RHSType = GEPRHS->getOperand(i)->getType();
792 // FIXME: Better support for vector of pointers.
793 if (LHSType->getPrimitiveSizeInBits() !=
794 RHSType->getPrimitiveSizeInBits() ||
795 (GEPLHS->getType()->isVectorTy() &&
796 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
797 // Irreconcilable differences.
798 NumDifferences = 2;
799 break;
800 }
801
802 if (NumDifferences++)
803 break;
804 DiffOperand = i;
805 }
806
807 if (NumDifferences == 0) // SAME GEP?
808 return replaceInstUsesWith(
809 I, // No comparison is needed here.
810 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
811 // If two GEPs only differ by an index, compare them.
812 // Note that nowrap flags are always needed when comparing two indices.
813 else if (NumDifferences == 1 && NW != GEPNoWrapFlags::none()) {
814 Value *LHSV = GEPLHS->getOperand(DiffOperand);
815 Value *RHSV = GEPRHS->getOperand(DiffOperand);
816 return NewICmp(NW, LHSV, RHSV);
817 }
818 }
819
820 if (Base.Ptr && !Base.isExpensive()) {
821 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
822 bool DoFold = CanFold(Base.LHSNW & Base.RHSNW);
823
824 if (!DoFold && Base.Ptr->getType()->isPointerTy()) {
825 // Without the flags, we can still fold if the offsets are constant and
826 // they cross the base's alignment boundary the same number of times, so
827 // either both arguments will wrap, or none of them will.
828 unsigned BW = DL.getIndexTypeSizeInBits(GEPLHS->getType());
829 APInt Alignment = APInt(BW, Base.Ptr->getPointerAlignment(DL).value());
830 APInt LOff(BW, 0);
831 APInt ROff(BW, 0);
833 DL, LOff, /*AllowNonInbounds=*/true) == Base.Ptr &&
834 RHS->stripAndAccumulateConstantOffsets(
835 DL, ROff, /*AllowNonInbounds=*/true) == Base.Ptr)
836 DoFold =
839 }
840
841 if (DoFold) {
842 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
843 Value *L = EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy,
844 /*RewriteGEP=*/true);
845 Value *R = EmitGEPOffsets(Base.RHSGEPs, Base.RHSNW, IdxTy,
846 /*RewriteGEP=*/true);
847 return NewICmp(Base.LHSNW & Base.RHSNW, L, R);
848 }
849 }
850 }
851
852 // Try convert this to an indexed compare by looking through PHIs/casts as a
853 // last resort.
854 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
855}
856
858 // It would be tempting to fold away comparisons between allocas and any
859 // pointer not based on that alloca (e.g. an argument). However, even
860 // though such pointers cannot alias, they can still compare equal.
861 //
862 // But LLVM doesn't specify where allocas get their memory, so if the alloca
863 // doesn't escape we can argue that it's impossible to guess its value, and we
864 // can therefore act as if any such guesses are wrong.
865 //
866 // However, we need to ensure that this folding is consistent: We can't fold
867 // one comparison to false, and then leave a different comparison against the
868 // same value alone (as it might evaluate to true at runtime, leading to a
869 // contradiction). As such, this code ensures that all comparisons are folded
870 // at the same time, and there are no other escapes.
871
872 struct CmpCaptureTracker : public CaptureTracker {
873 AllocaInst *Alloca;
874 bool Captured = false;
875 /// The value of the map is a bit mask of which icmp operands the alloca is
876 /// used in.
878
879 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
880
881 void tooManyUses() override { Captured = true; }
882
883 Action captured(const Use *U, UseCaptureInfo CI) override {
884 // TODO(captures): Use UseCaptureInfo.
885 auto *ICmp = dyn_cast<ICmpInst>(U->getUser());
886 // We need to check that U is based *only* on the alloca, and doesn't
887 // have other contributions from a select/phi operand.
888 // TODO: We could check whether getUnderlyingObjects() reduces to one
889 // object, which would allow looking through phi nodes.
890 if (ICmp && ICmp->isEquality() && getUnderlyingObject(*U) == Alloca) {
891 // Collect equality icmps of the alloca, and don't treat them as
892 // captures.
893 ICmps[ICmp] |= 1u << U->getOperandNo();
894 return Continue;
895 }
896
897 Captured = true;
898 return Stop;
899 }
900 };
901
902 CmpCaptureTracker Tracker(Alloca);
903 PointerMayBeCaptured(Alloca, &Tracker);
904 if (Tracker.Captured)
905 return false;
906
907 bool Changed = false;
908 for (auto [ICmp, Operands] : Tracker.ICmps) {
909 switch (Operands) {
910 case 1:
911 case 2: {
912 // The alloca is only used in one icmp operand. Assume that the
913 // equality is false.
914 auto *Res = ConstantInt::get(ICmp->getType(),
915 ICmp->getPredicate() == ICmpInst::ICMP_NE);
916 replaceInstUsesWith(*ICmp, Res);
918 Changed = true;
919 break;
920 }
921 case 3:
922 // Both icmp operands are based on the alloca, so this is comparing
923 // pointer offsets, without leaking any information about the address
924 // of the alloca. Ignore such comparisons.
925 break;
926 default:
927 llvm_unreachable("Cannot happen");
928 }
929 }
930
931 return Changed;
932}
933
934/// Fold "icmp pred (X+C), X".
936 CmpPredicate Pred) {
937 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
938 // so the values can never be equal. Similarly for all other "or equals"
939 // operators.
940 assert(!!C && "C should not be zero!");
941
942 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
943 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
944 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
945 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
946 Constant *R =
947 ConstantInt::get(X->getType(), APInt::getMaxValue(C.getBitWidth()) - C);
948 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
949 }
950
951 // (X+1) >u X --> X <u (0-1) --> X != 255
952 // (X+2) >u X --> X <u (0-2) --> X <u 254
953 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
954 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
955 return new ICmpInst(ICmpInst::ICMP_ULT, X,
956 ConstantInt::get(X->getType(), -C));
957
958 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
959
960 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
961 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
962 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
963 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
964 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
965 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
966 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
967 return new ICmpInst(ICmpInst::ICMP_SGT, X,
968 ConstantInt::get(X->getType(), SMax - C));
969
970 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
971 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
972 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
973 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
974 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
975 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
976
977 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
978 return new ICmpInst(ICmpInst::ICMP_SLT, X,
979 ConstantInt::get(X->getType(), SMax - (C - 1)));
980}
981
982/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
983/// (icmp eq/ne A, Log2(AP2/AP1)) ->
984/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
986 const APInt &AP1,
987 const APInt &AP2) {
988 assert(I.isEquality() && "Cannot fold icmp gt/lt");
989
990 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
991 if (I.getPredicate() == I.ICMP_NE)
992 Pred = CmpInst::getInversePredicate(Pred);
993 return new ICmpInst(Pred, LHS, RHS);
994 };
995
996 // Don't bother doing any work for cases which InstSimplify handles.
997 if (AP2.isZero())
998 return nullptr;
999
1000 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
1001 if (IsAShr) {
1002 if (AP2.isAllOnes())
1003 return nullptr;
1004 if (AP2.isNegative() != AP1.isNegative())
1005 return nullptr;
1006 if (AP2.sgt(AP1))
1007 return nullptr;
1008 }
1009
1010 if (!AP1)
1011 // 'A' must be large enough to shift out the highest set bit.
1012 return getICmp(I.ICMP_UGT, A,
1013 ConstantInt::get(A->getType(), AP2.logBase2()));
1014
1015 if (AP1 == AP2)
1016 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1017
1018 int Shift;
1019 if (IsAShr && AP1.isNegative())
1020 Shift = AP1.countl_one() - AP2.countl_one();
1021 else
1022 Shift = AP1.countl_zero() - AP2.countl_zero();
1023
1024 if (Shift > 0) {
1025 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1026 // There are multiple solutions if we are comparing against -1 and the LHS
1027 // of the ashr is not a power of two.
1028 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1029 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1030 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1031 } else if (AP1 == AP2.lshr(Shift)) {
1032 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1033 }
1034 }
1035
1036 // Shifting const2 will never be equal to const1.
1037 // FIXME: This should always be handled by InstSimplify?
1038 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1039 return replaceInstUsesWith(I, TorF);
1040}
1041
1042/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1043/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1045 const APInt &AP1,
1046 const APInt &AP2) {
1047 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1048
1049 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1050 if (I.getPredicate() == I.ICMP_NE)
1051 Pred = CmpInst::getInversePredicate(Pred);
1052 return new ICmpInst(Pred, LHS, RHS);
1053 };
1054
1055 // Don't bother doing any work for cases which InstSimplify handles.
1056 if (AP2.isZero())
1057 return nullptr;
1058
1059 unsigned AP2TrailingZeros = AP2.countr_zero();
1060
1061 if (!AP1 && AP2TrailingZeros != 0)
1062 return getICmp(
1063 I.ICMP_UGE, A,
1064 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1065
1066 if (AP1 == AP2)
1067 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1068
1069 // Get the distance between the lowest bits that are set.
1070 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1071
1072 if (Shift > 0 && AP2.shl(Shift) == AP1)
1073 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1074
1075 // Shifting const2 will never be equal to const1.
1076 // FIXME: This should always be handled by InstSimplify?
1077 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1078 return replaceInstUsesWith(I, TorF);
1079}
1080
1081/// The caller has matched a pattern of the form:
1082/// I = icmp ugt (add (add A, B), CI2), CI1
1083/// If this is of the form:
1084/// sum = a + b
1085/// if (sum+128 >u 255)
1086/// Then replace it with llvm.sadd.with.overflow.i8.
1087///
1089 ConstantInt *CI2, ConstantInt *CI1,
1090 InstCombinerImpl &IC) {
1091 // The transformation we're trying to do here is to transform this into an
1092 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1093 // with a narrower add, and discard the add-with-constant that is part of the
1094 // range check (if we can't eliminate it, this isn't profitable).
1095
1096 // In order to eliminate the add-with-constant, the compare can be its only
1097 // use.
1098 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1099 if (!AddWithCst->hasOneUse())
1100 return nullptr;
1101
1102 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1103 if (!CI2->getValue().isPowerOf2())
1104 return nullptr;
1105 unsigned NewWidth = CI2->getValue().countr_zero();
1106 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1107 return nullptr;
1108
1109 // The width of the new add formed is 1 more than the bias.
1110 ++NewWidth;
1111
1112 // Check to see that CI1 is an all-ones value with NewWidth bits.
1113 if (CI1->getBitWidth() == NewWidth ||
1114 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1115 return nullptr;
1116
1117 // This is only really a signed overflow check if the inputs have been
1118 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1119 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1120 if (IC.ComputeMaxSignificantBits(A, &I) > NewWidth ||
1121 IC.ComputeMaxSignificantBits(B, &I) > NewWidth)
1122 return nullptr;
1123
1124 // In order to replace the original add with a narrower
1125 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1126 // and truncates that discard the high bits of the add. Verify that this is
1127 // the case.
1128 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1129 for (User *U : OrigAdd->users()) {
1130 if (U == AddWithCst)
1131 continue;
1132
1133 // Only accept truncates for now. We would really like a nice recursive
1134 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1135 // chain to see which bits of a value are actually demanded. If the
1136 // original add had another add which was then immediately truncated, we
1137 // could still do the transformation.
1139 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1140 return nullptr;
1141 }
1142
1143 // If the pattern matches, truncate the inputs to the narrower type and
1144 // use the sadd_with_overflow intrinsic to efficiently compute both the
1145 // result and the overflow bit.
1146 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1148 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1149
1150 InstCombiner::BuilderTy &Builder = IC.Builder;
1151
1152 // Put the new code above the original add, in case there are any uses of the
1153 // add between the add and the compare.
1154 Builder.SetInsertPoint(OrigAdd);
1155
1156 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1157 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1158 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1159 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1160 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1161
1162 // The inner add was the result of the narrow add, zero extended to the
1163 // wider type. Replace it with the result computed by the intrinsic.
1164 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1165 IC.eraseInstFromFunction(*OrigAdd);
1166
1167 // The original icmp gets replaced with the overflow value.
1168 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1169}
1170
1171/// If we have:
1172/// icmp eq/ne (urem/srem %x, %y), 0
1173/// iff %y is a power-of-two, we can replace this with a bit test:
1174/// icmp eq/ne (and %x, (add %y, -1)), 0
1176 // This fold is only valid for equality predicates.
1177 if (!I.isEquality())
1178 return nullptr;
1179 CmpPredicate Pred;
1180 Value *X, *Y, *Zero;
1181 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1182 m_CombineAnd(m_Zero(), m_Value(Zero)))))
1183 return nullptr;
1184 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, &I))
1185 return nullptr;
1186 // This may increase instruction count, we don't enforce that Y is a constant.
1187 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1188 Value *Masked = Builder.CreateAnd(X, Mask);
1189 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1190}
1191
1192/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1193/// by one-less-than-bitwidth into a sign test on the original value.
1195 Instruction *Val;
1196 CmpPredicate Pred;
1197 if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1198 return nullptr;
1199
1200 Value *X;
1201 Type *XTy;
1202
1203 Constant *C;
1204 if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1205 XTy = X->getType();
1206 unsigned XBitWidth = XTy->getScalarSizeInBits();
1208 APInt(XBitWidth, XBitWidth - 1))))
1209 return nullptr;
1210 } else if (isa<BinaryOperator>(Val) &&
1212 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1213 /*AnalyzeForSignBitExtraction=*/true))) {
1214 XTy = X->getType();
1215 } else
1216 return nullptr;
1217
1218 return ICmpInst::Create(Instruction::ICmp,
1222}
1223
1224// Handle icmp pred X, 0
1226 CmpInst::Predicate Pred = Cmp.getPredicate();
1227 if (!match(Cmp.getOperand(1), m_Zero()))
1228 return nullptr;
1229
1230 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1231 if (Pred == ICmpInst::ICMP_SGT) {
1232 Value *A, *B;
1233 if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1234 if (isKnownPositive(A, SQ.getWithInstruction(&Cmp)))
1235 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1236 if (isKnownPositive(B, SQ.getWithInstruction(&Cmp)))
1237 return new ICmpInst(Pred, A, Cmp.getOperand(1));
1238 }
1239 }
1240
1242 return New;
1243
1244 // Given:
1245 // icmp eq/ne (urem %x, %y), 0
1246 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1247 // icmp eq/ne %x, 0
1248 Value *X, *Y;
1249 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1250 ICmpInst::isEquality(Pred)) {
1251 KnownBits XKnown = computeKnownBits(X, &Cmp);
1252 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1253 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1254 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1255 }
1256
1257 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1258 // odd/non-zero/there is no overflow.
1259 if (match(Cmp.getOperand(0), m_Mul(m_Value(X), m_Value(Y))) &&
1260 ICmpInst::isEquality(Pred)) {
1261
1262 KnownBits XKnown = computeKnownBits(X, &Cmp);
1263 // if X % 2 != 0
1264 // (icmp eq/ne Y)
1265 if (XKnown.countMaxTrailingZeros() == 0)
1266 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1267
1268 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1269 // if Y % 2 != 0
1270 // (icmp eq/ne X)
1271 if (YKnown.countMaxTrailingZeros() == 0)
1272 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1273
1274 auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1275 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1276 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
1277 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1278 // but to avoid unnecessary work, first just if this is an obvious case.
1279
1280 // if X non-zero and NoOverflow(X * Y)
1281 // (icmp eq/ne Y)
1282 if (!XKnown.One.isZero() || isKnownNonZero(X, Q))
1283 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1284
1285 // if Y non-zero and NoOverflow(X * Y)
1286 // (icmp eq/ne X)
1287 if (!YKnown.One.isZero() || isKnownNonZero(Y, Q))
1288 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1289 }
1290 // Note, we are skipping cases:
1291 // if Y % 2 != 0 AND X % 2 != 0
1292 // (false/true)
1293 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1294 // (false/true)
1295 // Those can be simplified later as we would have already replaced the (icmp
1296 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1297 // will fold to a constant elsewhere.
1298 }
1299
1300 // (icmp eq/ne f(X), 0) -> (icmp eq/ne X, 0)
1301 // where f(X) == 0 if and only if X == 0
1302 if (ICmpInst::isEquality(Pred))
1303 if (Value *Stripped = stripNullTest(Cmp.getOperand(0)))
1304 return new ICmpInst(Pred, Stripped,
1305 Constant::getNullValue(Stripped->getType()));
1306
1307 return nullptr;
1308}
1309
1310/// Fold icmp eq (num + mask) & ~mask, num
1311/// to
1312/// icmp eq (and num, mask), 0
1313/// Where mask is a low bit mask.
1315 Value *Num;
1316 CmpPredicate Pred;
1317 const APInt *Mask, *Neg;
1318
1319 if (!match(&Cmp,
1320 m_c_ICmp(Pred, m_Value(Num),
1322 m_LowBitMask(Mask))),
1323 m_APInt(Neg))))))
1324 return nullptr;
1325
1326 if (*Neg != ~*Mask)
1327 return nullptr;
1328
1329 if (!ICmpInst::isEquality(Pred))
1330 return nullptr;
1331
1332 // Create new icmp eq (num & mask), 0
1333 auto *NewAnd = Builder.CreateAnd(Num, *Mask);
1334 auto *Zero = Constant::getNullValue(Num->getType());
1335
1336 return new ICmpInst(Pred, NewAnd, Zero);
1337}
1338
1339/// Fold icmp Pred X, C.
1340/// TODO: This code structure does not make sense. The saturating add fold
1341/// should be moved to some other helper and extended as noted below (it is also
1342/// possible that code has been made unnecessary - do we canonicalize IR to
1343/// overflow/saturating intrinsics or not?).
1345 // Match the following pattern, which is a common idiom when writing
1346 // overflow-safe integer arithmetic functions. The source performs an addition
1347 // in wider type and explicitly checks for overflow using comparisons against
1348 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1349 //
1350 // TODO: This could probably be generalized to handle other overflow-safe
1351 // operations if we worked out the formulas to compute the appropriate magic
1352 // constants.
1353 //
1354 // sum = a + b
1355 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1356 CmpInst::Predicate Pred = Cmp.getPredicate();
1357 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1358 Value *A, *B;
1359 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1360 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1361 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1362 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1363 return Res;
1364
1365 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1367 if (!C)
1368 return nullptr;
1369
1370 if (auto *Phi = dyn_cast<PHINode>(Op0))
1371 if (all_of(Phi->operands(), IsaPred<Constant>)) {
1373 for (Value *V : Phi->incoming_values()) {
1374 Constant *Res =
1376 if (!Res)
1377 return nullptr;
1378 Ops.push_back(Res);
1379 }
1380 Builder.SetInsertPoint(Phi);
1381 PHINode *NewPhi = Builder.CreatePHI(Cmp.getType(), Phi->getNumOperands());
1382 for (auto [V, Pred] : zip(Ops, Phi->blocks()))
1383 NewPhi->addIncoming(V, Pred);
1384 return replaceInstUsesWith(Cmp, NewPhi);
1385 }
1386
1388 return R;
1389
1390 return nullptr;
1391}
1392
1393/// Canonicalize icmp instructions based on dominating conditions.
1395 // We already checked simple implication in InstSimplify, only handle complex
1396 // cases here.
1397 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1398 const APInt *C;
1399 if (!match(Y, m_APInt(C)))
1400 return nullptr;
1401
1402 CmpInst::Predicate Pred = Cmp.getPredicate();
1404
1405 auto handleDomCond = [&](ICmpInst::Predicate DomPred,
1406 const APInt *DomC) -> Instruction * {
1407 // We have 2 compares of a variable with constants. Calculate the constant
1408 // ranges of those compares to see if we can transform the 2nd compare:
1409 // DomBB:
1410 // DomCond = icmp DomPred X, DomC
1411 // br DomCond, CmpBB, FalseBB
1412 // CmpBB:
1413 // Cmp = icmp Pred X, C
1414 ConstantRange DominatingCR =
1415 ConstantRange::makeExactICmpRegion(DomPred, *DomC);
1416 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1417 ConstantRange Difference = DominatingCR.difference(CR);
1418 if (Intersection.isEmptySet())
1419 return replaceInstUsesWith(Cmp, Builder.getFalse());
1420 if (Difference.isEmptySet())
1421 return replaceInstUsesWith(Cmp, Builder.getTrue());
1422
1423 // Canonicalizing a sign bit comparison that gets used in a branch,
1424 // pessimizes codegen by generating branch on zero instruction instead
1425 // of a test and branch. So we avoid canonicalizing in such situations
1426 // because test and branch instruction has better branch displacement
1427 // than compare and branch instruction.
1428 bool UnusedBit;
1429 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1430 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1431 return nullptr;
1432
1433 // Avoid an infinite loop with min/max canonicalization.
1434 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1435 if (Cmp.hasOneUse() &&
1436 match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1437 return nullptr;
1438
1439 if (const APInt *EqC = Intersection.getSingleElement())
1440 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1441 if (const APInt *NeC = Difference.getSingleElement())
1442 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1443 return nullptr;
1444 };
1445
1446 for (CondBrInst *BI : DC.conditionsFor(X)) {
1447 CmpPredicate DomPred;
1448 const APInt *DomC;
1449 if (!match(BI->getCondition(),
1450 m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))))
1451 continue;
1452
1453 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1454 if (DT.dominates(Edge0, Cmp.getParent())) {
1455 if (auto *V = handleDomCond(DomPred, DomC))
1456 return V;
1457 } else {
1458 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1459 if (DT.dominates(Edge1, Cmp.getParent()))
1460 if (auto *V =
1461 handleDomCond(CmpInst::getInversePredicate(DomPred), DomC))
1462 return V;
1463 }
1464 }
1465
1466 return nullptr;
1467}
1468
1469/// Fold icmp (trunc X), C.
1471 TruncInst *Trunc,
1472 const APInt &C) {
1473 ICmpInst::Predicate Pred = Cmp.getPredicate();
1474 Value *X = Trunc->getOperand(0);
1475 Type *SrcTy = X->getType();
1476 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1477 SrcBits = SrcTy->getScalarSizeInBits();
1478
1479 // Match (icmp pred (trunc nuw/nsw X), C)
1480 // Which we can convert to (icmp pred X, (sext/zext C))
1481 if (shouldChangeType(Trunc->getType(), SrcTy)) {
1482 if (Trunc->hasNoSignedWrap())
1483 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.sext(SrcBits)));
1484 if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())
1485 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.zext(SrcBits)));
1486 }
1487
1488 if (C.isOne() && C.getBitWidth() > 1) {
1489 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1490 Value *V = nullptr;
1491 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1492 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1493 ConstantInt::get(V->getType(), 1));
1494 }
1495
1496 // TODO: Handle non-equality predicates.
1497 Value *Y;
1498 const APInt *Pow2;
1499 if (Cmp.isEquality() && match(X, m_Shl(m_Power2(Pow2), m_Value(Y))) &&
1500 DstBits > Pow2->logBase2()) {
1501 // (trunc (Pow2 << Y) to iN) == 0 --> Y u>= N - log2(Pow2)
1502 // (trunc (Pow2 << Y) to iN) != 0 --> Y u< N - log2(Pow2)
1503 // iff N > log2(Pow2)
1504 if (C.isZero()) {
1505 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1506 return new ICmpInst(NewPred, Y,
1507 ConstantInt::get(SrcTy, DstBits - Pow2->logBase2()));
1508 }
1509 // (trunc (Pow2 << Y) to iN) == 2**C --> Y == C - log2(Pow2)
1510 // (trunc (Pow2 << Y) to iN) != 2**C --> Y != C - log2(Pow2)
1511 if (C.isPowerOf2())
1512 return new ICmpInst(
1513 Pred, Y, ConstantInt::get(SrcTy, C.logBase2() - Pow2->logBase2()));
1514 }
1515
1516 if (Cmp.isEquality() && (Trunc->hasOneUse() || Trunc->hasNoUnsignedWrap())) {
1517 // Canonicalize to a mask and wider compare if the wide type is suitable:
1518 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1519 if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1520 Constant *Mask =
1521 ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1522 Value *And = Trunc->hasNoUnsignedWrap() ? X : Builder.CreateAnd(X, Mask);
1523 Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1524 return new ICmpInst(Pred, And, WideC);
1525 }
1526
1527 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1528 // of the high bits truncated out of x are known.
1530
1531 // If all the high bits are known, we can do this xform.
1532 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1533 // Pull in the high bits from known-ones set.
1534 APInt NewRHS = C.zext(SrcBits);
1535 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1536 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1537 }
1538 }
1539
1540 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1541 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1542 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1543 Value *ShOp;
1544 uint64_t ShAmt;
1545 bool TrueIfSigned;
1546 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1547 match(X, m_Shr(m_Value(ShOp), m_ConstantInt(ShAmt))) &&
1548 DstBits == SrcBits - ShAmt) {
1549 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1551 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1553 }
1554
1555 return nullptr;
1556}
1557
1558/// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
1559/// Fold icmp (trunc nuw/nsw X), (zext/sext Y).
1562 const SimplifyQuery &Q) {
1563 Value *X, *Y;
1564 CmpPredicate Pred;
1565 bool YIsSExt = false;
1566 // Try to match icmp (trunc X), (trunc Y)
1567 if (match(&Cmp, m_ICmp(Pred, m_Trunc(m_Value(X)), m_Trunc(m_Value(Y))))) {
1568 unsigned NoWrapFlags = cast<TruncInst>(Cmp.getOperand(0))->getNoWrapKind() &
1569 cast<TruncInst>(Cmp.getOperand(1))->getNoWrapKind();
1570 if (Cmp.isSigned()) {
1571 // For signed comparisons, both truncs must be nsw.
1572 if (!(NoWrapFlags & TruncInst::NoSignedWrap))
1573 return nullptr;
1574 } else {
1575 // For unsigned and equality comparisons, either both must be nuw or
1576 // both must be nsw, we don't care which.
1577 if (!NoWrapFlags)
1578 return nullptr;
1579 }
1580
1581 if (X->getType() != Y->getType() &&
1582 (!Cmp.getOperand(0)->hasOneUse() || !Cmp.getOperand(1)->hasOneUse()))
1583 return nullptr;
1584 if (!isDesirableIntType(X->getType()->getScalarSizeInBits()) &&
1585 isDesirableIntType(Y->getType()->getScalarSizeInBits())) {
1586 std::swap(X, Y);
1587 Pred = Cmp.getSwappedPredicate(Pred);
1588 }
1589 YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);
1590 }
1591 // Try to match icmp (trunc nuw X), (zext Y)
1592 else if (!Cmp.isSigned() &&
1593 match(&Cmp, m_c_ICmp(Pred, m_NUWTrunc(m_Value(X)),
1594 m_OneUse(m_ZExt(m_Value(Y)))))) {
1595 // Can fold trunc nuw + zext for unsigned and equality predicates.
1596 }
1597 // Try to match icmp (trunc nsw X), (sext Y)
1598 else if (match(&Cmp, m_c_ICmp(Pred, m_NSWTrunc(m_Value(X)),
1600 // Can fold trunc nsw + zext/sext for all predicates.
1601 YIsSExt =
1602 isa<SExtInst>(Cmp.getOperand(0)) || isa<SExtInst>(Cmp.getOperand(1));
1603 } else
1604 return nullptr;
1605
1606 Type *TruncTy = Cmp.getOperand(0)->getType();
1607 unsigned TruncBits = TruncTy->getScalarSizeInBits();
1608
1609 // If this transform will end up changing from desirable types -> undesirable
1610 // types skip it.
1611 if (isDesirableIntType(TruncBits) &&
1612 !isDesirableIntType(X->getType()->getScalarSizeInBits()))
1613 return nullptr;
1614
1615 Value *NewY = Builder.CreateIntCast(Y, X->getType(), YIsSExt);
1616 return new ICmpInst(Pred, X, NewY);
1617}
1618
1619/// Fold icmp (xor X, Y), C.
1622 const APInt &C) {
1623 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1624 return I;
1625
1626 Value *X = Xor->getOperand(0);
1627 Value *Y = Xor->getOperand(1);
1628 const APInt *XorC;
1629 if (!match(Y, m_APInt(XorC)))
1630 return nullptr;
1631
1632 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1633 // fold the xor.
1634 ICmpInst::Predicate Pred = Cmp.getPredicate();
1635 bool TrueIfSigned = false;
1636 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1637
1638 // If the sign bit of the XorCst is not set, there is no change to
1639 // the operation, just stop using the Xor.
1640 if (!XorC->isNegative())
1641 return replaceOperand(Cmp, 0, X);
1642
1643 // Emit the opposite comparison.
1644 if (TrueIfSigned)
1645 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1646 ConstantInt::getAllOnesValue(X->getType()));
1647 else
1648 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1649 ConstantInt::getNullValue(X->getType()));
1650 }
1651
1652 if (Xor->hasOneUse()) {
1653 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1654 if (!Cmp.isEquality() && XorC->isSignMask()) {
1655 Pred = Cmp.getFlippedSignednessPredicate();
1656 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1657 }
1658
1659 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1660 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1661 Pred = Cmp.getFlippedSignednessPredicate();
1662 Pred = Cmp.getSwappedPredicate(Pred);
1663 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1664 }
1665 }
1666
1667 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1668 if (Pred == ICmpInst::ICMP_UGT) {
1669 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1670 if (*XorC == ~C && (C + 1).isPowerOf2())
1671 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1672 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1673 if (*XorC == C && (C + 1).isPowerOf2())
1674 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1675 }
1676 if (Pred == ICmpInst::ICMP_ULT) {
1677 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1678 if (*XorC == -C && C.isPowerOf2())
1679 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1680 ConstantInt::get(X->getType(), ~C));
1681 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1682 if (*XorC == C && (-C).isPowerOf2())
1683 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1684 ConstantInt::get(X->getType(), ~C));
1685 }
1686 return nullptr;
1687}
1688
1689/// For power-of-2 C:
1690/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1691/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1694 const APInt &C) {
1695 CmpInst::Predicate Pred = Cmp.getPredicate();
1696 APInt PowerOf2;
1697 if (Pred == ICmpInst::ICMP_ULT)
1698 PowerOf2 = C;
1699 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1700 PowerOf2 = C + 1;
1701 else
1702 return nullptr;
1703 if (!PowerOf2.isPowerOf2())
1704 return nullptr;
1705 Value *X;
1706 const APInt *ShiftC;
1708 m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1709 return nullptr;
1710 uint64_t Shift = ShiftC->getLimitedValue();
1711 Type *XType = X->getType();
1712 if (Shift == 0 || PowerOf2.isMinSignedValue())
1713 return nullptr;
1714 Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1715 APInt Bound =
1716 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1717 return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1718}
1719
1720/// Fold icmp (and (sh X, Y), C2), C1.
1723 const APInt &C1,
1724 const APInt &C2) {
1725 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1726 if (!Shift || !Shift->isShift())
1727 return nullptr;
1728
1729 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1730 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1731 // code produced by the clang front-end, for bitfield access.
1732 // This seemingly simple opportunity to fold away a shift turns out to be
1733 // rather complicated. See PR17827 for details.
1734 unsigned ShiftOpcode = Shift->getOpcode();
1735 bool IsShl = ShiftOpcode == Instruction::Shl;
1736 const APInt *C3;
1737 if (match(Shift->getOperand(1), m_APInt(C3))) {
1738 APInt NewAndCst, NewCmpCst;
1739 bool AnyCmpCstBitsShiftedOut;
1740 if (ShiftOpcode == Instruction::Shl) {
1741 // For a left shift, we can fold if the comparison is not signed. We can
1742 // also fold a signed comparison if the mask value and comparison value
1743 // are not negative. These constraints may not be obvious, but we can
1744 // prove that they are correct using an SMT solver.
1745 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1746 return nullptr;
1747
1748 NewCmpCst = C1.lshr(*C3);
1749 NewAndCst = C2.lshr(*C3);
1750 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1751 } else if (ShiftOpcode == Instruction::LShr) {
1752 // For a logical right shift, we can fold if the comparison is not signed.
1753 // We can also fold a signed comparison if the shifted mask value and the
1754 // shifted comparison value are not negative. These constraints may not be
1755 // obvious, but we can prove that they are correct using an SMT solver.
1756 NewCmpCst = C1.shl(*C3);
1757 NewAndCst = C2.shl(*C3);
1758 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1759 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1760 return nullptr;
1761 } else {
1762 // For an arithmetic shift, check that both constants don't use (in a
1763 // signed sense) the top bits being shifted out.
1764 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1765 NewCmpCst = C1.shl(*C3);
1766 NewAndCst = C2.shl(*C3);
1767 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1768 if (NewAndCst.ashr(*C3) != C2)
1769 return nullptr;
1770 }
1771
1772 if (AnyCmpCstBitsShiftedOut) {
1773 // If we shifted bits out, the fold is not going to work out. As a
1774 // special case, check to see if this means that the result is always
1775 // true or false now.
1776 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1777 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1778 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1779 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1780 } else {
1781 Value *NewAnd = Builder.CreateAnd(
1782 Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1783 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1784 ConstantInt::get(And->getType(), NewCmpCst));
1785 }
1786 }
1787
1788 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1789 // preferable because it allows the C2 << Y expression to be hoisted out of a
1790 // loop if Y is invariant and X is not.
1791 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1792 !Shift->isArithmeticShift() &&
1793 ((!IsShl && C2.isOne()) || !isa<Constant>(Shift->getOperand(0)))) {
1794 // Compute C2 << Y.
1795 Value *NewShift =
1796 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1797 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1798
1799 // Compute X & (C2 << Y).
1800 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1801 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1802 }
1803
1804 return nullptr;
1805}
1806
1807/// Fold icmp (and X, C2), C1.
1810 const APInt &C1) {
1811 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1812
1813 // icmp ne (and X, 1), 0 --> trunc X to i1
1814 if (isICMP_NE && C1.isZero() && match(And->getOperand(1), m_One()))
1815 return new TruncInst(And->getOperand(0), Cmp.getType());
1816
1817 const APInt *C2;
1818 Value *X;
1819 if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1820 return nullptr;
1821
1822 // (and X, highmask) s> [0, ~highmask] --> X s> ~highmask
1823 if (Cmp.getPredicate() == ICmpInst::ICMP_SGT && C1.ule(~*C2) &&
1824 C2->isNegatedPowerOf2())
1825 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1826 ConstantInt::get(X->getType(), ~*C2));
1827 // (and X, highmask) s< [1, -highmask] --> X s< -highmask
1828 if (Cmp.getPredicate() == ICmpInst::ICMP_SLT && !C1.isSignMask() &&
1829 (C1 - 1).ule(~*C2) && C2->isNegatedPowerOf2() && !C2->isSignMask())
1830 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1831 ConstantInt::get(X->getType(), -*C2));
1832
1833 // Don't perform the following transforms if the AND has multiple uses
1834 if (!And->hasOneUse())
1835 return nullptr;
1836
1837 if (Cmp.isEquality() && C1.isZero()) {
1838 // Restrict this fold to single-use 'and' (PR10267).
1839 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1840 if (C2->isSignMask()) {
1841 Constant *Zero = Constant::getNullValue(X->getType());
1842 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1843 return new ICmpInst(NewPred, X, Zero);
1844 }
1845
1846 APInt NewC2 = *C2;
1847 KnownBits Know = computeKnownBits(And->getOperand(0), And);
1848 // Set high zeros of C2 to allow matching negated power-of-2.
1849 NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
1850 Know.countMinLeadingZeros());
1851
1852 // Restrict this fold only for single-use 'and' (PR10267).
1853 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1854 if (NewC2.isNegatedPowerOf2()) {
1855 Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1856 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1857 return new ICmpInst(NewPred, X, NegBOC);
1858 }
1859 }
1860
1861 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1862 // the input width without changing the value produced, eliminate the cast:
1863 //
1864 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1865 //
1866 // We can do this transformation if the constants do not have their sign bits
1867 // set or if it is an equality comparison. Extending a relational comparison
1868 // when we're checking the sign bit would not work.
1869 Value *W;
1870 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1871 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1872 // TODO: Is this a good transform for vectors? Wider types may reduce
1873 // throughput. Should this transform be limited (even for scalars) by using
1874 // shouldChangeType()?
1875 if (!Cmp.getType()->isVectorTy()) {
1876 Type *WideType = W->getType();
1877 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1878 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1879 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1880 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1881 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1882 }
1883 }
1884
1885 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1886 return I;
1887
1888 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1889 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1890 //
1891 // iff pred isn't signed
1892 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1893 match(And->getOperand(1), m_One())) {
1894 Constant *One = cast<Constant>(And->getOperand(1));
1895 Value *Or = And->getOperand(0);
1896 Value *A, *B, *LShr;
1897 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1898 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1899 unsigned UsesRemoved = 0;
1900 if (And->hasOneUse())
1901 ++UsesRemoved;
1902 if (Or->hasOneUse())
1903 ++UsesRemoved;
1904 if (LShr->hasOneUse())
1905 ++UsesRemoved;
1906
1907 // Compute A & ((1 << B) | 1)
1908 unsigned RequireUsesRemoved = match(B, m_ImmConstant()) ? 1 : 3;
1909 if (UsesRemoved >= RequireUsesRemoved) {
1910 Value *NewOr =
1911 Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1912 /*HasNUW=*/true),
1913 One, Or->getName());
1914 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1915 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1916 }
1917 }
1918 }
1919
1920 // (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->
1921 // llvm.is.fpclass(X, fcInf|fcNan)
1922 // (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->
1923 // llvm.is.fpclass(X, ~(fcInf|fcNan))
1924 // (icmp eq (and (bitcast X to int), ExponentMask), 0) -->
1925 // llvm.is.fpclass(X, fcSubnormal|fcZero)
1926 // (icmp ne (and (bitcast X to int), ExponentMask), 0) -->
1927 // llvm.is.fpclass(X, ~(fcSubnormal|fcZero))
1928 Value *V;
1929 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1930 Attribute::NoImplicitFloat) &&
1931 Cmp.isEquality() &&
1933 Type *FPType = V->getType()->getScalarType();
1934 if (FPType->isIEEELikeFPTy() && (C1.isZero() || C1 == *C2)) {
1935 APInt ExponentMask =
1936 APFloat::getInf(FPType->getFltSemantics()).bitcastToAPInt();
1937 if (*C2 == ExponentMask) {
1938 unsigned Mask = C1.isZero()
1941 if (isICMP_NE)
1942 Mask = ~Mask & fcAllFlags;
1943 return replaceInstUsesWith(Cmp, Builder.createIsFPClass(V, Mask));
1944 }
1945 }
1946 }
1947
1948 return nullptr;
1949}
1950
1951/// Fold icmp (and X, Y), C.
1954 const APInt &C) {
1955 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1956 return I;
1957
1958 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1959 bool TrueIfNeg;
1960 if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1961 // ((X - 1) & ~X) < 0 --> X == 0
1962 // ((X - 1) & ~X) >= 0 --> X != 0
1963 Value *X;
1964 if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1965 match(And->getOperand(1), m_Not(m_Specific(X)))) {
1966 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1967 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1968 }
1969 // (X & -X) < 0 --> X == MinSignedC
1970 // (X & -X) > -1 --> X != MinSignedC
1971 if (match(And, m_c_And(m_Neg(m_Value(X)), m_Deferred(X)))) {
1972 Constant *MinSignedC = ConstantInt::get(
1973 X->getType(),
1974 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits()));
1975 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1976 return new ICmpInst(NewPred, X, MinSignedC);
1977 }
1978 }
1979
1980 // TODO: These all require that Y is constant too, so refactor with the above.
1981
1982 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1983 Value *X = And->getOperand(0);
1984 Value *Y = And->getOperand(1);
1985 if (auto *C2 = dyn_cast<ConstantInt>(Y))
1986 if (auto *LI = dyn_cast<LoadInst>(X))
1987 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1988 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(LI, GEP, Cmp, C2))
1989 return Res;
1990
1991 if (!Cmp.isEquality())
1992 return nullptr;
1993
1994 // (X & -X) == 0 --> X == 0
1995 // (X & -X) != 0 --> X != 0
1996 // (X & -X) == 1 --> trunc X to i1
1997 // (X & -X) != 1 --> !(trunc X to i1)
1998 // Cmp is == or != by the check above.
1999 Value *MatchedX;
2000 // Match X & -X in either operand order.
2001 if (C.getBitWidth() > 1 && (C.isZero() || C.isOne()) &&
2002 match(And, m_c_And(m_Neg(m_Value(MatchedX)), m_Deferred(MatchedX)))) {
2003 // Preserve the predicate: (X & -X) ==/!= 0 --> X ==/!= 0.
2004 if (C.isZero())
2005 return new ICmpInst(Pred, MatchedX, Cmp.getOperand(1));
2006
2007 // (X & -X) == 1 iff the low bit of X is set.
2008 if (Pred == CmpInst::ICMP_EQ)
2009 return new TruncInst(MatchedX, Cmp.getType());
2010
2011 // The remaining case needs a trunc and not. Require the original and
2012 // to become dead to avoid increasing the instruction count.
2013 if (And->hasOneUse()) {
2014 Value *Trunc = Builder.CreateTrunc(MatchedX, Cmp.getType());
2015 return BinaryOperator::CreateNot(Trunc);
2016 }
2017 }
2018
2019 // X & -C == -C -> X > u ~C
2020 // X & -C != -C -> X <= u ~C
2021 // iff C is a power of 2
2022 if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
2023 auto NewPred =
2025 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
2026 }
2027
2028 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
2029 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
2030 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
2031 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
2033 X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
2034 Value *TruncY = Builder.CreateTrunc(Y, X->getType());
2035 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
2036 Value *And = Builder.CreateAnd(TruncY, X);
2038 }
2039 return BinaryOperator::CreateAnd(TruncY, X);
2040 }
2041
2042 // (icmp eq/ne (and (shl -1, X), Y), 0)
2043 // -> (icmp eq/ne (lshr Y, X), 0)
2044 // We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems
2045 // highly unlikely the non-zero case will ever show up in code.
2046 if (C.isZero() &&
2048 m_Value(Y))))) {
2049 Value *LShr = Builder.CreateLShr(Y, X);
2050 return new ICmpInst(Pred, LShr, Constant::getNullValue(LShr->getType()));
2051 }
2052
2053 // (icmp eq/ne (and (add A, Addend), Msk), C)
2054 // -> (icmp eq/ne (and A, Msk), (and (sub C, Addend), Msk))
2055 {
2056 Value *A;
2057 const APInt *Addend, *Msk;
2059 m_LowBitMask(Msk)))) &&
2060 C.ule(*Msk)) {
2061 APInt NewComperand = (C - *Addend) & *Msk;
2062 Value *MaskA = Builder.CreateAnd(A, ConstantInt::get(A->getType(), *Msk));
2063 return new ICmpInst(Pred, MaskA,
2064 ConstantInt::get(MaskA->getType(), NewComperand));
2065 }
2066 }
2067
2068 return nullptr;
2069}
2070
2071/// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
2073 InstCombiner::BuilderTy &Builder) {
2074 // Are we using xors or subs to bitwise check for a pair or pairs of
2075 // (in)equalities? Convert to a shorter form that has more potential to be
2076 // folded even further.
2077 // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
2078 // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
2079 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
2080 // (X1 == X2) && (X3 == X4) && (X5 == X6)
2081 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
2082 // (X1 != X2) || (X3 != X4) || (X5 != X6)
2084 SmallVector<Value *, 16> WorkList(1, Or);
2085
2086 while (!WorkList.empty()) {
2087 auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
2088 Value *Lhs, *Rhs;
2089
2090 if (match(OrOperatorArgument,
2091 m_OneUse(m_Xor(m_Value(Lhs), m_Value(Rhs))))) {
2092 CmpValues.emplace_back(Lhs, Rhs);
2093 return;
2094 }
2095
2096 if (match(OrOperatorArgument,
2097 m_OneUse(m_Sub(m_Value(Lhs), m_Value(Rhs))))) {
2098 CmpValues.emplace_back(Lhs, Rhs);
2099 return;
2100 }
2101
2102 WorkList.push_back(OrOperatorArgument);
2103 };
2104
2105 Value *CurrentValue = WorkList.pop_back_val();
2106 Value *OrOperatorLhs, *OrOperatorRhs;
2107
2108 if (!match(CurrentValue,
2109 m_Or(m_Value(OrOperatorLhs), m_Value(OrOperatorRhs)))) {
2110 return nullptr;
2111 }
2112
2113 MatchOrOperatorArgument(OrOperatorRhs);
2114 MatchOrOperatorArgument(OrOperatorLhs);
2115 }
2116
2117 ICmpInst::Predicate Pred = Cmp.getPredicate();
2118 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2119 Value *LhsCmp = Builder.CreateICmp(Pred, CmpValues.rbegin()->first,
2120 CmpValues.rbegin()->second);
2121
2122 for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
2123 Value *RhsCmp = Builder.CreateICmp(Pred, It->first, It->second);
2124 LhsCmp = Builder.CreateBinOp(BOpc, LhsCmp, RhsCmp);
2125 }
2126
2127 return LhsCmp;
2128}
2129
2130/// Fold icmp (or X, Y), C.
2133 const APInt &C) {
2134 ICmpInst::Predicate Pred = Cmp.getPredicate();
2135 if (C.isOne()) {
2136 // icmp slt signum(V) 1 --> icmp slt V, 1
2137 Value *V = nullptr;
2138 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
2139 return new ICmpInst(ICmpInst::ICMP_SLT, V,
2140 ConstantInt::get(V->getType(), 1));
2141 }
2142
2143 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
2144
2145 // (icmp eq/ne (or disjoint x, C0), C1)
2146 // -> (icmp eq/ne x, C0^C1)
2147 if (Cmp.isEquality() && match(OrOp1, m_ImmConstant()) &&
2148 cast<PossiblyDisjointInst>(Or)->isDisjoint()) {
2149 Value *NewC =
2150 Builder.CreateXor(OrOp1, ConstantInt::get(OrOp1->getType(), C));
2151 return new ICmpInst(Pred, OrOp0, NewC);
2152 }
2153
2154 const APInt *MaskC;
2155 if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
2156 if (*MaskC == C && (C + 1).isPowerOf2()) {
2157 // X | C == C --> X <=u C
2158 // X | C != C --> X >u C
2159 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
2161 return new ICmpInst(Pred, OrOp0, OrOp1);
2162 }
2163
2164 // More general: canonicalize 'equality with set bits mask' to
2165 // 'equality with clear bits mask'.
2166 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2167 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2168 if (Or->hasOneUse()) {
2169 Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
2170 Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
2171 return new ICmpInst(Pred, And, NewC);
2172 }
2173 }
2174
2175 // (X | (X-1)) s< 0 --> X s< 1
2176 // (X | (X-1)) s> -1 --> X s> 0
2177 Value *X;
2178 bool TrueIfSigned;
2179 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
2181 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2182 Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
2183 return new ICmpInst(NewPred, X, NewC);
2184 }
2185
2186 const APInt *OrC;
2187 // icmp(X | OrC, C) --> icmp(X, 0)
2188 if (C.isNonNegative() && match(Or, m_Or(m_Value(X), m_APInt(OrC)))) {
2189 switch (Pred) {
2190 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2191 case ICmpInst::ICMP_SLT:
2192 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2193 case ICmpInst::ICMP_SGE:
2194 if (OrC->sge(C))
2195 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2196 break;
2197 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2198 case ICmpInst::ICMP_SLE:
2199 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2200 case ICmpInst::ICMP_SGT:
2201 if (OrC->sgt(C))
2203 ConstantInt::getNullValue(X->getType()));
2204 break;
2205 default:
2206 break;
2207 }
2208 }
2209
2210 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2211 return nullptr;
2212
2213 Value *P, *Q;
2215 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2216 // -> and (icmp eq P, null), (icmp eq Q, null).
2217 Value *CmpP =
2218 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
2219 Value *CmpQ =
2220 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
2221 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2222 return BinaryOperator::Create(BOpc, CmpP, CmpQ);
2223 }
2224
2225 if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2226 return replaceInstUsesWith(Cmp, V);
2227
2228 return nullptr;
2229}
2230
2231/// Fold icmp (mul X, Y), C.
2234 const APInt &C) {
2235 ICmpInst::Predicate Pred = Cmp.getPredicate();
2236 Type *MulTy = Mul->getType();
2237 Value *X = Mul->getOperand(0);
2238
2239 // If comparing a square with a constant, try simplifying to comparing square
2240 // roots.
2241 if (X == Mul->getOperand(1) && !Cmp.isSigned()) {
2242 APInt R = C.sqrtFloor();
2243 bool IsSqr = C == R * R;
2244
2245 // X * X eq/ne C
2246 if (Cmp.isEquality() &&
2247 (Mul->hasNoUnsignedWrap() || (Mul->hasNoSignedWrap() && C.isZero()))) {
2248
2249 // If constant is not a square, eq/ne is false/true respectively
2250 if (!IsSqr)
2251 return replaceInstUsesWith(
2252 Cmp,
2253 ConstantInt::getBool(Cmp.getType(), Pred == ICmpInst::ICMP_NE));
2254
2255 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2256 }
2257
2258 // If the multiply does not wrap
2259 // X * X pred C --> X pred R
2260 if (Mul->hasNoUnsignedWrap()) {
2261
2262 if (IsSqr)
2263 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2264
2265 // If C is not a square, we use floor/ceil of sqrt(C).
2266 //
2267 // If LT or LE, we need R to be an overestimate of sqrt(C),
2268 // then use the strict predicate (LT->LT, LE->LT).
2269 //
2270 // If GT or GE, we need R to be an underestimate of sqrt(C),
2271 // then use the strict predicate (GT->GT, GE->GT).
2272 //
2273 // R is already an underestimate of sqrt(C) due to sqrtFloor.
2274 if (ICmpInst::isLT(Pred) || ICmpInst::isLE(Pred))
2275 ++R;
2276
2277 return new ICmpInst(Cmp.getStrictPredicate(), X,
2278 ConstantInt::get(MulTy, R));
2279 }
2280 }
2281
2282 const APInt *MulC;
2283 if (!match(Mul->getOperand(1), m_APInt(MulC)))
2284 return nullptr;
2285
2286 // If this is a test of the sign bit and the multiply is sign-preserving with
2287 // a constant operand, use the multiply LHS operand instead:
2288 // (X * +MulC) < 0 --> X < 0
2289 // (X * -MulC) < 0 --> X > 0
2290 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2291 if (MulC->isNegative())
2292 Pred = ICmpInst::getSwappedPredicate(Pred);
2293 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2294 }
2295
2296 if (MulC->isZero())
2297 return nullptr;
2298
2299 // If the multiply does not wrap or the constant is odd, try to divide the
2300 // compare constant by the multiplication factor.
2301 if (Cmp.isEquality()) {
2302 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2303 if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
2304 Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
2305 return new ICmpInst(Pred, X, NewC);
2306 }
2307
2308 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2309 // correct to transform if MulC * N == C including overflow. I.e with i8
2310 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2311 // miss that case.
2312 if (C.urem(*MulC).isZero()) {
2313 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2314 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2315 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2316 Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
2317 return new ICmpInst(Pred, X, NewC);
2318 }
2319 }
2320 }
2321
2322 // With a matching no-overflow guarantee, fold the constants:
2323 // (X * MulC) < C --> X < (C / MulC)
2324 // (X * MulC) > C --> X > (C / MulC)
2325 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2326 Constant *NewC = nullptr;
2327 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2328 // MININT / -1 --> overflow.
2329 if (C.isMinSignedValue() && MulC->isAllOnes())
2330 return nullptr;
2331 if (MulC->isNegative())
2332 Pred = ICmpInst::getSwappedPredicate(Pred);
2333
2334 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2335 NewC = ConstantInt::get(
2337 } else {
2338 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2339 "Unexpected predicate");
2340 NewC = ConstantInt::get(
2342 }
2343 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2344 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2345 NewC = ConstantInt::get(
2347 } else {
2348 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2349 "Unexpected predicate");
2350 NewC = ConstantInt::get(
2352 }
2353 }
2354
2355 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2356}
2357
2358/// Fold icmp (shl nuw C2, Y), C.
2360 const APInt &C) {
2361 Value *Y;
2362 const APInt *C2;
2363 if (!match(Shl, m_NUWShl(m_APInt(C2), m_Value(Y))))
2364 return nullptr;
2365
2366 Type *ShiftType = Shl->getType();
2367 unsigned TypeBits = C.getBitWidth();
2368 ICmpInst::Predicate Pred = Cmp.getPredicate();
2369 if (Cmp.isUnsigned()) {
2370 if (C2->isZero() || C2->ugt(C))
2371 return nullptr;
2372 APInt Div, Rem;
2373 APInt::udivrem(C, *C2, Div, Rem);
2374 bool CIsPowerOf2 = Rem.isZero() && Div.isPowerOf2();
2375
2376 // (1 << Y) pred C -> Y pred Log2(C)
2377 if (!CIsPowerOf2) {
2378 // (1 << Y) < 30 -> Y <= 4
2379 // (1 << Y) <= 30 -> Y <= 4
2380 // (1 << Y) >= 30 -> Y > 4
2381 // (1 << Y) > 30 -> Y > 4
2382 if (Pred == ICmpInst::ICMP_ULT)
2383 Pred = ICmpInst::ICMP_ULE;
2384 else if (Pred == ICmpInst::ICMP_UGE)
2385 Pred = ICmpInst::ICMP_UGT;
2386 }
2387
2388 unsigned CLog2 = Div.logBase2();
2389 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2390 } else if (Cmp.isSigned() && C2->isOne()) {
2391 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2392 // (1 << Y) > 0 -> Y != 31
2393 // (1 << Y) > C -> Y != 31 if C is negative.
2394 if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
2395 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2396
2397 // (1 << Y) < 0 -> Y == 31
2398 // (1 << Y) < 1 -> Y == 31
2399 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2400 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2401 if (Pred == ICmpInst::ICMP_SLT && (C - 1).sle(0))
2402 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2403 }
2404
2405 return nullptr;
2406}
2407
2408/// Fold icmp (shl X, Y), C.
2410 BinaryOperator *Shl,
2411 const APInt &C) {
2412 const APInt *ShiftVal;
2413 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2414 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2415
2416 ICmpInst::Predicate Pred = Cmp.getPredicate();
2417 // (icmp pred (shl nuw&nsw X, Y), Csle0)
2418 // -> (icmp pred X, Csle0)
2419 //
2420 // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2421 // so X's must be what is used.
2422 if (C.sle(0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2423 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2424
2425 // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2426 // -> (icmp eq/ne X, 0)
2427 if (ICmpInst::isEquality(Pred) && C.isZero() &&
2428 (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2429 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2430
2431 // (icmp slt (shl nsw X, Y), 0/1)
2432 // -> (icmp slt X, 0/1)
2433 // (icmp sgt (shl nsw X, Y), 0/-1)
2434 // -> (icmp sgt X, 0/-1)
2435 //
2436 // NB: sge/sle with a constant will canonicalize to sgt/slt.
2437 if (Shl->hasNoSignedWrap() &&
2438 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2439 if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2440 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2441
2442 const APInt *ShiftAmt;
2443 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2444 return foldICmpShlLHSC(Cmp, Shl, C);
2445
2446 // Check that the shift amount is in range. If not, don't perform undefined
2447 // shifts. When the shift is visited, it will be simplified.
2448 unsigned TypeBits = C.getBitWidth();
2449 if (ShiftAmt->uge(TypeBits))
2450 return nullptr;
2451
2452 Value *X = Shl->getOperand(0);
2453 Type *ShType = Shl->getType();
2454
2455 // NSW guarantees that we are only shifting out sign bits from the high bits,
2456 // so we can ASHR the compare constant without needing a mask and eliminate
2457 // the shift.
2458 if (Shl->hasNoSignedWrap()) {
2459 if (Pred == ICmpInst::ICMP_SGT) {
2460 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2461 APInt ShiftedC = C.ashr(*ShiftAmt);
2462 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2463 }
2464 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2465 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2466 APInt ShiftedC = C.ashr(*ShiftAmt);
2467 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2468 }
2469 if (Pred == ICmpInst::ICMP_SLT) {
2470 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2471 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2472 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2473 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2474 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2475 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2476 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2477 }
2478 }
2479
2480 // NUW guarantees that we are only shifting out zero bits from the high bits,
2481 // so we can LSHR the compare constant without needing a mask and eliminate
2482 // the shift.
2483 if (Shl->hasNoUnsignedWrap()) {
2484 if (Pred == ICmpInst::ICMP_UGT) {
2485 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2486 APInt ShiftedC = C.lshr(*ShiftAmt);
2487 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2488 }
2489 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2490 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2491 APInt ShiftedC = C.lshr(*ShiftAmt);
2492 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2493 }
2494 if (Pred == ICmpInst::ICMP_ULT) {
2495 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2496 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2497 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2498 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2499 assert(C.ugt(0) && "ult 0 should have been eliminated");
2500 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2501 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2502 }
2503 }
2504
2505 if (Cmp.isEquality() && Shl->hasOneUse()) {
2506 // Strength-reduce the shift into an 'and'.
2507 Constant *Mask = ConstantInt::get(
2508 ShType,
2509 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2510 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2511 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2512 return new ICmpInst(Pred, And, LShrC);
2513 }
2514
2515 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2516 bool TrueIfSigned = false;
2517 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2518 // (X << 31) <s 0 --> (X & 1) != 0
2519 Constant *Mask = ConstantInt::get(
2520 ShType,
2521 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2522 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2523 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2524 And, Constant::getNullValue(ShType));
2525 }
2526
2527 // Simplify 'shl' inequality test into 'and' equality test.
2528 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2529 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2530 if ((C + 1).isPowerOf2() &&
2531 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2532 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2533 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2535 And, Constant::getNullValue(ShType));
2536 }
2537 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2538 if (C.isPowerOf2() &&
2539 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2540 Value *And =
2541 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2542 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2544 And, Constant::getNullValue(ShType));
2545 }
2546 }
2547
2548 // Transform (icmp pred iM (shl iM %v, N), C)
2549 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2550 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2551 // This enables us to get rid of the shift in favor of a trunc that may be
2552 // free on the target. It has the additional benefit of comparing to a
2553 // smaller constant that may be more target-friendly.
2554 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2555 if (Shl->hasOneUse() && Amt != 0 &&
2556 shouldChangeType(ShType->getScalarSizeInBits(), TypeBits - Amt)) {
2557 ICmpInst::Predicate CmpPred = Pred;
2558 APInt RHSC = C;
2559
2560 if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(CmpPred)) {
2561 // Try the flipped strictness predicate.
2562 // e.g.:
2563 // icmp ult i64 (shl X, 32), 8589934593 ->
2564 // icmp ule i64 (shl X, 32), 8589934592 ->
2565 // icmp ule i32 (trunc X, i32), 2 ->
2566 // icmp ult i32 (trunc X, i32), 3
2567 if (auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(
2568 Pred, ConstantInt::get(ShType->getContext(), C))) {
2569 CmpPred = FlippedStrictness->first;
2570 RHSC = cast<ConstantInt>(FlippedStrictness->second)->getValue();
2571 }
2572 }
2573
2574 if (RHSC.countr_zero() >= Amt) {
2575 Type *TruncTy = ShType->getWithNewBitWidth(TypeBits - Amt);
2576 Constant *NewC =
2577 ConstantInt::get(TruncTy, RHSC.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2578 return new ICmpInst(CmpPred,
2579 Builder.CreateTrunc(X, TruncTy, "", /*IsNUW=*/false,
2580 Shl->hasNoSignedWrap()),
2581 NewC);
2582 }
2583 }
2584
2585 return nullptr;
2586}
2587
2588/// Fold icmp ({al}shr X, Y), C.
2590 BinaryOperator *Shr,
2591 const APInt &C) {
2592 // An exact shr only shifts out zero bits, so:
2593 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2594 Value *X = Shr->getOperand(0);
2595 CmpInst::Predicate Pred = Cmp.getPredicate();
2596 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2597 return new ICmpInst(Pred, X, Cmp.getOperand(1));
2598
2599 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2600 const APInt *ShiftValC;
2601 if (match(X, m_APInt(ShiftValC))) {
2602 if (Cmp.isEquality())
2603 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2604
2605 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2606 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2607 bool TrueIfSigned;
2608 if (!IsAShr && ShiftValC->isNegative() &&
2609 isSignBitCheck(Pred, C, TrueIfSigned))
2610 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2611 Shr->getOperand(1),
2612 ConstantInt::getNullValue(X->getType()));
2613
2614 // If the shifted constant is a power-of-2, test the shift amount directly:
2615 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2616 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2617 if (!IsAShr && ShiftValC->isPowerOf2() &&
2618 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2619 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2620 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2621 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2622
2623 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2624 unsigned ShiftLZ = ShiftValC->countl_zero();
2625 Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2626 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2627 return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2628 }
2629 }
2630
2631 const APInt *ShiftAmtC;
2632 if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2633 return nullptr;
2634
2635 // Check that the shift amount is in range. If not, don't perform undefined
2636 // shifts. When the shift is visited it will be simplified.
2637 unsigned TypeBits = C.getBitWidth();
2638 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2639 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2640 return nullptr;
2641
2642 bool IsExact = Shr->isExact();
2643 Type *ShrTy = Shr->getType();
2644 // TODO: If we could guarantee that InstSimplify would handle all of the
2645 // constant-value-based preconditions in the folds below, then we could assert
2646 // those conditions rather than checking them. This is difficult because of
2647 // undef/poison (PR34838).
2648 if (IsAShr && Shr->hasOneUse()) {
2649 if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&
2650 (C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {
2651 // When C - 1 is a power of two and the transform can be legally
2652 // performed, prefer this form so the produced constant is close to a
2653 // power of two.
2654 // icmp slt/ult (ashr exact X, ShAmtC), C
2655 // --> icmp slt/ult X, (C - 1) << ShAmtC) + 1
2656 APInt ShiftedC = (C - 1).shl(ShAmtVal) + 1;
2657 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2658 }
2659 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2660 // When ShAmtC can be shifted losslessly:
2661 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2662 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2663 APInt ShiftedC = C.shl(ShAmtVal);
2664 if (ShiftedC.ashr(ShAmtVal) == C)
2665 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2666 }
2667 if (Pred == CmpInst::ICMP_SGT) {
2668 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2669 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2670 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2671 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2672 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2673 }
2674 if (Pred == CmpInst::ICMP_UGT) {
2675 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2676 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2677 // clause accounts for that pattern.
2678 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2679 if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2680 (C + 1).shl(ShAmtVal).isMinSignedValue())
2681 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2682 }
2683
2684 // If the compare constant has significant bits above the lowest sign-bit,
2685 // then convert an unsigned cmp to a test of the sign-bit:
2686 // (ashr X, ShiftC) u> C --> X s< 0
2687 // (ashr X, ShiftC) u< C --> X s> -1
2688 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2689 if (Pred == CmpInst::ICMP_UGT) {
2690 return new ICmpInst(CmpInst::ICMP_SLT, X,
2692 }
2693 if (Pred == CmpInst::ICMP_ULT) {
2694 return new ICmpInst(CmpInst::ICMP_SGT, X,
2696 }
2697 }
2698 } else if (!IsAShr) {
2699 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2700 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2701 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2702 APInt ShiftedC = C.shl(ShAmtVal);
2703 if (ShiftedC.lshr(ShAmtVal) == C)
2704 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2705 }
2706 if (Pred == CmpInst::ICMP_UGT) {
2707 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2708 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2709 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2710 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2711 }
2712 }
2713
2714 if (!Cmp.isEquality())
2715 return nullptr;
2716
2717 // Handle equality comparisons of shift-by-constant.
2718
2719 // If the comparison constant changes with the shift, the comparison cannot
2720 // succeed (bits of the comparison constant cannot match the shifted value).
2721 // This should be known by InstSimplify and already be folded to true/false.
2722 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2723 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2724 "Expected icmp+shr simplify did not occur.");
2725
2726 // If the bits shifted out are known zero, compare the unshifted value:
2727 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2728 if (Shr->isExact())
2729 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2730
2731 if (Shr->hasOneUse()) {
2732 // Canonicalize the shift into an 'and':
2733 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2734 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2735 Constant *Mask = ConstantInt::get(ShrTy, Val);
2736 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2737 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2738 }
2739
2740 return nullptr;
2741}
2742
2744 BinaryOperator *SRem,
2745 const APInt &C) {
2746 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2747 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT) {
2748 // Canonicalize unsigned predicates to signed:
2749 // (X s% DivisorC) u> C -> (X s% DivisorC) s< 0
2750 // iff (C s< 0 ? ~C : C) u>= abs(DivisorC)-1
2751 // (X s% DivisorC) u< C+1 -> (X s% DivisorC) s> -1
2752 // iff (C+1 s< 0 ? ~C : C) u>= abs(DivisorC)-1
2753
2754 const APInt *DivisorC;
2755 if (!match(SRem->getOperand(1), m_APInt(DivisorC)))
2756 return nullptr;
2757 if (DivisorC->isZero())
2758 return nullptr;
2759
2760 APInt NormalizedC = C;
2761 if (Pred == ICmpInst::ICMP_ULT) {
2762 assert(!NormalizedC.isZero() &&
2763 "ult X, 0 should have been simplified already.");
2764 --NormalizedC;
2765 }
2766 if (C.isNegative())
2767 NormalizedC.flipAllBits();
2768 if (!NormalizedC.uge(DivisorC->abs() - 1))
2769 return nullptr;
2770
2771 Type *Ty = SRem->getType();
2772 if (Pred == ICmpInst::ICMP_UGT)
2773 return new ICmpInst(ICmpInst::ICMP_SLT, SRem,
2775 return new ICmpInst(ICmpInst::ICMP_SGT, SRem,
2777 }
2778 // Match an 'is positive' or 'is negative' comparison of remainder by a
2779 // constant power-of-2 value:
2780 // (X % pow2C) sgt/slt 0
2781 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2782 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2783 return nullptr;
2784
2785 // TODO: The one-use check is standard because we do not typically want to
2786 // create longer instruction sequences, but this might be a special-case
2787 // because srem is not good for analysis or codegen.
2788 if (!SRem->hasOneUse())
2789 return nullptr;
2790
2791 const APInt *DivisorC;
2792 if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2793 return nullptr;
2794
2795 // For cmp_sgt/cmp_slt only zero valued C is handled.
2796 // For cmp_eq/cmp_ne only positive valued C is handled.
2797 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2798 !C.isZero()) ||
2799 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2800 !C.isStrictlyPositive()))
2801 return nullptr;
2802
2803 // Mask off the sign bit and the modulo bits (low-bits).
2804 Type *Ty = SRem->getType();
2805 APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
2806 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2807 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2808
2809 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2810 return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2811
2812 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2813 // bit is set. Example:
2814 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2815 if (Pred == ICmpInst::ICMP_SGT)
2817
2818 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2819 // bit is set. Example:
2820 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2821 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2822}
2823
2824/// Fold icmp (udiv X, Y), C.
2826 BinaryOperator *UDiv,
2827 const APInt &C) {
2828 ICmpInst::Predicate Pred = Cmp.getPredicate();
2829 Value *X = UDiv->getOperand(0);
2830 Value *Y = UDiv->getOperand(1);
2831 Type *Ty = UDiv->getType();
2832
2833 const APInt *C2;
2834 if (!match(X, m_APInt(C2)))
2835 return nullptr;
2836
2837 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2838
2839 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2840 if (Pred == ICmpInst::ICMP_UGT) {
2841 assert(!C.isMaxValue() &&
2842 "icmp ugt X, UINT_MAX should have been simplified already.");
2843 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2844 ConstantInt::get(Ty, C2->udiv(C + 1)));
2845 }
2846
2847 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2848 if (Pred == ICmpInst::ICMP_ULT) {
2849 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2850 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2851 ConstantInt::get(Ty, C2->udiv(C)));
2852 }
2853
2854 return nullptr;
2855}
2856
2857/// Fold icmp ({su}div X, Y), C.
2859 BinaryOperator *Div,
2860 const APInt &C) {
2861 ICmpInst::Predicate Pred = Cmp.getPredicate();
2862 Value *X = Div->getOperand(0);
2863 Value *Y = Div->getOperand(1);
2864 Type *Ty = Div->getType();
2865 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2866
2867 // If unsigned division and the compare constant is bigger than
2868 // UMAX/2 (negative), there's only one pair of values that satisfies an
2869 // equality check, so eliminate the division:
2870 // (X u/ Y) == C --> (X == C) && (Y == 1)
2871 // (X u/ Y) != C --> (X != C) || (Y != 1)
2872 // Similarly, if signed division and the compare constant is exactly SMIN:
2873 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2874 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2875 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2876 (!DivIsSigned || C.isMinSignedValue())) {
2877 Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2878 Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2879 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2880 return BinaryOperator::Create(Logic, XBig, YOne);
2881 }
2882
2883 // Fold: icmp pred ([us]div X, C2), C -> range test
2884 // Fold this div into the comparison, producing a range check.
2885 // Determine, based on the divide type, what the range is being
2886 // checked. If there is an overflow on the low or high side, remember
2887 // it, otherwise compute the range [low, hi) bounding the new value.
2888 // See: InsertRangeTest above for the kinds of replacements possible.
2889 const APInt *C2;
2890 if (!match(Y, m_APInt(C2)))
2891 return nullptr;
2892
2893 // FIXME: If the operand types don't match the type of the divide
2894 // then don't attempt this transform. The code below doesn't have the
2895 // logic to deal with a signed divide and an unsigned compare (and
2896 // vice versa). This is because (x /s C2) <s C produces different
2897 // results than (x /s C2) <u C or (x /u C2) <s C or even
2898 // (x /u C2) <u C. Simply casting the operands and result won't
2899 // work. :( The if statement below tests that condition and bails
2900 // if it finds it.
2901 // However, when the divisor is a positive constant and the dividend is
2902 // known non-negative, sdiv is equivalent to udiv, so we can lower
2903 // DivIsSigned and proceed through the unsigned path.
2904 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) {
2905 if (!DivIsSigned || !C2->isStrictlyPositive() ||
2906 !isKnownNonNegative(X, SQ.getWithInstruction(&Cmp)))
2907 return nullptr;
2908 DivIsSigned = false;
2909 }
2910
2911 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2912 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2913 // division-by-constant cases should be present, we can not assert that they
2914 // have happened before we reach this icmp instruction.
2915 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2916 return nullptr;
2917
2918 // Compute Prod = C * C2. We are essentially solving an equation of
2919 // form X / C2 = C. We solve for X by multiplying C2 and C.
2920 // By solving for X, we can turn this into a range check instead of computing
2921 // a divide.
2922 APInt Prod = C * *C2;
2923
2924 // Determine if the product overflows by seeing if the product is not equal to
2925 // the divide. Make sure we do the same kind of divide as in the LHS
2926 // instruction that we're folding.
2927 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2928
2929 // If the division is known to be exact, then there is no remainder from the
2930 // divide, so the covered range size is unit, otherwise it is the divisor.
2931 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2932
2933 // Figure out the interval that is being checked. For example, a comparison
2934 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2935 // Compute this interval based on the constants involved and the signedness of
2936 // the compare/divide. This computes a half-open interval, keeping track of
2937 // whether either value in the interval overflows. After analysis each
2938 // overflow variable is set to 0 if it's corresponding bound variable is valid
2939 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2940 int LoOverflow = 0, HiOverflow = 0;
2941 APInt LoBound, HiBound;
2942
2943 if (!DivIsSigned) { // udiv
2944 // e.g. X/5 op 3 --> [15, 20)
2945 LoBound = Prod;
2946 HiOverflow = LoOverflow = ProdOV;
2947 if (!HiOverflow) {
2948 // If this is not an exact divide, then many values in the range collapse
2949 // to the same result value.
2950 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2951 }
2952 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2953 if (C.isZero()) { // (X / pos) op 0
2954 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2955 LoBound = -(RangeSize - 1);
2956 HiBound = RangeSize;
2957 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2958 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2959 HiOverflow = LoOverflow = ProdOV;
2960 if (!HiOverflow)
2961 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2962 } else { // (X / pos) op neg
2963 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2964 HiBound = Prod + 1;
2965 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2966 if (!LoOverflow) {
2967 APInt DivNeg = -RangeSize;
2968 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2969 }
2970 }
2971 } else if (C2->isNegative()) { // Divisor is < 0.
2972 if (Div->isExact())
2973 RangeSize.negate();
2974 if (C.isZero()) { // (X / neg) op 0
2975 // e.g. X/-5 op 0 --> [-4, 5)
2976 LoBound = RangeSize + 1;
2977 HiBound = -RangeSize;
2978 if (HiBound == *C2) { // -INTMIN = INTMIN
2979 HiOverflow = 1; // [INTMIN+1, overflow)
2980 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2981 }
2982 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2983 // e.g. X/-5 op 3 --> [-19, -14)
2984 HiBound = Prod + 1;
2985 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2986 if (!LoOverflow)
2987 LoOverflow =
2988 addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
2989 } else { // (X / neg) op neg
2990 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2991 LoOverflow = HiOverflow = ProdOV;
2992 if (!HiOverflow)
2993 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2994 }
2995
2996 // Dividing by a negative swaps the condition. LT <-> GT
2997 Pred = ICmpInst::getSwappedPredicate(Pred);
2998 }
2999
3000 switch (Pred) {
3001 default:
3002 llvm_unreachable("Unhandled icmp predicate!");
3003 case ICmpInst::ICMP_EQ:
3004 if (LoOverflow && HiOverflow)
3005 return replaceInstUsesWith(Cmp, Builder.getFalse());
3006 if (HiOverflow)
3007 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3008 X, ConstantInt::get(Ty, LoBound));
3009 if (LoOverflow)
3010 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3011 X, ConstantInt::get(Ty, HiBound));
3012 return replaceInstUsesWith(
3013 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
3014 case ICmpInst::ICMP_NE:
3015 if (LoOverflow && HiOverflow)
3016 return replaceInstUsesWith(Cmp, Builder.getTrue());
3017 if (HiOverflow)
3018 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3019 X, ConstantInt::get(Ty, LoBound));
3020 if (LoOverflow)
3021 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3022 X, ConstantInt::get(Ty, HiBound));
3023 return replaceInstUsesWith(
3024 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
3025 case ICmpInst::ICMP_ULT:
3026 case ICmpInst::ICMP_SLT:
3027 if (LoOverflow == +1) // Low bound is greater than input range.
3028 return replaceInstUsesWith(Cmp, Builder.getTrue());
3029 if (LoOverflow == -1) // Low bound is less than input range.
3030 return replaceInstUsesWith(Cmp, Builder.getFalse());
3031 return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
3032 case ICmpInst::ICMP_UGT:
3033 case ICmpInst::ICMP_SGT:
3034 if (HiOverflow == +1) // High bound greater than input range.
3035 return replaceInstUsesWith(Cmp, Builder.getFalse());
3036 if (HiOverflow == -1) // High bound less than input range.
3037 return replaceInstUsesWith(Cmp, Builder.getTrue());
3038 if (Pred == ICmpInst::ICMP_UGT)
3039 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
3040 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
3041 }
3042
3043 return nullptr;
3044}
3045
3046/// Fold icmp (sub X, Y), C.
3049 const APInt &C) {
3050 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
3051 ICmpInst::Predicate Pred = Cmp.getPredicate();
3052 Type *Ty = Sub->getType();
3053
3054 // (X - (X urem D)) is D*(X/D), a multiple of D, so it is u> C exactly when
3055 // X u>= D (for C u< D), and u< C exactly when X u< D (for 0 u< C u<= D):
3056 // icmp ugt (sub X, (urem X, D)), C --> icmp ugt X, D-1
3057 // icmp ult (sub X, (urem X, D)), C --> icmp ult X, D
3058 const APInt *D;
3059 if (match(Y, m_URem(m_Specific(X), m_APInt(D))) && !D->isZero()) {
3060 if (Pred == ICmpInst::ICMP_UGT && C.ult(*D))
3061 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, *D - 1));
3062 if (Pred == ICmpInst::ICMP_ULT && !C.isZero() && C.ule(*D))
3063 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, *D));
3064 }
3065
3066 // (SubC - Y) == C) --> Y == (SubC - C)
3067 // (SubC - Y) != C) --> Y != (SubC - C)
3068 Constant *SubC;
3069 if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
3070 return new ICmpInst(Pred, Y,
3071 ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C)));
3072 }
3073
3074 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
3075 const APInt *C2;
3076 APInt SubResult;
3077 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
3078 bool HasNSW = Sub->hasNoSignedWrap();
3079 bool HasNUW = Sub->hasNoUnsignedWrap();
3080 if (match(X, m_APInt(C2)) &&
3081 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
3082 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
3083 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
3084
3085 // X - Y == 0 --> X == Y.
3086 // X - Y != 0 --> X != Y.
3087 // TODO: We allow this with multiple uses as long as the other uses are not
3088 // in phis. The phi use check is guarding against a codegen regression
3089 // for a loop test. If the backend could undo this (and possibly
3090 // subsequent transforms), we would not need this hack.
3091 if (Cmp.isEquality() && C.isZero() &&
3092 none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
3093 return new ICmpInst(Pred, X, Y);
3094
3095 // The following transforms are only worth it if the only user of the subtract
3096 // is the icmp.
3097 // TODO: This is an artificial restriction for all of the transforms below
3098 // that only need a single replacement icmp. Can these use the phi test
3099 // like the transform above here?
3100 if (!Sub->hasOneUse())
3101 return nullptr;
3102
3103 if (Sub->hasNoSignedWrap()) {
3104 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
3105 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3106 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3107
3108 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
3109 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
3110 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3111
3112 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
3113 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
3114 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3115
3116 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
3117 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3118 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3119 }
3120
3121 if (!match(X, m_APInt(C2)))
3122 return nullptr;
3123
3124 // C2 - Y <u C -> (Y | (C - 1)) == C2
3125 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
3126 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
3127 (*C2 & (C - 1)) == (C - 1))
3128 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
3129
3130 // C2 - Y >u C -> (Y | C) != C2
3131 // iff C2 & C == C and C + 1 is a power of 2
3132 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
3133 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
3134
3135 // We have handled special cases that reduce.
3136 // Canonicalize any remaining sub to add as:
3137 // (C2 - Y) > C --> (Y + ~C2) < ~C
3138 Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
3139 HasNUW, HasNSW);
3140 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
3141}
3142
3143static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
3144 Value *Op1, IRBuilderBase &Builder,
3145 bool HasOneUse) {
3146 auto FoldConstant = [&](bool Val) {
3147 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3148 if (Op0->getType()->isVectorTy())
3150 cast<VectorType>(Op0->getType())->getElementCount(), Res);
3151 return Res;
3152 };
3153
3154 switch (Table.to_ulong()) {
3155 case 0: // 0 0 0 0
3156 return FoldConstant(false);
3157 case 1: // 0 0 0 1
3158 return HasOneUse ? Builder.CreateNot(Builder.CreateOr(Op0, Op1)) : nullptr;
3159 case 2: // 0 0 1 0
3160 return HasOneUse ? Builder.CreateAnd(Builder.CreateNot(Op0), Op1) : nullptr;
3161 case 3: // 0 0 1 1
3162 return Builder.CreateNot(Op0);
3163 case 4: // 0 1 0 0
3164 return HasOneUse ? Builder.CreateAnd(Op0, Builder.CreateNot(Op1)) : nullptr;
3165 case 5: // 0 1 0 1
3166 return Builder.CreateNot(Op1);
3167 case 6: // 0 1 1 0
3168 return Builder.CreateXor(Op0, Op1);
3169 case 7: // 0 1 1 1
3170 return HasOneUse ? Builder.CreateNot(Builder.CreateAnd(Op0, Op1)) : nullptr;
3171 case 8: // 1 0 0 0
3172 return Builder.CreateAnd(Op0, Op1);
3173 case 9: // 1 0 0 1
3174 return HasOneUse ? Builder.CreateNot(Builder.CreateXor(Op0, Op1)) : nullptr;
3175 case 10: // 1 0 1 0
3176 return Op1;
3177 case 11: // 1 0 1 1
3178 return HasOneUse ? Builder.CreateOr(Builder.CreateNot(Op0), Op1) : nullptr;
3179 case 12: // 1 1 0 0
3180 return Op0;
3181 case 13: // 1 1 0 1
3182 return HasOneUse ? Builder.CreateOr(Op0, Builder.CreateNot(Op1)) : nullptr;
3183 case 14: // 1 1 1 0
3184 return Builder.CreateOr(Op0, Op1);
3185 case 15: // 1 1 1 1
3186 return FoldConstant(true);
3187 default:
3188 llvm_unreachable("Invalid Operation");
3189 }
3190 return nullptr;
3191}
3192
3194 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3195 Value *A, *B;
3196 Constant *C1, *C2, *C3, *C4;
3197 if (!match(BO->getOperand(0),
3199 !match(BO->getOperand(1),
3201 Cmp.getType() != A->getType() || Cmp.getType() != B->getType())
3202 return nullptr;
3203
3204 std::bitset<4> Table;
3205 auto ComputeTable = [&](bool First, bool Second) -> std::optional<bool> {
3206 Constant *L = First ? C1 : C2;
3207 Constant *R = Second ? C3 : C4;
3208 if (auto *Res = ConstantFoldBinaryOpOperands(BO->getOpcode(), L, R, DL)) {
3209 auto *Val = Res->getType()->isVectorTy() ? Res->getSplatValue() : Res;
3210 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val))
3211 return ICmpInst::compare(CI->getValue(), C, Cmp.getPredicate());
3212 }
3213 return std::nullopt;
3214 };
3215
3216 for (unsigned I = 0; I < 4; ++I) {
3217 bool First = (I >> 1) & 1;
3218 bool Second = I & 1;
3219 if (auto Res = ComputeTable(First, Second))
3220 Table[I] = *Res;
3221 else
3222 return nullptr;
3223 }
3224
3225 // Synthesize optimal logic.
3226 if (auto *Cond = createLogicFromTable(Table, A, B, Builder, BO->hasOneUse()))
3227 return replaceInstUsesWith(Cmp, Cond);
3228 return nullptr;
3229}
3230
3231/// Fold icmp (add X, Y), C.
3234 const APInt &C) {
3235 Value *Y = Add->getOperand(1);
3236 Value *X = Add->getOperand(0);
3237 const CmpPredicate Pred = Cmp.getCmpPredicate();
3238
3239 // icmp ult (add nuw A, (lshr A, ShAmtC)), C --> icmp ult A, C
3240 // when C <= (1 << ShAmtC).
3241 const APInt *ShAmtC;
3242 Value *A;
3243 unsigned BitWidth = C.getBitWidth();
3244 if (Pred == ICmpInst::ICMP_ULT &&
3245 match(Add,
3246 m_c_NUWAdd(m_Value(A), m_LShr(m_Deferred(A), m_APInt(ShAmtC)))) &&
3247 ShAmtC->ult(BitWidth) &&
3248 C.ule(APInt::getOneBitSet(BitWidth, ShAmtC->getZExtValue())))
3249 return new ICmpInst(Pred, A, ConstantInt::get(A->getType(), C));
3250
3251 const APInt *C2;
3252 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
3253 return nullptr;
3254
3255 // Fold icmp pred (add X, C2), C.
3256 Type *Ty = Add->getType();
3257
3258 // If the add does not wrap, we can always adjust the compare by subtracting
3259 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3260 // have been canonicalized to SGT/SLT/UGT/ULT.
3261 if (Add->hasNoUnsignedWrap() &&
3262 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT)) {
3263 bool Overflow;
3264 APInt NewC = C.usub_ov(*C2, Overflow);
3265 // If there is overflow, the result must be true or false.
3266 if (!Overflow)
3267 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
3268 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
3269 }
3270
3271 CmpInst::Predicate ChosenPred = Pred.getPreferredSignedPredicate();
3272
3273 if (Add->hasNoSignedWrap() &&
3274 (ChosenPred == ICmpInst::ICMP_SGT || ChosenPred == ICmpInst::ICMP_SLT)) {
3275 bool Overflow;
3276 APInt NewC = C.ssub_ov(*C2, Overflow);
3277 if (!Overflow)
3278 // icmp samesign ugt/ult (add nsw X, C2), C
3279 // -> icmp sgt/slt X, (C - C2)
3280 return new ICmpInst(ChosenPred, X, ConstantInt::get(Ty, NewC));
3281 }
3282
3283 if (ICmpInst::isUnsigned(Pred) && Add->hasNoSignedWrap() &&
3284 C.isNonNegative() && (C - *C2).isNonNegative() &&
3285 computeConstantRange(X, /*ForSigned=*/true, SQ.getWithInstruction(&Cmp))
3286 .add(*C2)
3287 .isAllNonNegative())
3288 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), X,
3289 ConstantInt::get(Ty, C - *C2));
3290
3291 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
3292 const APInt &Upper = CR.getUpper();
3293 const APInt &Lower = CR.getLower();
3294 if (Cmp.isSigned()) {
3295 if (Lower.isSignMask())
3296 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
3297 if (Upper.isSignMask())
3298 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
3299 } else {
3300 if (Lower.isMinValue())
3301 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
3302 if (Upper.isMinValue())
3303 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
3304 }
3305
3306 // This set of folds is intentionally placed after folds that use no-wrapping
3307 // flags because those folds are likely better for later analysis/codegen.
3308 const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
3309 const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
3310
3311 // Fold compare with offset to opposite sign compare if it eliminates offset:
3312 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3313 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3314 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
3315
3316 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3317 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3318 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
3319
3320 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3321 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3322 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
3323
3324 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3325 if (Pred == CmpInst::ICMP_SLT && C == *C2)
3326 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
3327
3328 // (X + -1) <u C --> X <=u C (if X is never null)
3329 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3330 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3331 if (llvm::isKnownNonZero(X, Q))
3332 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
3333 }
3334
3335 if (!Add->hasOneUse())
3336 return nullptr;
3337
3338 // X+C <u C2 -> (X & -C2) == C
3339 // iff C & (C2-1) == 0
3340 // C2 is a power of 2
3341 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3342 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
3344
3345 // X+C2 <u C -> (X & C) == 2C
3346 // iff C == -(C2)
3347 // C2 is a power of 2
3348 if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)
3349 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, C),
3350 ConstantInt::get(Ty, C * 2));
3351
3352 // X+C >u C2 -> (X & ~C2) != C
3353 // iff C & C2 == 0
3354 // C2+1 is a power of 2
3355 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3356 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
3358
3359 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3360 // to the ult form.
3361 // X+C2 >u C -> X+(C2-C-1) <u ~C
3362 if (Pred == ICmpInst::ICMP_UGT)
3363 return new ICmpInst(ICmpInst::ICMP_ULT,
3364 Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
3365 ConstantInt::get(Ty, ~C));
3366
3367 // zext(V) + C2 pred C -> V + C3 pred' C4
3368 Value *V;
3369 if (match(X, m_ZExt(m_Value(V)))) {
3370 Type *NewCmpTy = V->getType();
3371 unsigned NewCmpBW = NewCmpTy->getScalarSizeInBits();
3372 if (shouldChangeType(Ty, NewCmpTy)) {
3373 ConstantRange SrcCR = CR.truncate(NewCmpBW, TruncInst::NoUnsignedWrap);
3374 CmpInst::Predicate EquivPred;
3375 APInt EquivInt;
3376 APInt EquivOffset;
3377
3378 SrcCR.getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
3379 return new ICmpInst(
3380 EquivPred,
3381 EquivOffset.isZero()
3382 ? V
3383 : Builder.CreateAdd(V, ConstantInt::get(NewCmpTy, EquivOffset)),
3384 ConstantInt::get(NewCmpTy, EquivInt));
3385 }
3386 }
3387
3388 return nullptr;
3389}
3390
3392 Value *&RHS, ConstantInt *&Less,
3393 ConstantInt *&Equal,
3394 ConstantInt *&Greater) {
3395 // TODO: Generalize this to work with other comparison idioms or ensure
3396 // they get canonicalized into this form.
3397
3398 // select i1 (a == b),
3399 // i32 Equal,
3400 // i32 (select i1 (a < b), i32 Less, i32 Greater)
3401 // where Equal, Less and Greater are placeholders for any three constants.
3402 CmpPredicate PredA;
3403 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
3404 !ICmpInst::isEquality(PredA))
3405 return false;
3406 Value *EqualVal = SI->getTrueValue();
3407 Value *UnequalVal = SI->getFalseValue();
3408 // We still can get non-canonical predicate here, so canonicalize.
3409 if (PredA == ICmpInst::ICMP_NE)
3410 std::swap(EqualVal, UnequalVal);
3411 if (!match(EqualVal, m_ConstantInt(Equal)))
3412 return false;
3413 CmpPredicate PredB;
3414 Value *LHS2, *RHS2;
3415 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
3416 m_ConstantInt(Less), m_ConstantInt(Greater))))
3417 return false;
3418 // We can get predicate mismatch here, so canonicalize if possible:
3419 // First, ensure that 'LHS' match.
3420 if (LHS2 != LHS) {
3421 // x sgt y <--> y slt x
3422 std::swap(LHS2, RHS2);
3423 PredB = ICmpInst::getSwappedPredicate(PredB);
3424 }
3425 if (LHS2 != LHS)
3426 return false;
3427 // We also need to canonicalize 'RHS'.
3428 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
3429 // x sgt C-1 <--> x sge C <--> not(x slt C)
3430 auto FlippedStrictness =
3432 if (!FlippedStrictness)
3433 return false;
3434 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3435 "basic correctness failure");
3436 RHS2 = FlippedStrictness->second;
3437 // And kind-of perform the result swap.
3438 std::swap(Less, Greater);
3439 PredB = ICmpInst::ICMP_SLT;
3440 }
3441 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3442}
3443
3446 ConstantInt *C) {
3447
3448 assert(C && "Cmp RHS should be a constant int!");
3449 // If we're testing a constant value against the result of a three way
3450 // comparison, the result can be expressed directly in terms of the
3451 // original values being compared. Note: We could possibly be more
3452 // aggressive here and remove the hasOneUse test. The original select is
3453 // really likely to simplify or sink when we remove a test of the result.
3454 Value *OrigLHS, *OrigRHS;
3455 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3456 if (Cmp.hasOneUse() &&
3457 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
3458 C3GreaterThan)) {
3459 assert(C1LessThan && C2Equal && C3GreaterThan);
3460
3461 bool TrueWhenLessThan = ICmpInst::compare(
3462 C1LessThan->getValue(), C->getValue(), Cmp.getPredicate());
3463 bool TrueWhenEqual = ICmpInst::compare(C2Equal->getValue(), C->getValue(),
3464 Cmp.getPredicate());
3465 bool TrueWhenGreaterThan = ICmpInst::compare(
3466 C3GreaterThan->getValue(), C->getValue(), Cmp.getPredicate());
3467
3468 // This generates the new instruction that will replace the original Cmp
3469 // Instruction. Instead of enumerating the various combinations when
3470 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3471 // false, we rely on chaining of ORs and future passes of InstCombine to
3472 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3473
3474 // When none of the three constants satisfy the predicate for the RHS (C),
3475 // the entire original Cmp can be simplified to a false.
3476 Value *Cond = Builder.getFalse();
3477 if (TrueWhenLessThan)
3478 Cond = Builder.CreateOr(
3479 Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT, OrigLHS, OrigRHS));
3480 if (TrueWhenEqual)
3481 Cond = Builder.CreateOr(
3482 Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ, OrigLHS, OrigRHS));
3483 if (TrueWhenGreaterThan)
3484 Cond = Builder.CreateOr(
3485 Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT, OrigLHS, OrigRHS));
3486
3487 return replaceInstUsesWith(Cmp, Cond);
3488 }
3489 return nullptr;
3490}
3491
3493 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3494 if (!Bitcast)
3495 return nullptr;
3496
3497 ICmpInst::Predicate Pred = Cmp.getPredicate();
3498 Value *Op1 = Cmp.getOperand(1);
3499 Value *BCSrcOp = Bitcast->getOperand(0);
3500 Type *SrcType = Bitcast->getSrcTy();
3501 Type *DstType = Bitcast->getType();
3502
3503 // Make sure the bitcast doesn't change between scalar and vector and
3504 // doesn't change the number of vector elements.
3505 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3506 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3507 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3508 Value *X;
3509 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
3510 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3511 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3512 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3513 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3514 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3515 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3516 match(Op1, m_Zero()))
3517 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3518
3519 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3520 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
3521 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
3522
3523 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3524 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
3525 return new ICmpInst(Pred, X,
3526 ConstantInt::getAllOnesValue(X->getType()));
3527 }
3528
3529 // Zero-equality checks are preserved through unsigned floating-point casts:
3530 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3531 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3532 if (match(BCSrcOp, m_UIToFP(m_Value(X))))
3533 if (Cmp.isEquality() && match(Op1, m_Zero()))
3534 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3535
3536 const APInt *C;
3537 bool TrueIfSigned;
3538 if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse()) {
3539 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3540 // the FP extend/truncate because that cast does not change the sign-bit.
3541 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3542 // The sign-bit is always the most significant bit in those types.
3543 if (isSignBitCheck(Pred, *C, TrueIfSigned) &&
3544 (match(BCSrcOp, m_FPExt(m_Value(X))) ||
3545 match(BCSrcOp, m_FPTrunc(m_Value(X))))) {
3546 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3547 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3548 Type *XType = X->getType();
3549
3550 // We can't currently handle Power style floating point operations here.
3551 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3552 Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
3553 if (auto *XVTy = dyn_cast<VectorType>(XType))
3554 NewType = VectorType::get(NewType, XVTy->getElementCount());
3555 Value *NewBitcast = Builder.CreateBitCast(X, NewType);
3556 if (TrueIfSigned)
3557 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3558 ConstantInt::getNullValue(NewType));
3559 else
3560 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3562 }
3563 }
3564
3565 // icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)
3566 Type *FPType = SrcType->getScalarType();
3567 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3568 Attribute::NoImplicitFloat) &&
3569 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3570 FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();
3571 if (Mask & (fcInf | fcZero)) {
3572 if (Pred == ICmpInst::ICMP_NE)
3573 Mask = ~Mask;
3574 return replaceInstUsesWith(Cmp,
3575 Builder.createIsFPClass(BCSrcOp, Mask));
3576 }
3577 }
3578 }
3579 }
3580
3581 // Fold the canonicalized form of vector_reduce_or if the arg is
3582 // get_active_lane mask.
3583 // icmp ne (bitcast <N x i1> to iN (get_active_lane_mask(l, h))), 0 ->
3584 // icmp ult l, h
3585 // icmp eq (bitcast <N x i1> to iN (get_active_lane_mask(l, h))), 0 ->
3586 // icmp uge l, h
3587 Value *Upper, *Lower;
3589 m_Value(Lower), m_Value(Upper))) &&
3590 match(Op1, m_Zero()) && DstType->isIntegerTy()) {
3591 if (Pred == ICmpInst::ICMP_NE)
3592 return new ICmpInst(ICmpInst::ICMP_ULT, Lower, Upper);
3593 if (Pred == ICmpInst::ICMP_EQ)
3594 return new ICmpInst(ICmpInst::ICMP_UGE, Lower, Upper);
3595 }
3596
3597 const APInt *C;
3598 if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3599 !SrcType->isIntOrIntVectorTy())
3600 return nullptr;
3601
3602 // If this is checking if all elements of a vector compare are set or not,
3603 // invert the casted vector equality compare and test if all compare
3604 // elements are clear or not. Compare against zero is generally easier for
3605 // analysis and codegen.
3606 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3607 // Example: are all elements equal? --> are zero elements not equal?
3608 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3609 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3610 if (Value *NotBCSrcOp =
3611 getFreelyInverted(BCSrcOp, BCSrcOp->hasOneUse(), &Builder)) {
3612 Value *Cast = Builder.CreateBitCast(NotBCSrcOp, DstType);
3613 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3614 }
3615 }
3616
3617 // If this is checking if all elements of an extended vector are clear or not,
3618 // compare in a narrow type to eliminate the extend:
3619 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3620 Value *X;
3621 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3622 match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3623 if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3624 Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3625 Value *NewCast = Builder.CreateBitCast(X, NewType);
3626 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3627 }
3628 }
3629
3630 // Folding: icmp <pred> iN X, C
3631 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3632 // and C is a splat of a K-bit pattern
3633 // and SC is a constant vector = <C', C', C', ..., C'>
3634 // Into:
3635 // %E = extractelement <M x iK> %vec, i32 C'
3636 // icmp <pred> iK %E, trunc(C)
3637 Value *Vec;
3638 ArrayRef<int> Mask;
3639 if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3640 // Check whether every element of Mask is the same constant
3641 if (all_equal(Mask)) {
3642 auto *VecTy = cast<VectorType>(SrcType);
3643 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3644 if (C->isSplat(EltTy->getBitWidth())) {
3645 // Fold the icmp based on the value of C
3646 // If C is M copies of an iK sized bit pattern,
3647 // then:
3648 // => %E = extractelement <N x iK> %vec, i64 Elem
3649 // icmp <pred> iK %SplatVal, <pattern>
3650 Value *Extract = Builder.CreateExtractElement(Vec, Mask[0]);
3651 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3652 return new ICmpInst(Pred, Extract, NewC);
3653 }
3654 }
3655 }
3656 return nullptr;
3657}
3658
3659/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3660/// where X is some kind of instruction.
3662 const APInt *C;
3663
3664 if (match(Cmp.getOperand(1), m_APInt(C))) {
3665 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3666 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3667 return I;
3668
3669 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3670 // For now, we only support constant integers while folding the
3671 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3672 // similar to the cases handled by binary ops above.
3673 if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3674 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3675 return I;
3676
3677 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3678 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3679 return I;
3680
3681 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3683 return I;
3684
3685 {
3686 // icmp slt/sgt (extractvalue (frexp X), 1), C -->
3687 // fcmp olt/oge (fabs X), 2^ExpVal
3688 // slt -> olt, ExpVal = C-1; sgt -> oge, ExpVal = C.
3689 Value *X;
3690 if (match(Cmp.getOperand(0),
3693 ICmpInst::Predicate Pred = Cmp.getPredicate();
3694 APInt Exp;
3695 FCmpInst::Predicate NewPred;
3696 bool ValidPred = true;
3697
3698 switch (Pred) {
3699 case ICmpInst::ICMP_SLT:
3700 NewPred = FCmpInst::FCMP_OLT;
3701 Exp = *C - 1;
3702 break;
3703 case ICmpInst::ICMP_SGT:
3704 NewPred = FCmpInst::FCMP_OGE;
3705 Exp = *C;
3706 break;
3707 default:
3708 ValidPred = false;
3709 break;
3710 }
3711
3712 if (ValidPred) {
3713 const fltSemantics &Sem =
3714 X->getType()->getScalarType()->getFltSemantics();
3715 int MaxExp = APFloat::semanticsMaxExponent(Sem);
3716
3717 if (!Exp.isNegative() && Exp.sle(MaxExp + 1) &&
3718 isKnownNeverInfOrNaN(X, SQ.getWithInstruction(&Cmp))) {
3719 int ExpVal = static_cast<int>(Exp.getSExtValue());
3720 APFloat CmpConst = scalbn(APFloat::getOne(Sem), ExpVal,
3722 Value *Fabs = Builder.CreateFAbs(X);
3723 return new FCmpInst(NewPred, Fabs,
3724 ConstantFP::get(X->getType(), CmpConst));
3725 }
3726 }
3727 }
3728 }
3729
3730 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3731 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3732 // TODO: This checks one-use, but that is not strictly necessary.
3733 Value *Cmp0 = Cmp.getOperand(0);
3734 Value *X, *Y;
3735 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3736 (match(Cmp0,
3738 m_Value(X), m_Value(Y)))) ||
3739 match(Cmp0,
3741 m_Value(X), m_Value(Y))))))
3742 return new ICmpInst(Cmp.getPredicate(), X, Y);
3743 }
3744
3745 if (match(Cmp.getOperand(1), m_APIntAllowPoison(C)))
3747
3748 return nullptr;
3749}
3750
3751/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3752/// icmp eq/ne BO, C.
3754 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3755 // TODO: Some of these folds could work with arbitrary constants, but this
3756 // function is limited to scalar and vector splat constants.
3757 if (!Cmp.isEquality())
3758 return nullptr;
3759
3760 ICmpInst::Predicate Pred = Cmp.getPredicate();
3761 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3762 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3763 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3764
3765 switch (BO->getOpcode()) {
3766 case Instruction::SRem:
3767 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3768 if (C.isZero() && BO->hasOneUse()) {
3769 const APInt *BOC;
3770 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3771 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3772 return new ICmpInst(Pred, NewRem,
3774 }
3775 }
3776 break;
3777 case Instruction::Add: {
3778 // (A + C2) == C --> A == (C - C2)
3779 // (A + C2) != C --> A != (C - C2)
3780 // TODO: Remove the one-use limitation? See discussion in D58633.
3781 if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
3782 if (BO->hasOneUse())
3783 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
3784 } else if (C.isZero()) {
3785 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3786 // efficiently invertible, or if the add has just this one use.
3787 if (Value *NegVal = dyn_castNegVal(BOp1))
3788 return new ICmpInst(Pred, BOp0, NegVal);
3789 if (Value *NegVal = dyn_castNegVal(BOp0))
3790 return new ICmpInst(Pred, NegVal, BOp1);
3791 if (BO->hasOneUse()) {
3792 // (add nuw A, B) != 0 -> (or A, B) != 0
3793 if (match(BO, m_NUWAdd(m_Value(), m_Value()))) {
3794 Value *Or = Builder.CreateOr(BOp0, BOp1);
3795 return new ICmpInst(Pred, Or, Constant::getNullValue(BO->getType()));
3796 }
3797 Value *Neg = Builder.CreateNeg(BOp1);
3798 Neg->takeName(BO);
3799 return new ICmpInst(Pred, BOp0, Neg);
3800 }
3801 }
3802 break;
3803 }
3804 case Instruction::Xor:
3805 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3806 // For the xor case, we can xor two constants together, eliminating
3807 // the explicit xor.
3808 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3809 } else if (C.isZero()) {
3810 // Replace ((xor A, B) != 0) with (A != B)
3811 return new ICmpInst(Pred, BOp0, BOp1);
3812 }
3813 break;
3814 case Instruction::Or: {
3815 const APInt *BOC;
3816 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3817 // Comparing if all bits outside of a constant mask are set?
3818 // Replace (X | C) == -1 with (X & ~C) == ~C.
3819 // This removes the -1 constant.
3821 Value *And = Builder.CreateAnd(BOp0, NotBOC);
3822 return new ICmpInst(Pred, And, NotBOC);
3823 }
3824 // (icmp eq (or (select cond, 0, NonZero), Other), 0)
3825 // -> (and cond, (icmp eq Other, 0))
3826 // (icmp ne (or (select cond, NonZero, 0), Other), 0)
3827 // -> (or cond, (icmp ne Other, 0))
3828 Value *Cond, *TV, *FV, *Other, *Sel;
3829 if (C.isZero() &&
3830 match(BO,
3833 m_Value(FV))),
3834 m_Value(Other)))) &&
3835 Cond->getType() == Cmp.getType()) {
3836 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3837 // Easy case is if eq/ne matches whether 0 is trueval/falseval.
3838 if (Pred == ICmpInst::ICMP_EQ
3839 ? (match(TV, m_Zero()) && isKnownNonZero(FV, Q))
3840 : (match(FV, m_Zero()) && isKnownNonZero(TV, Q))) {
3841 Value *Cmp = Builder.CreateICmp(
3842 Pred, Other, Constant::getNullValue(Other->getType()));
3844 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3845 Cond);
3846 }
3847 // Harder case is if eq/ne matches whether 0 is falseval/trueval. In this
3848 // case we need to invert the select condition so we need to be careful to
3849 // avoid creating extra instructions.
3850 // (icmp ne (or (select cond, 0, NonZero), Other), 0)
3851 // -> (or (not cond), (icmp ne Other, 0))
3852 // (icmp eq (or (select cond, NonZero, 0), Other), 0)
3853 // -> (and (not cond), (icmp eq Other, 0))
3854 //
3855 // Only do this if the inner select has one use, in which case we are
3856 // replacing `select` with `(not cond)`. Otherwise, we will create more
3857 // uses. NB: Trying to freely invert cond doesn't make sense here, as if
3858 // cond was freely invertable, the select arms would have been inverted.
3859 if (Sel->hasOneUse() &&
3860 (Pred == ICmpInst::ICMP_EQ
3861 ? (match(FV, m_Zero()) && isKnownNonZero(TV, Q))
3862 : (match(TV, m_Zero()) && isKnownNonZero(FV, Q)))) {
3863 Value *NotCond = Builder.CreateNot(Cond);
3864 Value *Cmp = Builder.CreateICmp(
3865 Pred, Other, Constant::getNullValue(Other->getType()));
3867 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3868 NotCond);
3869 }
3870 }
3871 break;
3872 }
3873 case Instruction::UDiv:
3874 case Instruction::SDiv:
3875 if (BO->isExact()) {
3876 // div exact X, Y eq/ne 0 -> X eq/ne 0
3877 // div exact X, Y eq/ne 1 -> X eq/ne Y
3878 // div exact X, Y eq/ne C ->
3879 // if Y * C never-overflow && OneUse:
3880 // -> Y * C eq/ne X
3881 if (C.isZero())
3882 return new ICmpInst(Pred, BOp0, Constant::getNullValue(BO->getType()));
3883 else if (C.isOne())
3884 return new ICmpInst(Pred, BOp0, BOp1);
3885 else if (BO->hasOneUse()) {
3887 Instruction::Mul, BO->getOpcode() == Instruction::SDiv, BOp1,
3888 Cmp.getOperand(1), BO);
3890 Value *YC =
3891 Builder.CreateMul(BOp1, ConstantInt::get(BO->getType(), C));
3892 return new ICmpInst(Pred, YC, BOp0);
3893 }
3894 }
3895 }
3896 if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3897 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3898 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3899 return new ICmpInst(NewPred, BOp1, BOp0);
3900 }
3901 break;
3902 default:
3903 break;
3904 }
3905 return nullptr;
3906}
3907
3909 const APInt &CRhs,
3910 InstCombiner::BuilderTy &Builder,
3911 const SimplifyQuery &Q) {
3912 assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3913 "Non-ctpop intrin in ctpop fold");
3914 if (!CtpopLhs->hasOneUse())
3915 return nullptr;
3916
3917 // Power of 2 test:
3918 // isPow2OrZero : ctpop(X) u< 2
3919 // isPow2 : ctpop(X) == 1
3920 // NotPow2OrZero: ctpop(X) u> 1
3921 // NotPow2 : ctpop(X) != 1
3922 // If we know any bit of X can be folded to:
3923 // IsPow2 : X & (~Bit) == 0
3924 // NotPow2 : X & (~Bit) != 0
3925 const ICmpInst::Predicate Pred = I.getPredicate();
3926 if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3927 (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3928 Value *Op = CtpopLhs->getArgOperand(0);
3929 KnownBits OpKnown = computeKnownBits(Op, Q.DL, Q.AC, Q.CtxI, Q.DT);
3930 // No need to check for count > 1, that should be already constant folded.
3931 if (OpKnown.countMinPopulation() == 1) {
3932 Value *And = Builder.CreateAnd(
3933 Op, Constant::getIntegerValue(Op->getType(), ~(OpKnown.One)));
3934 return new ICmpInst(
3935 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3938 And, Constant::getNullValue(Op->getType()));
3939 }
3940 }
3941
3942 return nullptr;
3943}
3944
3945/// Fold an equality icmp with LLVM intrinsic and constant operand.
3947 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3948 Type *Ty = II->getType();
3949 unsigned BitWidth = C.getBitWidth();
3950 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3951
3952 switch (II->getIntrinsicID()) {
3953 case Intrinsic::abs:
3954 // abs(A) == 0 -> A == 0
3955 // abs(A) == INT_MIN -> A == INT_MIN
3956 if (C.isZero() || C.isMinSignedValue())
3957 return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3958 break;
3959
3960 case Intrinsic::bswap:
3961 // bswap(A) == C -> A == bswap(C)
3962 return new ICmpInst(Pred, II->getArgOperand(0),
3963 ConstantInt::get(Ty, C.byteSwap()));
3964
3965 case Intrinsic::bitreverse:
3966 // bitreverse(A) == C -> A == bitreverse(C)
3967 return new ICmpInst(Pred, II->getArgOperand(0),
3968 ConstantInt::get(Ty, C.reverseBits()));
3969
3970 case Intrinsic::ctlz:
3971 case Intrinsic::cttz: {
3972 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3973 if (C == BitWidth)
3974 return new ICmpInst(Pred, II->getArgOperand(0),
3976
3977 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3978 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3979 // Limit to one use to ensure we don't increase instruction count.
3980 unsigned Num = C.getLimitedValue(BitWidth);
3981 if (Num != BitWidth && II->hasOneUse()) {
3982 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3983 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3984 : APInt::getHighBitsSet(BitWidth, Num + 1);
3985 APInt Mask2 = IsTrailing
3988 return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
3989 ConstantInt::get(Ty, Mask2));
3990 }
3991 break;
3992 }
3993
3994 case Intrinsic::ctpop: {
3995 // popcount(A) == 0 -> A == 0 and likewise for !=
3996 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3997 bool IsZero = C.isZero();
3998 if (IsZero || C == BitWidth)
3999 return new ICmpInst(Pred, II->getArgOperand(0),
4000 IsZero ? Constant::getNullValue(Ty)
4002
4003 break;
4004 }
4005
4006 case Intrinsic::fshl:
4007 case Intrinsic::fshr:
4008 if (II->getArgOperand(0) == II->getArgOperand(1)) {
4009 const APInt *RotAmtC;
4010 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
4011 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
4012 if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
4013 return new ICmpInst(Pred, II->getArgOperand(0),
4014 II->getIntrinsicID() == Intrinsic::fshl
4015 ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
4016 : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
4017 }
4018 break;
4019
4020 case Intrinsic::umax:
4021 case Intrinsic::uadd_sat: {
4022 // uadd.sat(a, b) == 0 -> (a | b) == 0
4023 // umax(a, b) == 0 -> (a | b) == 0
4024 if (C.isZero() && II->hasOneUse()) {
4025 Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));
4026 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
4027 }
4028 break;
4029 }
4030
4031 case Intrinsic::ssub_sat:
4032 // ssub.sat(a, b) == 0 -> a == b
4033 //
4034 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4035 // (because 1 saturates to 0). Just skip the optimization for i1.
4036 if (C.isZero() && II->getType()->getScalarSizeInBits() > 1)
4037 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4038 break;
4039 case Intrinsic::usub_sat: {
4040 // usub.sat(a, b) == 0 -> a <= b
4041 if (C.isZero()) {
4042 ICmpInst::Predicate NewPred =
4044 return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
4045 }
4046 break;
4047 }
4048 default:
4049 break;
4050 }
4051
4052 return nullptr;
4053}
4054
4055/// Fold an icmp with LLVM intrinsics
4056static Instruction *
4058 InstCombiner::BuilderTy &Builder) {
4059 assert(Cmp.isEquality());
4060
4061 ICmpInst::Predicate Pred = Cmp.getPredicate();
4062 Value *Op0 = Cmp.getOperand(0);
4063 Value *Op1 = Cmp.getOperand(1);
4064 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
4065 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
4066 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
4067 return nullptr;
4068
4069 switch (IIOp0->getIntrinsicID()) {
4070 case Intrinsic::bswap:
4071 case Intrinsic::bitreverse:
4072 // If both operands are byte-swapped or bit-reversed, just compare the
4073 // original values.
4074 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4075 case Intrinsic::fshl:
4076 case Intrinsic::fshr: {
4077 // If both operands are rotated by same amount, just compare the
4078 // original values.
4079 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
4080 break;
4081 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
4082 break;
4083 if (IIOp0->getOperand(2) == IIOp1->getOperand(2))
4084 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4085
4086 // rotate(X, AmtX) == rotate(Y, AmtY)
4087 // -> rotate(X, AmtX - AmtY) == Y
4088 // Do this if either both rotates have one use or if only one has one use
4089 // and AmtX/AmtY are constants.
4090 const unsigned BW = IIOp0->getType()->getScalarSizeInBits();
4091 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
4092 if (OneUses == 2 ||
4093 (OneUses == 1 && match(IIOp0->getOperand(2), m_ImmConstant()) &&
4094 match(IIOp1->getOperand(2), m_ImmConstant()))) {
4095
4096 // Only valid assuming (2**BW) % BW == 0, which only holds for powers
4097 // of two.
4098 if (isPowerOf2_32(BW)) {
4099 Value *SubAmt =
4100 Builder.CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));
4101 Value *CombinedRotate = Builder.CreateIntrinsic(
4102 Op0->getType(), IIOp0->getIntrinsicID(),
4103 {IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});
4104 return new ICmpInst(Pred, IIOp1->getOperand(0), CombinedRotate);
4105 }
4106 }
4107 } break;
4108 default:
4109 break;
4110 }
4111
4112 return nullptr;
4113}
4114
4115/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
4116/// where X is some kind of instruction and C is AllowPoison.
4117/// TODO: Move more folds which allow poison to this function.
4120 const APInt &C) {
4121 const ICmpInst::Predicate Pred = Cmp.getPredicate();
4122 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
4123 switch (II->getIntrinsicID()) {
4124 default:
4125 break;
4126 case Intrinsic::fshl:
4127 case Intrinsic::fshr:
4128 if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
4129 // (rot X, ?) == 0/-1 --> X == 0/-1
4130 if (C.isZero() || C.isAllOnes())
4131 return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
4132 }
4133 break;
4134 }
4135 }
4136
4137 return nullptr;
4138}
4139
4140/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
4142 BinaryOperator *BO,
4143 const APInt &C) {
4144 switch (BO->getOpcode()) {
4145 case Instruction::Xor:
4146 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
4147 return I;
4148 break;
4149 case Instruction::And:
4150 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
4151 return I;
4152 break;
4153 case Instruction::Or:
4154 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
4155 return I;
4156 break;
4157 case Instruction::Mul:
4158 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
4159 return I;
4160 break;
4161 case Instruction::Shl:
4162 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
4163 return I;
4164 break;
4165 case Instruction::LShr:
4166 case Instruction::AShr:
4167 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
4168 return I;
4169 break;
4170 case Instruction::SRem:
4171 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
4172 return I;
4173 break;
4174 case Instruction::UDiv:
4175 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
4176 return I;
4177 [[fallthrough]];
4178 case Instruction::SDiv:
4179 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
4180 return I;
4181 break;
4182 case Instruction::Sub:
4183 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
4184 return I;
4185 break;
4186 case Instruction::Add:
4187 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
4188 return I;
4189 break;
4190 default:
4191 break;
4192 }
4193
4194 // TODO: These folds could be refactored to be part of the above calls.
4196 return I;
4197
4198 // Fall back to handling `icmp pred (select A ? C1 : C2) binop (select B ? C3
4199 // : C4), C5` pattern, by computing a truth table of the four constant
4200 // variants.
4202}
4203
4204static Instruction *
4206 const APInt &C,
4207 InstCombiner::BuilderTy &Builder) {
4208 // This transform may end up producing more than one instruction for the
4209 // intrinsic, so limit it to one user of the intrinsic.
4210 if (!II->hasOneUse())
4211 return nullptr;
4212
4213 // Let Y = [add/sub]_sat(X, C) pred C2
4214 // SatVal = The saturating value for the operation
4215 // WillWrap = Whether or not the operation will underflow / overflow
4216 // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
4217 // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
4218 //
4219 // When (SatVal pred C2) is true, then
4220 // Y = WillWrap ? true : ((X binop C) pred C2)
4221 // => Y = WillWrap || ((X binop C) pred C2)
4222 // else
4223 // Y = WillWrap ? false : ((X binop C) pred C2)
4224 // => Y = !WillWrap ? ((X binop C) pred C2) : false
4225 // => Y = !WillWrap && ((X binop C) pred C2)
4226 Value *Op0 = II->getOperand(0);
4227 Value *Op1 = II->getOperand(1);
4228
4229 const APInt *COp1;
4230 // This transform only works when the intrinsic has an integral constant or
4231 // splat vector as the second operand.
4232 if (!match(Op1, m_APInt(COp1)))
4233 return nullptr;
4234
4235 APInt SatVal;
4236 switch (II->getIntrinsicID()) {
4237 default:
4239 "This function only works with usub_sat and uadd_sat for now!");
4240 case Intrinsic::uadd_sat:
4241 SatVal = APInt::getAllOnes(C.getBitWidth());
4242 break;
4243 case Intrinsic::usub_sat:
4244 SatVal = APInt::getZero(C.getBitWidth());
4245 break;
4246 }
4247
4248 // Check (SatVal pred C2)
4249 bool SatValCheck = ICmpInst::compare(SatVal, C, Pred);
4250
4251 // !WillWrap.
4253 II->getBinaryOp(), *COp1, II->getNoWrapKind());
4254
4255 // WillWrap.
4256 if (SatValCheck)
4257 C1 = C1.inverse();
4258
4260 if (II->getBinaryOp() == Instruction::Add)
4261 C2 = C2.sub(*COp1);
4262 else
4263 C2 = C2.add(*COp1);
4264
4265 Instruction::BinaryOps CombiningOp =
4266 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4267
4268 std::optional<ConstantRange> Combination;
4269 if (CombiningOp == Instruction::BinaryOps::Or)
4270 Combination = C1.exactUnionWith(C2);
4271 else /* CombiningOp == Instruction::BinaryOps::And */
4272 Combination = C1.exactIntersectWith(C2);
4273
4274 if (!Combination)
4275 return nullptr;
4276
4277 CmpInst::Predicate EquivPred;
4278 APInt EquivInt;
4279 APInt EquivOffset;
4280
4281 Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
4282
4283 return new ICmpInst(
4284 EquivPred,
4285 Builder.CreateAdd(Op0, ConstantInt::get(Op1->getType(), EquivOffset)),
4286 ConstantInt::get(Op1->getType(), EquivInt));
4287}
4288
4289static Instruction *
4291 const APInt &C,
4292 InstCombiner::BuilderTy &Builder) {
4293 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4294 switch (Pred) {
4295 case ICmpInst::ICMP_EQ:
4296 case ICmpInst::ICMP_NE:
4297 if (C.isZero())
4298 NewPredicate = Pred;
4299 else if (C.isOne())
4300 NewPredicate =
4302 else if (C.isAllOnes())
4303 NewPredicate =
4305 break;
4306
4307 case ICmpInst::ICMP_SGT:
4308 if (C.isAllOnes())
4309 NewPredicate = ICmpInst::ICMP_UGE;
4310 else if (C.isZero())
4311 NewPredicate = ICmpInst::ICMP_UGT;
4312 break;
4313
4314 case ICmpInst::ICMP_SLT:
4315 if (C.isZero())
4316 NewPredicate = ICmpInst::ICMP_ULT;
4317 else if (C.isOne())
4318 NewPredicate = ICmpInst::ICMP_ULE;
4319 break;
4320
4321 case ICmpInst::ICMP_ULT:
4322 if (C.ugt(1))
4323 NewPredicate = ICmpInst::ICMP_UGE;
4324 break;
4325
4326 case ICmpInst::ICMP_UGT:
4327 if (!C.isZero() && !C.isAllOnes())
4328 NewPredicate = ICmpInst::ICMP_ULT;
4329 break;
4330
4331 default:
4332 break;
4333 }
4334
4335 if (!NewPredicate)
4336 return nullptr;
4337
4338 if (I->getIntrinsicID() == Intrinsic::scmp)
4339 NewPredicate = ICmpInst::getSignedPredicate(*NewPredicate);
4340 Value *LHS = I->getOperand(0);
4341 Value *RHS = I->getOperand(1);
4342 return new ICmpInst(*NewPredicate, LHS, RHS);
4343}
4344
4345/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
4348 const APInt &C) {
4349 ICmpInst::Predicate Pred = Cmp.getPredicate();
4350
4351 // Handle folds that apply for any kind of icmp.
4352 switch (II->getIntrinsicID()) {
4353 default:
4354 break;
4355 case Intrinsic::uadd_sat:
4356 case Intrinsic::usub_sat:
4357 if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(
4358 Pred, cast<SaturatingInst>(II), C, Builder))
4359 return Folded;
4360 break;
4361 case Intrinsic::ctpop: {
4362 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
4363 if (Instruction *R = foldCtpopPow2Test(Cmp, II, C, Builder, Q))
4364 return R;
4365 } break;
4366 case Intrinsic::scmp:
4367 case Intrinsic::ucmp:
4368 if (auto *Folded = foldICmpOfCmpIntrinsicWithConstant(Pred, II, C, Builder))
4369 return Folded;
4370 break;
4371 }
4372
4373 if (Cmp.isEquality())
4374 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
4375
4376 Type *Ty = II->getType();
4377 unsigned BitWidth = C.getBitWidth();
4378 switch (II->getIntrinsicID()) {
4379 case Intrinsic::ctpop: {
4380 // (ctpop X > BitWidth - 1) --> X == -1
4381 Value *X = II->getArgOperand(0);
4382 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
4383 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
4385 // (ctpop X < BitWidth) --> X != -1
4386 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
4387 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
4389 break;
4390 }
4391 case Intrinsic::ctlz: {
4392 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
4393 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4394 unsigned Num = C.getLimitedValue();
4395 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
4396 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
4397 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4398 }
4399
4400 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
4401 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4402 unsigned Num = C.getLimitedValue();
4404 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
4405 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4406 }
4407 break;
4408 }
4409 case Intrinsic::cttz: {
4410 // Limit to one use to ensure we don't increase instruction count.
4411 if (!II->hasOneUse())
4412 return nullptr;
4413
4414 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
4415 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4416 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
4417 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
4418 Builder.CreateAnd(II->getArgOperand(0), Mask),
4420 }
4421
4422 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
4423 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4424 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
4425 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
4426 Builder.CreateAnd(II->getArgOperand(0), Mask),
4428 }
4429 break;
4430 }
4431 case Intrinsic::ssub_sat:
4432 // ssub.sat(a, b) spred 0 -> a spred b
4433 //
4434 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4435 // (because 1 saturates to 0). Just skip the optimization for i1.
4436 if (ICmpInst::isSigned(Pred) && C.getBitWidth() > 1) {
4437 if (C.isZero())
4438 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4439 // X s<= 0 is cannonicalized to X s< 1
4440 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
4441 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(0),
4442 II->getArgOperand(1));
4443 // X s>= 0 is cannonicalized to X s> -1
4444 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
4445 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(0),
4446 II->getArgOperand(1));
4447 }
4448 break;
4449 case Intrinsic::abs: {
4450 if (!II->hasOneUse())
4451 return nullptr;
4452
4453 Value *X = II->getArgOperand(0);
4454
4455 // If C >= 0:
4456 // abs(X) u> C --> X + C u> 2 * C
4457 if (Pred == CmpInst::ICMP_UGT && C.isNonNegative()) {
4458 return new ICmpInst(ICmpInst::ICMP_UGT,
4459 Builder.CreateAdd(X, ConstantInt::get(Ty, C)),
4460 ConstantInt::get(Ty, 2 * C));
4461 }
4462
4463 // If C >= 1:
4464 // abs(X) u< C --> X + (C - 1) u<= 2 * (C - 1)
4465 if (Pred == CmpInst::ICMP_ULT && C.sge(1))
4466 return new ICmpInst(ICmpInst::ICMP_ULE,
4467 Builder.CreateAdd(X, ConstantInt::get(Ty, C - 1)),
4468 ConstantInt::get(Ty, 2 * (C - 1)));
4469
4470 break;
4471 }
4472 default:
4473 break;
4474 }
4475
4476 return nullptr;
4477}
4478
4479/// Handle icmp with constant (but not simple integer constant) RHS.
4481 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4482 Constant *RHSC = dyn_cast<Constant>(Op1);
4484 if (!RHSC || !LHSI)
4485 return nullptr;
4486
4487 switch (LHSI->getOpcode()) {
4488 case Instruction::IntToPtr:
4489 // icmp pred inttoptr(X), null -> icmp pred X, null pointer value
4490 if (isa<ConstantPointerNull>(RHSC)) {
4491 Type *IntPtrTy = DL.getIntPtrType(RHSC->getType());
4492 if (IntPtrTy == LHSI->getOperand(0)->getType()) {
4493 APInt NullPtrValue =
4494 DL.getNullPtrValue(RHSC->getType()->getPointerAddressSpace());
4495 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
4496 Constant::getIntegerValue(IntPtrTy, NullPtrValue));
4497 }
4498 }
4499 break;
4500
4501 case Instruction::Load:
4502 // Try to optimize things like "A[i] > 4" to index computations.
4503 if (GetElementPtrInst *GEP =
4505 if (Instruction *Res =
4507 return Res;
4508 break;
4509 }
4510
4511 return nullptr;
4512}
4513
4515 Value *RHS, const ICmpInst &I) {
4516 // Try to fold the comparison into the select arms, which will cause the
4517 // select to be converted into a logical and/or.
4518 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
4519 if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
4520 return Res;
4521 if (std::optional<bool> Impl = isImpliedCondition(
4522 SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
4523 return ConstantInt::get(I.getType(), *Impl);
4524 return nullptr;
4525 };
4526
4527 ConstantInt *CI = nullptr;
4528 Value *Op1 = SimplifyOp(SI->getOperand(1), true);
4529 if (Op1)
4530 CI = dyn_cast<ConstantInt>(Op1);
4531
4532 Value *Op2 = SimplifyOp(SI->getOperand(2), false);
4533 if (Op2)
4534 CI = dyn_cast<ConstantInt>(Op2);
4535
4536 auto Simplifies = [&](Value *Op, unsigned Idx) {
4537 // A comparison of ucmp/scmp with a constant will fold into an icmp.
4538 const APInt *Dummy;
4539 return Op ||
4540 (isa<CmpIntrinsic>(SI->getOperand(Idx)) &&
4541 SI->getOperand(Idx)->hasOneUse() && match(RHS, m_APInt(Dummy)));
4542 };
4543
4544 // We only want to perform this transformation if it will not lead to
4545 // additional code. This is true if either both sides of the select
4546 // fold to a constant (in which case the icmp is replaced with a select
4547 // which will usually simplify) or this is the only user of the
4548 // select (in which case we are trading a select+icmp for a simpler
4549 // select+icmp) or all uses of the select can be replaced based on
4550 // dominance information ("Global cases").
4551 bool Transform = false;
4552 if (Op1 && Op2)
4553 Transform = true;
4554 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4555 // Local case
4556 if (SI->hasOneUse())
4557 Transform = true;
4558 // Global cases
4559 else if (CI && !CI->isZero())
4560 // When Op1 is constant try replacing select with second operand.
4561 // Otherwise Op2 is constant and try replacing select with first
4562 // operand.
4563 Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
4564 }
4565 if (Transform) {
4566 if (!Op1)
4567 Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
4568 if (!Op2)
4569 Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
4570 return SelectInst::Create(SI->getOperand(0), Op1, Op2, "", nullptr, SI);
4571 }
4572
4573 // Fold icmp eq/ne X, select(icmp pred X, P, C1, C2)
4574 // When the select condition compares X with a constant P and the select
4575 // arms are constants C1/C2, we can fold to a set membership test.
4576 // Example: X == select(X >s 0, 2, 0) -> (X == 2) | (X == 0)
4577 // This is valid when C1 satisfies the condition (C1 >s 0) and C2 does not.
4578 if (ICmpInst::isEquality(Pred)) {
4579 CmpPredicate CondPred;
4580 const APInt *C1, *C2, *P;
4581 if (match(SI,
4582 m_OneUse(m_Select(m_ICmp(CondPred, m_Specific(RHS), m_APInt(P)),
4583 m_APInt(C1), m_APInt(C2))))) {
4584 bool C1SatisfiesCond = ICmpInst::compare(*C1, *P, CondPred);
4585 bool C2SatisfiesCond = ICmpInst::compare(*C2, *P, CondPred);
4586
4587 if (C1SatisfiesCond && !C2SatisfiesCond) {
4588 // X == select(cond, C1, C2) -> (X == C1) | (X == C2)
4589 // X != select(cond, C1, C2) -> (X != C1) & (X != C2)
4590 Value *Cmp1 = Builder.CreateICmp(Pred, RHS, SI->getTrueValue());
4591 Value *Cmp2 = Builder.CreateICmp(Pred, RHS, SI->getFalseValue());
4592 if (Pred == ICmpInst::ICMP_EQ)
4593 return BinaryOperator::CreateOr(Cmp1, Cmp2);
4594 return BinaryOperator::CreateAnd(Cmp1, Cmp2);
4595 }
4596 }
4597 }
4598
4599 return nullptr;
4600}
4601
4602// Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)
4603static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,
4604 unsigned Depth = 0) {
4605 if (Not ? match(V, m_NegatedPower2OrZero()) : match(V, m_LowBitMaskOrZero()))
4606 return true;
4607 if (V->getType()->getScalarSizeInBits() == 1)
4608 return true;
4610 return false;
4611 Value *X;
4613 if (!I)
4614 return false;
4615 switch (I->getOpcode()) {
4616 case Instruction::ZExt:
4617 // ZExt(Mask) is a Mask.
4618 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4619 case Instruction::SExt:
4620 // SExt(Mask) is a Mask.
4621 // SExt(~Mask) is a ~Mask.
4622 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4623 case Instruction::And:
4624 case Instruction::Or:
4625 // Mask0 | Mask1 is a Mask.
4626 // Mask0 & Mask1 is a Mask.
4627 // ~Mask0 | ~Mask1 is a ~Mask.
4628 // ~Mask0 & ~Mask1 is a ~Mask.
4629 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4630 isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4631 case Instruction::Xor:
4632 if (match(V, m_Not(m_Value(X))))
4633 return isMaskOrZero(X, !Not, Q, Depth);
4634
4635 // (X ^ -X) is a ~Mask
4636 if (Not)
4637 return match(V, m_c_Xor(m_Value(X), m_Neg(m_Deferred(X))));
4638 // (X ^ (X - 1)) is a Mask
4639 else
4640 return match(V, m_c_Xor(m_Value(X), m_Add(m_Deferred(X), m_AllOnes())));
4641 case Instruction::Select:
4642 // c ? Mask0 : Mask1 is a Mask.
4643 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4644 isMaskOrZero(I->getOperand(2), Not, Q, Depth);
4645 case Instruction::Shl:
4646 // (~Mask) << X is a ~Mask.
4647 return Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4648 case Instruction::LShr:
4649 // Mask >> X is a Mask.
4650 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4651 case Instruction::AShr:
4652 // Mask s>> X is a Mask.
4653 // ~Mask s>> X is a ~Mask.
4654 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4655 case Instruction::Add:
4656 // Pow2 - 1 is a Mask.
4657 if (!Not && match(I->getOperand(1), m_AllOnes()))
4658 return isKnownToBeAPowerOfTwo(I->getOperand(0), Q.DL, /*OrZero*/ true,
4659 Q.AC, Q.CtxI, Q.DT, Depth);
4660 break;
4661 case Instruction::Sub:
4662 // -Pow2 is a ~Mask.
4663 if (Not && match(I->getOperand(0), m_Zero()))
4664 return isKnownToBeAPowerOfTwo(I->getOperand(1), Q.DL, /*OrZero*/ true,
4665 Q.AC, Q.CtxI, Q.DT, Depth);
4666 break;
4667 case Instruction::Call: {
4668 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
4669 switch (II->getIntrinsicID()) {
4670 // min/max(Mask0, Mask1) is a Mask.
4671 // min/max(~Mask0, ~Mask1) is a ~Mask.
4672 case Intrinsic::umax:
4673 case Intrinsic::smax:
4674 case Intrinsic::umin:
4675 case Intrinsic::smin:
4676 return isMaskOrZero(II->getArgOperand(1), Not, Q, Depth) &&
4677 isMaskOrZero(II->getArgOperand(0), Not, Q, Depth);
4678
4679 // In the context of masks, bitreverse(Mask) == ~Mask
4680 case Intrinsic::bitreverse:
4681 return isMaskOrZero(II->getArgOperand(0), !Not, Q, Depth);
4682 default:
4683 break;
4684 }
4685 }
4686 break;
4687 }
4688 default:
4689 break;
4690 }
4691 return false;
4692}
4693
4694/// Some comparisons can be simplified.
4695/// In this case, we are looking for comparisons that look like
4696/// a check for a lossy truncation.
4697/// Folds:
4698/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
4699/// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask
4700/// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask
4701/// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask
4702/// Where Mask is some pattern that produces all-ones in low bits:
4703/// (-1 >> y)
4704/// ((-1 << y) >> y) <- non-canonical, has extra uses
4705/// ~(-1 << y)
4706/// ((1 << y) + (-1)) <- non-canonical, has extra uses
4707/// The Mask can be a constant, too.
4708/// For some predicates, the operands are commutative.
4709/// For others, x can only be on a specific side.
4711 Value *Op1, const SimplifyQuery &Q,
4712 InstCombiner &IC) {
4713
4714 ICmpInst::Predicate DstPred;
4715 switch (Pred) {
4717 // x & Mask == x
4718 // x & ~Mask == 0
4719 // ~x | Mask == -1
4720 // -> x u<= Mask
4721 // x & ~Mask == ~Mask
4722 // -> ~Mask u<= x
4724 break;
4726 // x & Mask != x
4727 // x & ~Mask != 0
4728 // ~x | Mask != -1
4729 // -> x u> Mask
4730 // x & ~Mask != ~Mask
4731 // -> ~Mask u> x
4733 break;
4735 // x & Mask u< x
4736 // -> x u> Mask
4737 // x & ~Mask u< ~Mask
4738 // -> ~Mask u> x
4740 break;
4742 // x & Mask u>= x
4743 // -> x u<= Mask
4744 // x & ~Mask u>= ~Mask
4745 // -> ~Mask u<= x
4747 break;
4749 // x & Mask s< x [iff Mask s>= 0]
4750 // -> x s> Mask
4751 // x & ~Mask s< ~Mask [iff ~Mask != 0]
4752 // -> ~Mask s> x
4754 break;
4756 // x & Mask s>= x [iff Mask s>= 0]
4757 // -> x s<= Mask
4758 // x & ~Mask s>= ~Mask [iff ~Mask != 0]
4759 // -> ~Mask s<= x
4761 break;
4762 default:
4763 // We don't support sgt,sle
4764 // ult/ugt are simplified to true/false respectively.
4765 return nullptr;
4766 }
4767
4768 Value *X, *M;
4769 // Put search code in lambda for early positive returns.
4770 auto IsLowBitMask = [&]() {
4771 if (match(Op0, m_c_And(m_Specific(Op1), m_Value(M)))) {
4772 X = Op1;
4773 // Look for: x & Mask pred x
4774 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4775 return !ICmpInst::isSigned(Pred) ||
4776 (match(M, m_NonNegative()) || isKnownNonNegative(M, Q));
4777 }
4778
4779 // Look for: x & ~Mask pred ~Mask
4780 if (isMaskOrZero(X, /*Not=*/true, Q)) {
4781 return !ICmpInst::isSigned(Pred) || isKnownNonZero(X, Q);
4782 }
4783 return false;
4784 }
4785 if (ICmpInst::isEquality(Pred) && match(Op1, m_AllOnes()) &&
4786 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(M))))) {
4787
4788 auto Check = [&]() {
4789 // Look for: ~x | Mask == -1
4790 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4791 if (Value *NotX =
4792 IC.getFreelyInverted(X, X->hasOneUse(), &IC.Builder)) {
4793 X = NotX;
4794 return true;
4795 }
4796 }
4797 return false;
4798 };
4799 if (Check())
4800 return true;
4801 std::swap(X, M);
4802 return Check();
4803 }
4804 if (ICmpInst::isEquality(Pred) && match(Op1, m_Zero()) &&
4805 match(Op0, m_OneUse(m_And(m_Value(X), m_Value(M))))) {
4806 auto Check = [&]() {
4807 // Look for: x & ~Mask == 0
4808 if (isMaskOrZero(M, /*Not=*/true, Q)) {
4809 if (Value *NotM =
4810 IC.getFreelyInverted(M, M->hasOneUse(), &IC.Builder)) {
4811 M = NotM;
4812 return true;
4813 }
4814 }
4815 return false;
4816 };
4817 if (Check())
4818 return true;
4819 std::swap(X, M);
4820 return Check();
4821 }
4822 return false;
4823 };
4824
4825 if (!IsLowBitMask())
4826 return nullptr;
4827
4828 return IC.Builder.CreateICmp(DstPred, X, M);
4829}
4830
4831/// Some comparisons can be simplified.
4832/// In this case, we are looking for comparisons that look like
4833/// a check for a lossy signed truncation.
4834/// Folds: (MaskedBits is a constant.)
4835/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4836/// Into:
4837/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4838/// Where KeptBits = bitwidth(%x) - MaskedBits
4839static Value *
4841 InstCombiner::BuilderTy &Builder) {
4842 CmpPredicate SrcPred;
4843 Value *X;
4844 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4845 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4846 if (!match(&I, m_c_ICmp(SrcPred,
4848 m_APInt(C1))),
4849 m_Deferred(X))))
4850 return nullptr;
4851
4852 // Potential handling of non-splats: for each element:
4853 // * if both are undef, replace with constant 0.
4854 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4855 // * if both are not undef, and are different, bailout.
4856 // * else, only one is undef, then pick the non-undef one.
4857
4858 // The shift amount must be equal.
4859 if (*C0 != *C1)
4860 return nullptr;
4861 const APInt &MaskedBits = *C0;
4862 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4863
4864 ICmpInst::Predicate DstPred;
4865 switch (SrcPred) {
4867 // ((%x << MaskedBits) a>> MaskedBits) == %x
4868 // =>
4869 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4871 break;
4873 // ((%x << MaskedBits) a>> MaskedBits) != %x
4874 // =>
4875 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4877 break;
4878 // FIXME: are more folds possible?
4879 default:
4880 return nullptr;
4881 }
4882
4883 auto *XType = X->getType();
4884 const unsigned XBitWidth = XType->getScalarSizeInBits();
4885 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4886 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4887
4888 // KeptBits = bitwidth(%x) - MaskedBits
4889 const APInt KeptBits = BitWidth - MaskedBits;
4890 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4891 // ICmpCst = (1 << KeptBits)
4892 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
4893 assert(ICmpCst.isPowerOf2());
4894 // AddCst = (1 << (KeptBits-1))
4895 const APInt AddCst = ICmpCst.lshr(1);
4896 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4897
4898 // T0 = add %x, AddCst
4899 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
4900 // T1 = T0 DstPred ICmpCst
4901 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
4902
4903 return T1;
4904}
4905
4906// Given pattern:
4907// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4908// we should move shifts to the same hand of 'and', i.e. rewrite as
4909// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4910// We are only interested in opposite logical shifts here.
4911// One of the shifts can be truncated.
4912// If we can, we want to end up creating 'lshr' shift.
4913static Value *
4915 InstCombiner::BuilderTy &Builder) {
4916 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
4917 !I.getOperand(0)->hasOneUse())
4918 return nullptr;
4919
4920 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
4921
4922 // Look for an 'and' of two logical shifts, one of which may be truncated.
4923 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4924 Instruction *XShift, *MaybeTruncation, *YShift;
4925 if (!match(
4926 I.getOperand(0),
4927 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
4929 m_AnyLogicalShift, m_Instruction(YShift))),
4930 m_Instruction(MaybeTruncation)))))
4931 return nullptr;
4932
4933 // We potentially looked past 'trunc', but only when matching YShift,
4934 // therefore YShift must have the widest type.
4935 Instruction *WidestShift = YShift;
4936 // Therefore XShift must have the shallowest type.
4937 // Or they both have identical types if there was no truncation.
4938 Instruction *NarrowestShift = XShift;
4939
4940 Type *WidestTy = WidestShift->getType();
4941 Type *NarrowestTy = NarrowestShift->getType();
4942 assert(NarrowestTy == I.getOperand(0)->getType() &&
4943 "We did not look past any shifts while matching XShift though.");
4944 bool HadTrunc = WidestTy != I.getOperand(0)->getType();
4945
4946 // If YShift is a 'lshr', swap the shifts around.
4947 if (match(YShift, m_LShr(m_Value(), m_Value())))
4948 std::swap(XShift, YShift);
4949
4950 // The shifts must be in opposite directions.
4951 auto XShiftOpcode = XShift->getOpcode();
4952 if (XShiftOpcode == YShift->getOpcode())
4953 return nullptr; // Do not care about same-direction shifts here.
4954
4955 Value *X, *XShAmt, *Y, *YShAmt;
4956 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
4957 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
4958
4959 // If one of the values being shifted is a constant, then we will end with
4960 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4961 // however, we will need to ensure that we won't increase instruction count.
4962 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
4963 // At least one of the hands of the 'and' should be one-use shift.
4964 if (!match(I.getOperand(0),
4965 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
4966 return nullptr;
4967 if (HadTrunc) {
4968 // Due to the 'trunc', we will need to widen X. For that either the old
4969 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4970 if (!MaybeTruncation->hasOneUse() &&
4971 !NarrowestShift->getOperand(1)->hasOneUse())
4972 return nullptr;
4973 }
4974 }
4975
4976 // We have two shift amounts from two different shifts. The types of those
4977 // shift amounts may not match. If that's the case let's bailout now.
4978 if (XShAmt->getType() != YShAmt->getType())
4979 return nullptr;
4980
4981 // As input, we have the following pattern:
4982 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4983 // We want to rewrite that as:
4984 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4985 // While we know that originally (Q+K) would not overflow
4986 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
4987 // shift amounts. so it may now overflow in smaller bitwidth.
4988 // To ensure that does not happen, we need to ensure that the total maximal
4989 // shift amount is still representable in that smaller bit width.
4990 unsigned MaximalPossibleTotalShiftAmount =
4991 (WidestTy->getScalarSizeInBits() - 1) +
4992 (NarrowestTy->getScalarSizeInBits() - 1);
4993 APInt MaximalRepresentableShiftAmount =
4995 if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
4996 return nullptr;
4997
4998 // Can we fold (XShAmt+YShAmt) ?
4999 auto *NewShAmt = dyn_cast_or_null<Constant>(
5000 simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
5001 /*isNUW=*/false, SQ.getWithInstruction(&I)));
5002 if (!NewShAmt)
5003 return nullptr;
5004 if (NewShAmt->getType() != WidestTy) {
5005 NewShAmt =
5006 ConstantFoldCastOperand(Instruction::ZExt, NewShAmt, WidestTy, SQ.DL);
5007 if (!NewShAmt)
5008 return nullptr;
5009 }
5010 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
5011
5012 // Is the new shift amount smaller than the bit width?
5013 // FIXME: could also rely on ConstantRange.
5014 if (!match(NewShAmt,
5016 APInt(WidestBitWidth, WidestBitWidth))))
5017 return nullptr;
5018
5019 // An extra legality check is needed if we had trunc-of-lshr.
5020 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
5021 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
5022 WidestShift]() {
5023 // It isn't obvious whether it's worth it to analyze non-constants here.
5024 // Also, let's basically give up on non-splat cases, pessimizing vectors.
5025 // If *any* of these preconditions matches we can perform the fold.
5026 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
5027 ? NewShAmt->getSplatValue()
5028 : NewShAmt;
5029 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
5030 if (NewShAmtSplat &&
5031 (NewShAmtSplat->isNullValue() ||
5032 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
5033 return true;
5034 // We consider *min* leading zeros so a single outlier
5035 // blocks the transform as opposed to allowing it.
5036 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
5038 unsigned MinLeadZero = Known.countMinLeadingZeros();
5039 // If the value being shifted has at most lowest bit set we can fold.
5040 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5041 if (MaxActiveBits <= 1)
5042 return true;
5043 // Precondition: NewShAmt u<= countLeadingZeros(C)
5044 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
5045 return true;
5046 }
5047 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
5049 unsigned MinLeadZero = Known.countMinLeadingZeros();
5050 // If the value being shifted has at most lowest bit set we can fold.
5051 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5052 if (MaxActiveBits <= 1)
5053 return true;
5054 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
5055 if (NewShAmtSplat) {
5056 APInt AdjNewShAmt =
5057 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
5058 if (AdjNewShAmt.ule(MinLeadZero))
5059 return true;
5060 }
5061 }
5062 return false; // Can't tell if it's ok.
5063 };
5064 if (!CanFold())
5065 return nullptr;
5066 }
5067
5068 // All good, we can do this fold.
5069 X = Builder.CreateZExt(X, WidestTy);
5070 Y = Builder.CreateZExt(Y, WidestTy);
5071 // The shift is the same that was for X.
5072 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
5073 ? Builder.CreateLShr(X, NewShAmt)
5074 : Builder.CreateShl(X, NewShAmt);
5075 Value *T1 = Builder.CreateAnd(T0, Y);
5076 return Builder.CreateICmp(I.getPredicate(), T1,
5077 Constant::getNullValue(WidestTy));
5078}
5079
5080/// Fold
5081/// (-1 u/ x) u< y
5082/// ((x * y) ?/ x) != y
5083/// to
5084/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
5085/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
5086/// will mean that we are looking for the opposite answer.
5088 CmpPredicate Pred;
5089 Value *X, *Y;
5091 Instruction *Div;
5092 bool NeedNegation;
5093 // Look for: (-1 u/ x) u</u>= y
5094 if (!I.isEquality() &&
5095 match(&I, m_c_ICmp(Pred,
5097 m_Instruction(Div)),
5098 m_Value(Y)))) {
5099 Mul = nullptr;
5100
5101 // Are we checking that overflow does not happen, or does happen?
5102 switch (Pred) {
5104 NeedNegation = false;
5105 break; // OK
5107 NeedNegation = true;
5108 break; // OK
5109 default:
5110 return nullptr; // Wrong predicate.
5111 }
5112 } else // Look for: ((x * y) / x) !=/== y
5113 if (I.isEquality() &&
5114 match(&I, m_c_ICmp(Pred, m_Value(Y),
5117 m_Value(X)),
5119 m_Deferred(X))),
5120 m_Instruction(Div))))) {
5121 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
5122 } else
5123 return nullptr;
5124
5126 // If the pattern included (x * y), we'll want to insert new instructions
5127 // right before that original multiplication so that we can replace it.
5128 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
5129 if (MulHadOtherUses)
5130 Builder.SetInsertPoint(Mul);
5131
5132 Value *Call = Builder.CreateIntrinsic(
5133 Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
5134 : Intrinsic::smul_with_overflow,
5135 X->getType(), {X, Y}, /*FMFSource=*/nullptr, "mul");
5136
5137 // If the multiplication was used elsewhere, to ensure that we don't leave
5138 // "duplicate" instructions, replace uses of that original multiplication
5139 // with the multiplication result from the with.overflow intrinsic.
5140 if (MulHadOtherUses)
5141 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
5142
5143 Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
5144 if (NeedNegation) // This technically increases instruction count.
5145 Res = Builder.CreateNot(Res, "mul.not.ov");
5146
5147 // If we replaced the mul, erase it. Do this after all uses of Builder,
5148 // as the mul is used as insertion point.
5149 if (MulHadOtherUses)
5151
5152 return Res;
5153}
5154
5156 InstCombiner::BuilderTy &Builder) {
5157 CmpPredicate Pred;
5158 Value *X;
5159 if (match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) {
5160
5161 if (ICmpInst::isSigned(Pred))
5162 Pred = ICmpInst::getSwappedPredicate(Pred);
5163 else if (ICmpInst::isUnsigned(Pred))
5164 Pred = ICmpInst::getSignedPredicate(Pred);
5165 // else for equality-comparisons just keep the predicate.
5166
5167 return ICmpInst::Create(Instruction::ICmp, Pred, X,
5168 Constant::getNullValue(X->getType()), I.getName());
5169 }
5170
5171 // A value is not equal to its negation unless that value is 0 or
5172 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
5173 if (match(&I, m_c_ICmp(Pred, m_OneUse(m_Neg(m_Value(X))), m_Deferred(X))) &&
5174 ICmpInst::isEquality(Pred)) {
5175 Type *Ty = X->getType();
5176 uint32_t BitWidth = Ty->getScalarSizeInBits();
5177 Constant *MaxSignedVal =
5178 ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
5179 Value *And = Builder.CreateAnd(X, MaxSignedVal);
5180 Constant *Zero = Constant::getNullValue(Ty);
5181 return CmpInst::Create(Instruction::ICmp, Pred, And, Zero);
5182 }
5183
5184 return nullptr;
5185}
5186
5188 InstCombinerImpl &IC) {
5189 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5190 // Normalize and operand as operand 0.
5191 CmpInst::Predicate Pred = I.getPredicate();
5192 if (match(Op1, m_c_And(m_Specific(Op0), m_Value()))) {
5193 std::swap(Op0, Op1);
5194 Pred = ICmpInst::getSwappedPredicate(Pred);
5195 }
5196
5197 if (!match(Op0, m_c_And(m_Specific(Op1), m_Value(A))))
5198 return nullptr;
5199
5200 // (icmp (X & Y) u< X --> (X & Y) != X
5201 if (Pred == ICmpInst::ICMP_ULT)
5202 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5203
5204 // (icmp (X & Y) u>= X --> (X & Y) == X
5205 if (Pred == ICmpInst::ICMP_UGE)
5206 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5207
5208 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5209 // icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and
5210 // Y is non-constant. If Y is constant the `X & C == C` form is preferable
5211 // so don't do this fold.
5212 if (!match(Op1, m_ImmConstant()))
5213 if (auto *NotOp1 =
5214 IC.getFreelyInverted(Op1, !Op1->hasNUsesOrMore(3), &IC.Builder))
5215 return new ICmpInst(Pred, IC.Builder.CreateOr(A, NotOp1),
5216 Constant::getAllOnesValue(Op1->getType()));
5217 // icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.
5218 if (auto *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5219 return new ICmpInst(Pred, IC.Builder.CreateAnd(Op1, NotA),
5220 Constant::getNullValue(Op1->getType()));
5221 }
5222
5223 if (!ICmpInst::isSigned(Pred))
5224 return nullptr;
5225
5226 KnownBits KnownY = IC.computeKnownBits(A, &I);
5227 // (X & NegY) spred X --> (X & NegY) upred X
5228 if (KnownY.isNegative())
5229 return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);
5230
5231 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGT)
5232 return nullptr;
5233
5234 if (KnownY.isNonNegative())
5235 // (X & PosY) s<= X --> X s>= 0
5236 // (X & PosY) s> X --> X s< 0
5237 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
5238 Constant::getNullValue(Op1->getType()));
5239
5241 // (NegX & Y) s<= NegX --> Y s< 0
5242 // (NegX & Y) s> NegX --> Y s>= 0
5244 Constant::getNullValue(A->getType()));
5245
5246 return nullptr;
5247}
5248
5250 InstCombinerImpl &IC) {
5251 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5252
5253 // Normalize or operand as operand 0.
5254 CmpInst::Predicate Pred = I.getPredicate();
5255 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value(A)))) {
5256 std::swap(Op0, Op1);
5257 Pred = ICmpInst::getSwappedPredicate(Pred);
5258 } else if (!match(Op0, m_c_Or(m_Specific(Op1), m_Value(A)))) {
5259 return nullptr;
5260 }
5261
5262 // icmp (X | Y) u<= X --> (X | Y) == X
5263 if (Pred == ICmpInst::ICMP_ULE)
5264 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5265
5266 // icmp (X | Y) u> X --> (X | Y) != X
5267 if (Pred == ICmpInst::ICMP_UGT)
5268 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5269
5270 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5271 // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
5272 if (Value *NotOp1 = IC.getFreelyInverted(
5273 Op1, !isa<Constant>(Op1) && !Op1->hasNUsesOrMore(3), &IC.Builder))
5274 return new ICmpInst(Pred, IC.Builder.CreateAnd(A, NotOp1),
5275 Constant::getNullValue(Op1->getType()));
5276 // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.
5277 if (Value *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5278 return new ICmpInst(Pred, IC.Builder.CreateOr(Op1, NotA),
5279 Constant::getAllOnesValue(Op1->getType()));
5280 }
5281 return nullptr;
5282}
5283
5285 InstCombinerImpl &IC) {
5286 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5287 // Normalize xor operand as operand 0.
5288 CmpInst::Predicate Pred = I.getPredicate();
5289 if (match(Op1, m_c_Xor(m_Specific(Op0), m_Value()))) {
5290 std::swap(Op0, Op1);
5291 Pred = ICmpInst::getSwappedPredicate(Pred);
5292 }
5293 if (!match(Op0, m_c_Xor(m_Specific(Op1), m_Value(A))))
5294 return nullptr;
5295
5296 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
5297 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
5298 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
5299 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
5301 if (PredOut != Pred && isKnownNonZero(A, Q))
5302 return new ICmpInst(PredOut, Op0, Op1);
5303
5304 // These transform work when A is negative.
5305 // X s< X^A, X s<= X^A, X u> X^A, X u>= X^A --> X s< 0
5306 // X s> X^A, X s>= X^A, X u< X^A, X u<= X^A --> X s>= 0
5307 if (match(A, m_Negative())) {
5308 CmpInst::Predicate NewPred;
5309 switch (ICmpInst::getStrictPredicate(Pred)) {
5310 default:
5311 return nullptr;
5312 case ICmpInst::ICMP_SLT:
5313 case ICmpInst::ICMP_UGT:
5314 NewPred = ICmpInst::ICMP_SLT;
5315 break;
5316 case ICmpInst::ICMP_SGT:
5317 case ICmpInst::ICMP_ULT:
5318 NewPred = ICmpInst::ICMP_SGE;
5319 break;
5320 }
5321 Constant *Const = Constant::getNullValue(Op0->getType());
5322 return new ICmpInst(NewPred, Op0, Const);
5323 }
5324
5325 return nullptr;
5326}
5327
5328/// Return true if X is a multiple of C.
5329/// TODO: Handle non-power-of-2 factors.
5330static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q) {
5331 if (C.isOne())
5332 return true;
5333
5334 if (!C.isPowerOf2())
5335 return false;
5336
5337 return MaskedValueIsZero(X, C - 1, Q);
5338}
5339
5340/// Try to fold icmp (binop), X or icmp X, (binop).
5341/// TODO: A large part of this logic is duplicated in InstSimplify's
5342/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
5343/// duplication.
5345 const SimplifyQuery &SQ) {
5346 const SimplifyQuery Q = SQ.getWithInstruction(&I);
5347 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5348
5349 // Special logic for binary operators.
5352 if (!BO0 && !BO1)
5353 return nullptr;
5354
5355 if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
5356 return NewICmp;
5357
5358 const CmpInst::Predicate Pred = I.getPredicate();
5359
5360 // (X urem Y) == X --> X u< Y
5361 // (X urem Y) != X --> X u>= Y
5362 Value *Dividend, *Divisor;
5363 if (I.isEquality() &&
5364 match(&I, m_c_ICmp(m_URem(m_Value(Dividend), m_Value(Divisor)),
5365 m_Deferred(Dividend)))) {
5366 CmpInst::Predicate NewPred =
5368 return new ICmpInst(NewPred, Dividend, Divisor);
5369 }
5370
5371 Value *X;
5372
5373 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
5374 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
5375 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
5376 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5377 return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
5378 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
5379 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
5380 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5381 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
5382
5383 {
5384 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
5385 Constant *C;
5386 if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
5387 m_ImmConstant(C)))) &&
5388 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
5390 return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
5391 }
5392 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
5393 if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
5394 m_ImmConstant(C)))) &&
5395 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
5397 return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
5398 }
5399 }
5400
5401 // (icmp eq/ne (X, -P2), INT_MIN)
5402 // -> (icmp slt/sge X, INT_MIN + P2)
5403 if (ICmpInst::isEquality(Pred) && BO0 &&
5404 match(I.getOperand(1), m_SignMask()) &&
5406 // Will Constant fold.
5407 Value *NewC = Builder.CreateSub(I.getOperand(1), BO0->getOperand(1));
5408 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SLT
5410 BO0->getOperand(0), NewC);
5411 }
5412
5413 {
5414 // Similar to above: an unsigned overflow comparison may use offset + mask:
5415 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
5416 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
5417 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
5418 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
5419 BinaryOperator *BO;
5420 const APInt *C;
5421 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
5422 match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5424 CmpInst::Predicate NewPred =
5426 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5427 return new ICmpInst(NewPred, Op1, Zero);
5428 }
5429
5430 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5431 match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5433 CmpInst::Predicate NewPred =
5435 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5436 return new ICmpInst(NewPred, Op0, Zero);
5437 }
5438 }
5439
5440 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
5441 bool Op0HasNUW = false, Op1HasNUW = false;
5442 bool Op0HasNSW = false, Op1HasNSW = false;
5443 // Analyze the case when either Op0 or Op1 is an add instruction.
5444 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
5445 auto hasNoWrapProblem = [](const BinaryOperator &BO, CmpInst::Predicate Pred,
5446 bool &HasNSW, bool &HasNUW) -> bool {
5448 HasNUW = BO.hasNoUnsignedWrap();
5449 HasNSW = BO.hasNoSignedWrap();
5450 return ICmpInst::isEquality(Pred) ||
5451 (CmpInst::isUnsigned(Pred) && HasNUW) ||
5452 (CmpInst::isSigned(Pred) && HasNSW);
5453 } else if (BO.getOpcode() == Instruction::Or) {
5454 // The invariant here is that we are handling m_AddLike instructions,
5455 // which can only be a or disjoint, which is equivalent to an add nuw nsw.
5456 HasNUW = true;
5457 HasNSW = true;
5458 return true;
5459 } else {
5460 return false;
5461 }
5462 };
5463 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5464
5465 if (BO0) {
5466 match(BO0, m_AddLike(m_Value(A), m_Value(B)));
5467 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5468 }
5469 if (BO1) {
5470 match(BO1, m_AddLike(m_Value(C), m_Value(D)));
5471 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5472 }
5473
5474 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5475 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5476 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5477 return new ICmpInst(Pred, A == Op1 ? B : A,
5478 Constant::getNullValue(Op1->getType()));
5479
5480 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5481 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5482 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5483 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
5484 C == Op0 ? D : C);
5485
5486 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
5487 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
5488 NoOp1WrapProblem) {
5489 // Determine Y and Z in the form icmp (X+Y), (X+Z).
5490 Value *Y, *Z;
5491 if (A == C) {
5492 // C + B == C + D -> B == D
5493 Y = B;
5494 Z = D;
5495 } else if (A == D) {
5496 // D + B == C + D -> B == C
5497 Y = B;
5498 Z = C;
5499 } else if (B == C) {
5500 // A + C == C + D -> A == D
5501 Y = A;
5502 Z = D;
5503 } else {
5504 assert(B == D);
5505 // A + D == C + D -> A == C
5506 Y = A;
5507 Z = C;
5508 }
5509 return new ICmpInst(Pred, Y, Z);
5510 }
5511
5512 if (ICmpInst::isRelational(Pred)) {
5513 // Return if both X and Y is divisible by Z/-Z.
5514 // TODO: Generalize to check if (X - Y) is divisible by Z/-Z.
5515 auto ShareCommonDivisor = [&Q](Value *X, Value *Y, Value *Z,
5516 bool IsNegative) -> bool {
5517 const APInt *OffsetC;
5518 if (!match(Z, m_APInt(OffsetC)))
5519 return false;
5520
5521 // Fast path for Z == 1/-1.
5522 if (IsNegative ? OffsetC->isAllOnes() : OffsetC->isOne())
5523 return true;
5524
5525 APInt C = *OffsetC;
5526 if (IsNegative)
5527 C.negate();
5528 // Note: -INT_MIN is also negative.
5529 if (!C.isStrictlyPositive())
5530 return false;
5531
5532 return isMultipleOf(X, C, Q) && isMultipleOf(Y, C, Q);
5533 };
5534
5535 // The subtraction-related identities (A -nuw B) shown below require that
5536 // the subtraction does not wrap unsigned (i.e., A >=u B). Canonicalization
5537 // from (A -nuw 1) to (A + -1) means that such combinations ought to never
5538 // occur, as sub nuw ops should have been canonicalized to add ones. It may
5539 // however appear in the form of a or disjoint. Though, or disjoint A, -B
5540 // requires proving A <u B, for which the nowrap precondition can never be
5541 // satisfied. These are therefore skipped.
5542 //
5543 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5544 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5545 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5546 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5547
5548 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5549 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5550 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5551 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5552 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5553 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5554 bool IsNegative = ICmpInst::isLT(Pred) || ICmpInst::isGE(Pred);
5555 bool IsAddOrSignedPred = !IsNegative || ICmpInst::isSigned(Pred);
5556 if (A && NoOp0WrapProblem && IsAddOrSignedPred &&
5557 ShareCommonDivisor(A, Op1, B, IsNegative))
5559 Op1);
5560
5561 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5562 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5563 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5564 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5565 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5566 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5567 if (C && NoOp1WrapProblem &&
5568 ShareCommonDivisor(Op0, C, D,
5569 ICmpInst::isGT(Pred) || ICmpInst::isLE(Pred)))
5571 C);
5572 }
5573
5574 // if C1 has greater magnitude than C2:
5575 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5576 // s.t. C3 = C1 - C2
5577 //
5578 // if C2 has greater magnitude than C1:
5579 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5580 // s.t. C3 = C2 - C1
5581 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5582 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5583 const APInt *AP1, *AP2;
5584 // TODO: Support non-uniform vectors.
5585 // TODO: Allow poison passthrough if B or D's element is poison.
5586 if (match(B, m_APIntAllowPoison(AP1)) &&
5587 match(D, m_APIntAllowPoison(AP2)) &&
5588 AP1->isNegative() == AP2->isNegative()) {
5589 APInt AP1Abs = AP1->abs();
5590 APInt AP2Abs = AP2->abs();
5591 if (AP1Abs.uge(AP2Abs)) {
5592 APInt Diff = *AP1 - *AP2;
5593 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5594 Value *NewAdd = Builder.CreateAdd(
5595 A, C3, "", Op0HasNUW && Diff.ule(*AP1), Op0HasNSW);
5596 return new ICmpInst(Pred, NewAdd, C);
5597 } else {
5598 APInt Diff = *AP2 - *AP1;
5599 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5600 Value *NewAdd = Builder.CreateAdd(
5601 C, C3, "", Op1HasNUW && Diff.ule(*AP2), Op1HasNSW);
5602 return new ICmpInst(Pred, A, NewAdd);
5603 }
5604 }
5605 Constant *Cst1, *Cst2;
5606 if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
5607 ICmpInst::isEquality(Pred)) {
5608 Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
5609 Value *NewAdd = Builder.CreateAdd(C, Diff);
5610 return new ICmpInst(Pred, A, NewAdd);
5611 }
5612 }
5613
5614 // Analyze the case when either Op0 or Op1 is a sub instruction.
5615 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5616 A = nullptr;
5617 B = nullptr;
5618 C = nullptr;
5619 D = nullptr;
5620 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5621 A = BO0->getOperand(0);
5622 B = BO0->getOperand(1);
5623 }
5624 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5625 C = BO1->getOperand(0);
5626 D = BO1->getOperand(1);
5627 }
5628
5629 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5630 if (A == Op1 && NoOp0WrapProblem)
5631 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
5632 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5633 if (C == Op0 && NoOp1WrapProblem)
5634 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
5635
5636 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5637 // (A - B) u>/u<= A --> B u>/u<= A
5638 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5639 return new ICmpInst(Pred, B, A);
5640 // C u</u>= (C - D) --> C u</u>= D
5641 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5642 return new ICmpInst(Pred, C, D);
5643 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5644 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5645 isKnownNonZero(B, Q))
5647 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5648 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5649 isKnownNonZero(D, Q))
5651
5652 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
5653 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
5654 return new ICmpInst(Pred, A, C);
5655
5656 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
5657 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
5658 return new ICmpInst(Pred, D, B);
5659
5660 // icmp (0-X) < cst --> x > -cst
5661 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
5662 Value *X;
5663 if (match(BO0, m_Neg(m_Value(X))))
5664 if (Constant *RHSC = dyn_cast<Constant>(Op1))
5665 if (RHSC->isNotMinSignedValue())
5666 return new ICmpInst(I.getSwappedPredicate(), X,
5667 ConstantExpr::getNeg(RHSC));
5668 }
5669
5670 if (Instruction *R = foldICmpXorXX(I, Q, *this))
5671 return R;
5672 if (Instruction *R = foldICmpOrXX(I, Q, *this))
5673 return R;
5674
5675 {
5676 // Try to remove shared multiplier from comparison:
5677 // X * Z pred Y * Z
5678 Value *X, *Y, *Z;
5679 if ((match(Op0, m_Mul(m_Value(X), m_Value(Z))) &&
5680 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))) ||
5681 (match(Op0, m_Mul(m_Value(Z), m_Value(X))) &&
5682 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y))))) {
5683 if (ICmpInst::isSigned(Pred)) {
5684 if (Op0HasNSW && Op1HasNSW) {
5685 KnownBits ZKnown = computeKnownBits(Z, &I);
5686 if (ZKnown.isStrictlyPositive())
5687 return new ICmpInst(Pred, X, Y);
5688 if (ZKnown.isNegative())
5689 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), X, Y);
5691 SQ.getWithInstruction(&I));
5692 if (LessThan && match(LessThan, m_One()))
5693 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Z,
5694 Constant::getNullValue(Z->getType()));
5695 Value *GreaterThan = simplifyICmpInst(ICmpInst::ICMP_SGT, X, Y,
5696 SQ.getWithInstruction(&I));
5697 if (GreaterThan && match(GreaterThan, m_One()))
5698 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5699 }
5700 } else {
5701 bool NonZero;
5702 if (ICmpInst::isEquality(Pred)) {
5703 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5704 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5705 isKnownNonEqual(X, Y, SQ))
5706 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5707
5708 KnownBits ZKnown = computeKnownBits(Z, &I);
5709 // if Z % 2 != 0
5710 // X * Z eq/ne Y * Z -> X eq/ne Y
5711 if (ZKnown.countMaxTrailingZeros() == 0)
5712 return new ICmpInst(Pred, X, Y);
5713 NonZero = !ZKnown.One.isZero() || isKnownNonZero(Z, Q);
5714 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5715 // X * Z eq/ne Y * Z -> X eq/ne Y
5716 if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)
5717 return new ICmpInst(Pred, X, Y);
5718 } else
5719 NonZero = isKnownNonZero(Z, Q);
5720
5721 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5722 // X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
5723 if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)
5724 return new ICmpInst(Pred, X, Y);
5725 }
5726 }
5727 }
5728
5729 BinaryOperator *SRem = nullptr;
5730 // icmp (srem X, Y), Y
5731 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
5732 SRem = BO0;
5733 // icmp Y, (srem X, Y)
5734 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5735 Op0 == BO1->getOperand(1))
5736 SRem = BO1;
5737 if (SRem) {
5738 // We don't check hasOneUse to avoid increasing register pressure because
5739 // the value we use is the same value this instruction was already using.
5740 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
5741 default:
5742 break;
5743 case ICmpInst::ICMP_EQ:
5744 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5745 case ICmpInst::ICMP_NE:
5746 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5747 case ICmpInst::ICMP_SGT:
5748 case ICmpInst::ICMP_SGE:
5749 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
5751 case ICmpInst::ICMP_SLT:
5752 case ICmpInst::ICMP_SLE:
5753 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
5755 }
5756 }
5757
5758 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5759 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5760 BO0->getOperand(1) == BO1->getOperand(1)) {
5761 switch (BO0->getOpcode()) {
5762 default:
5763 break;
5764 case Instruction::Add:
5765 case Instruction::Sub:
5766 case Instruction::Xor: {
5767 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5768 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5769
5770 const APInt *C;
5771 if (match(BO0->getOperand(1), m_APInt(C))) {
5772 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5773 if (C->isSignMask()) {
5774 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5775 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5776 }
5777
5778 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5779 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5780 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5781 NewPred = I.getSwappedPredicate(NewPred);
5782 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5783 }
5784 }
5785 break;
5786 }
5787 case Instruction::Mul: {
5788 if (!I.isEquality())
5789 break;
5790
5791 const APInt *C;
5792 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
5793 !C->isOne()) {
5794 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5795 // Mask = -1 >> count-trailing-zeros(C).
5796 if (unsigned TZs = C->countr_zero()) {
5797 Constant *Mask = ConstantInt::get(
5798 BO0->getType(),
5799 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
5800 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
5801 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
5802 return new ICmpInst(Pred, And1, And2);
5803 }
5804 }
5805 break;
5806 }
5807 case Instruction::UDiv:
5808 case Instruction::LShr:
5809 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
5810 break;
5811 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5812
5813 case Instruction::SDiv:
5814 if (!(I.isEquality() || match(BO0->getOperand(1), m_NonNegative())) ||
5815 !BO0->isExact() || !BO1->isExact())
5816 break;
5817 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5818
5819 case Instruction::AShr:
5820 if (!BO0->isExact() || !BO1->isExact())
5821 break;
5822 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5823
5824 case Instruction::Shl: {
5825 bool NUW = Op0HasNUW && Op1HasNUW;
5826 bool NSW = Op0HasNSW && Op1HasNSW;
5827 if (!NUW && !NSW)
5828 break;
5829 if (!NSW && I.isSigned())
5830 break;
5831 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5832 }
5833 }
5834 }
5835
5836 if (BO0) {
5837 // Transform A & (L - 1) `ult` L --> L != 0
5838 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
5839 auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
5840
5841 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5842 auto *Zero = Constant::getNullValue(BO0->getType());
5843 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5844 }
5845 }
5846
5847 // For unsigned predicates / eq / ne:
5848 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5849 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5850 if (!ICmpInst::isSigned(Pred)) {
5851 if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
5852 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5853 Constant::getNullValue(Op1->getType()));
5854 else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
5855 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5856 Constant::getNullValue(Op0->getType()), Op0);
5857 }
5858
5860 return replaceInstUsesWith(I, V);
5861
5862 if (Instruction *R = foldICmpAndXX(I, Q, *this))
5863 return R;
5864
5866 return replaceInstUsesWith(I, V);
5867
5869 return replaceInstUsesWith(I, V);
5870
5871 return nullptr;
5872}
5873
5874/// Fold icmp Pred min|max(X, Y), Z.
5877 Value *Z, CmpPredicate Pred) {
5878 Value *X = MinMax->getLHS();
5879 Value *Y = MinMax->getRHS();
5880 if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5881 return nullptr;
5882 if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {
5883 // Revert the transform signed pred -> unsigned pred
5884 // TODO: We can flip the signedness of predicate if both operands of icmp
5885 // are negative.
5886 if (isKnownNonNegative(Z, SQ.getWithInstruction(&I)) &&
5887 isKnownNonNegative(MinMax, SQ.getWithInstruction(&I))) {
5889 } else
5890 return nullptr;
5891 }
5892 SimplifyQuery Q = SQ.getWithInstruction(&I);
5893 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5894 if (!Val)
5895 return std::nullopt;
5896 if (match(Val, m_One()))
5897 return true;
5898 if (match(Val, m_Zero()))
5899 return false;
5900 return std::nullopt;
5901 };
5902 // Remove samesign here since it is illegal to keep it when we speculatively
5903 // execute comparisons. For example, `icmp samesign ult umax(X, -46), -32`
5904 // cannot be decomposed into `(icmp samesign ult X, -46) or (icmp samesign ult
5905 // -46, -32)`. `X` is allowed to be non-negative here.
5906 Pred = Pred.dropSameSign();
5907 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, X, Z, Q));
5908 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, Y, Z, Q));
5909 if (!CmpXZ.has_value() && !CmpYZ.has_value())
5910 return nullptr;
5911 if (!CmpXZ.has_value()) {
5912 std::swap(X, Y);
5913 std::swap(CmpXZ, CmpYZ);
5914 }
5915
5916 auto FoldIntoCmpYZ = [&]() -> Instruction * {
5917 if (CmpYZ.has_value())
5918 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *CmpYZ));
5919 return ICmpInst::Create(Instruction::ICmp, Pred, Y, Z);
5920 };
5921
5922 switch (Pred) {
5923 case ICmpInst::ICMP_EQ:
5924 case ICmpInst::ICMP_NE: {
5925 // If X == Z:
5926 // Expr Result
5927 // min(X, Y) == Z X <= Y
5928 // max(X, Y) == Z X >= Y
5929 // min(X, Y) != Z X > Y
5930 // max(X, Y) != Z X < Y
5931 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5932 ICmpInst::Predicate NewPred =
5933 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
5934 if (Pred == ICmpInst::ICMP_NE)
5935 NewPred = ICmpInst::getInversePredicate(NewPred);
5936 return ICmpInst::Create(Instruction::ICmp, NewPred, X, Y);
5937 }
5938 // Otherwise (X != Z):
5939 ICmpInst::Predicate NewPred = MinMax->getPredicate();
5940 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5941 if (!MinMaxCmpXZ.has_value()) {
5942 std::swap(X, Y);
5943 std::swap(CmpXZ, CmpYZ);
5944 // Re-check pre-condition X != Z
5945 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5946 break;
5947 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5948 }
5949 if (!MinMaxCmpXZ.has_value())
5950 break;
5951 if (*MinMaxCmpXZ) {
5952 // Expr Fact Result
5953 // min(X, Y) == Z X < Z false
5954 // max(X, Y) == Z X > Z false
5955 // min(X, Y) != Z X < Z true
5956 // max(X, Y) != Z X > Z true
5957 return replaceInstUsesWith(
5958 I, ConstantInt::getBool(I.getType(), Pred == ICmpInst::ICMP_NE));
5959 } else {
5960 // Expr Fact Result
5961 // min(X, Y) == Z X > Z Y == Z
5962 // max(X, Y) == Z X < Z Y == Z
5963 // min(X, Y) != Z X > Z Y != Z
5964 // max(X, Y) != Z X < Z Y != Z
5965 return FoldIntoCmpYZ();
5966 }
5967 break;
5968 }
5969 case ICmpInst::ICMP_SLT:
5970 case ICmpInst::ICMP_ULT:
5971 case ICmpInst::ICMP_SLE:
5972 case ICmpInst::ICMP_ULE:
5973 case ICmpInst::ICMP_SGT:
5974 case ICmpInst::ICMP_UGT:
5975 case ICmpInst::ICMP_SGE:
5976 case ICmpInst::ICMP_UGE: {
5977 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(Pred);
5978 if (*CmpXZ) {
5979 if (IsSame) {
5980 // Expr Fact Result
5981 // min(X, Y) < Z X < Z true
5982 // min(X, Y) <= Z X <= Z true
5983 // max(X, Y) > Z X > Z true
5984 // max(X, Y) >= Z X >= Z true
5985 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5986 } else {
5987 // Expr Fact Result
5988 // max(X, Y) < Z X < Z Y < Z
5989 // max(X, Y) <= Z X <= Z Y <= Z
5990 // min(X, Y) > Z X > Z Y > Z
5991 // min(X, Y) >= Z X >= Z Y >= Z
5992 return FoldIntoCmpYZ();
5993 }
5994 } else {
5995 if (IsSame) {
5996 // Expr Fact Result
5997 // min(X, Y) < Z X >= Z Y < Z
5998 // min(X, Y) <= Z X > Z Y <= Z
5999 // max(X, Y) > Z X <= Z Y > Z
6000 // max(X, Y) >= Z X < Z Y >= Z
6001 return FoldIntoCmpYZ();
6002 } else {
6003 // Expr Fact Result
6004 // max(X, Y) < Z X >= Z false
6005 // max(X, Y) <= Z X > Z false
6006 // min(X, Y) > Z X <= Z false
6007 // min(X, Y) >= Z X < Z false
6008 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6009 }
6010 }
6011 break;
6012 }
6013 default:
6014 break;
6015 }
6016
6017 return nullptr;
6018}
6019
6020/// Match and fold patterns like:
6021/// icmp eq/ne X, min(max(X, Lo), Hi)
6022/// which represents a range check and can be represented as a ConstantRange.
6023///
6024/// For icmp eq, build ConstantRange [Lo, Hi + 1) and convert to:
6025/// (X - Lo) u< (Hi + 1 - Lo)
6026/// For icmp ne, build ConstantRange [Hi + 1, Lo) and convert to:
6027/// (X - (Hi + 1)) u< (Lo - (Hi + 1))
6029 MinMaxIntrinsic *Min) {
6030 if (!I.isEquality() || !Min->hasOneUse() || !Min->isMin())
6031 return nullptr;
6032
6033 const APInt *Lo = nullptr, *Hi = nullptr;
6034 if (Min->isSigned()) {
6035 if (!match(Min->getLHS(), m_OneUse(m_SMax(m_Specific(X), m_APInt(Lo)))) ||
6036 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->slt(*Hi))
6037 return nullptr;
6038 } else {
6039 if (!match(Min->getLHS(), m_OneUse(m_UMax(m_Specific(X), m_APInt(Lo)))) ||
6040 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->ult(*Hi))
6041 return nullptr;
6042 }
6043
6046 APInt C, Offset;
6047 if (I.getPredicate() == ICmpInst::ICMP_EQ)
6048 CR.getEquivalentICmp(Pred, C, Offset);
6049 else
6050 CR.inverse().getEquivalentICmp(Pred, C, Offset);
6051
6052 if (!Offset.isZero())
6053 X = Builder.CreateAdd(X, ConstantInt::get(X->getType(), Offset));
6054
6055 return replaceInstUsesWith(
6056 I, Builder.CreateICmp(Pred, X, ConstantInt::get(X->getType(), C)));
6057}
6058
6059// Canonicalize checking for a power-of-2-or-zero value:
6061 InstCombiner::BuilderTy &Builder) {
6062 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6063 const CmpInst::Predicate Pred = I.getPredicate();
6064 Value *A = nullptr;
6065 bool CheckIs;
6066 if (I.isEquality()) {
6067 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
6068 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
6069 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
6070 m_Deferred(A)))) ||
6071 !match(Op1, m_ZeroInt()))
6072 A = nullptr;
6073
6074 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
6075 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
6076 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
6077 A = Op1;
6078 else if (match(Op1,
6080 A = Op0;
6081
6082 CheckIs = Pred == ICmpInst::ICMP_EQ;
6083 } else if (ICmpInst::isUnsigned(Pred)) {
6084 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
6085 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
6086
6087 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
6089 m_Specific(Op1))))) {
6090 A = Op1;
6091 CheckIs = Pred == ICmpInst::ICMP_UGE;
6092 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
6094 m_Specific(Op0))))) {
6095 A = Op0;
6096 CheckIs = Pred == ICmpInst::ICMP_ULE;
6097 }
6098 }
6099
6100 if (A) {
6101 Type *Ty = A->getType();
6102 Value *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
6103 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
6104 ConstantInt::get(Ty, 2))
6105 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
6106 ConstantInt::get(Ty, 1));
6107 }
6108
6109 return nullptr;
6110}
6111
6112/// Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
6113using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
6115 bool AllowRecursion) {
6117 if (!Inst || !Inst->hasOneUse())
6118 return;
6119
6120 switch (Inst->getOpcode()) {
6121 case Instruction::Add:
6122 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(1));
6123 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(0));
6124 break;
6125 case Instruction::Sub:
6126 Offsets.emplace_back(Instruction::Add, Inst->getOperand(1));
6127 break;
6128 case Instruction::Xor:
6129 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(1));
6130 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(0));
6131 break;
6132 case Instruction::Shl:
6133 if (Inst->hasNoSignedWrap())
6134 Offsets.emplace_back(Instruction::AShr, Inst->getOperand(1));
6135 if (Inst->hasNoUnsignedWrap())
6136 Offsets.emplace_back(Instruction::LShr, Inst->getOperand(1));
6137 break;
6138 case Instruction::Select:
6139 if (AllowRecursion) {
6140 collectOffsetOp(Inst->getOperand(1), Offsets, /*AllowRecursion=*/false);
6141 collectOffsetOp(Inst->getOperand(2), Offsets, /*AllowRecursion=*/false);
6142 }
6143 break;
6144 default:
6145 break;
6146 }
6147}
6148
6150
6155
6157 return {OffsetKind::Invalid, nullptr, nullptr, nullptr, nullptr};
6158 }
6160 return {OffsetKind::Value, V, nullptr, nullptr, nullptr};
6161 }
6162 static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV,
6164 return {OffsetKind::Select, Cond, TrueV, FalseV, MDFrom};
6165 }
6166 bool isValid() const { return Kind != OffsetKind::Invalid; }
6168 switch (Kind) {
6170 llvm_unreachable("Invalid offset result");
6171 case OffsetKind::Value:
6172 return V0;
6173 case OffsetKind::Select:
6174 return Builder.CreateSelect(V0, V1, V2, "", MDFrom);
6175 }
6176 llvm_unreachable("Unknown OffsetKind enum");
6177 }
6178};
6179
6180/// Offset both sides of an equality icmp to see if we can save some
6181/// instructions: icmp eq/ne X, Y -> icmp eq/ne X op Z, Y op Z.
6182/// Note: This operation should not introduce poison.
6184 InstCombiner::BuilderTy &Builder,
6185 const SimplifyQuery &SQ) {
6186 assert(I.isEquality() && "Expected an equality icmp");
6187 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6188 if (!Op0->getType()->isIntOrIntVectorTy())
6189 return nullptr;
6190
6191 SmallVector<OffsetOp, 4> OffsetOps;
6192 collectOffsetOp(Op0, OffsetOps, /*AllowRecursion=*/true);
6193 collectOffsetOp(Op1, OffsetOps, /*AllowRecursion=*/true);
6194
6195 auto ApplyOffsetImpl = [&](Value *V, unsigned BinOpc, Value *RHS) -> Value * {
6196 switch (BinOpc) {
6197 // V = shl nsw X, RHS => X = ashr V, RHS
6198 case Instruction::AShr: {
6199 const APInt *CV, *CRHS;
6200 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6201 CV->ashr(*CRHS).shl(*CRHS) == *CV) &&
6203 return nullptr;
6204 break;
6205 }
6206 // V = shl nuw X, RHS => X = lshr V, RHS
6207 case Instruction::LShr: {
6208 const APInt *CV, *CRHS;
6209 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6210 CV->lshr(*CRHS).shl(*CRHS) == *CV) &&
6212 return nullptr;
6213 break;
6214 }
6215 default:
6216 break;
6217 }
6218
6219 Value *Simplified = simplifyBinOp(BinOpc, V, RHS, SQ);
6220 if (!Simplified)
6221 return nullptr;
6222 // Reject constant expressions as they don't simplify things.
6223 if (isa<Constant>(Simplified) && !match(Simplified, m_ImmConstant()))
6224 return nullptr;
6225 // Check if the transformation introduces poison.
6226 return impliesPoison(RHS, V) ? Simplified : nullptr;
6227 };
6228
6229 auto ApplyOffset = [&](Value *V, unsigned BinOpc,
6230 Value *RHS) -> OffsetResult {
6231 if (auto *Sel = dyn_cast<SelectInst>(V)) {
6232 if (!Sel->hasOneUse())
6233 return OffsetResult::invalid();
6234 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc, RHS);
6235 if (!TrueVal)
6236 return OffsetResult::invalid();
6237 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc, RHS);
6238 if (!FalseVal)
6239 return OffsetResult::invalid();
6240 return OffsetResult::select(Sel->getCondition(), TrueVal, FalseVal, Sel);
6241 }
6242 if (Value *Simplified = ApplyOffsetImpl(V, BinOpc, RHS))
6243 return OffsetResult::value(Simplified);
6244 return OffsetResult::invalid();
6245 };
6246
6247 for (auto [BinOp, RHS] : OffsetOps) {
6248 auto BinOpc = static_cast<unsigned>(BinOp);
6249
6250 auto Op0Result = ApplyOffset(Op0, BinOpc, RHS);
6251 if (!Op0Result.isValid())
6252 continue;
6253 auto Op1Result = ApplyOffset(Op1, BinOpc, RHS);
6254 if (!Op1Result.isValid())
6255 continue;
6256
6257 Value *NewLHS = Op0Result.materialize(Builder);
6258 Value *NewRHS = Op1Result.materialize(Builder);
6259 return new ICmpInst(I.getPredicate(), NewLHS, NewRHS);
6260 }
6261
6262 return nullptr;
6263}
6264
6266 if (!I.isEquality())
6267 return nullptr;
6268
6269 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6270 const CmpInst::Predicate Pred = I.getPredicate();
6271 Value *A, *B, *C, *D;
6272 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6273 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6274 Value *OtherVal = A == Op1 ? B : A;
6275 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6276 }
6277
6278 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6279 // A^c1 == C^c2 --> A == C^(c1^c2)
6280 ConstantInt *C1, *C2;
6281 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
6282 Op1->hasOneUse()) {
6283 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
6284 Value *Xor = Builder.CreateXor(C, NC);
6285 return new ICmpInst(Pred, A, Xor);
6286 }
6287
6288 // A^B == A^D -> B == D
6289 if (A == C)
6290 return new ICmpInst(Pred, B, D);
6291 if (A == D)
6292 return new ICmpInst(Pred, B, C);
6293 if (B == C)
6294 return new ICmpInst(Pred, A, D);
6295 if (B == D)
6296 return new ICmpInst(Pred, A, C);
6297 }
6298 }
6299
6300 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
6301 // A == (A^B) -> B == 0
6302 Value *OtherVal = A == Op0 ? B : A;
6303 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6304 }
6305
6306 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6307 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
6308 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6309 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
6310
6311 if (A == C) {
6312 X = B;
6313 Y = D;
6314 Z = A;
6315 } else if (A == D) {
6316 X = B;
6317 Y = C;
6318 Z = A;
6319 } else if (B == C) {
6320 X = A;
6321 Y = D;
6322 Z = B;
6323 } else if (B == D) {
6324 X = A;
6325 Y = C;
6326 Z = B;
6327 }
6328
6329 if (X) {
6330 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
6331 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
6332 // instructions.
6333 const APInt *C0, *C1;
6334 bool XorIsNegP2 = match(X, m_APInt(C0)) && match(Y, m_APInt(C1)) &&
6335 (*C0 ^ *C1).isNegatedPowerOf2();
6336
6337 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
6338 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
6339 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
6340 int UseCnt =
6341 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
6342 (int(match(X, m_ImmConstant()) && match(Y, m_ImmConstant())));
6343 if (XorIsNegP2 || UseCnt >= 2) {
6344 // Build (X^Y) & Z
6345 Op1 = Builder.CreateXor(X, Y);
6346 Op1 = Builder.CreateAnd(Op1, Z);
6347 return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
6348 }
6349 }
6350 }
6351
6352 {
6353 // Similar to above, but specialized for constant because invert is needed:
6354 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
6355 Value *X, *Y;
6356 Constant *C;
6357 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
6358 match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
6359 Value *Xor = Builder.CreateXor(X, Y);
6360 Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
6361 return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
6362 }
6363 }
6364
6365 if (match(Op1, m_ZExt(m_Value(A))) &&
6366 (Op0->hasOneUse() || Op1->hasOneUse())) {
6367 // (B & (Pow2C-1)) == zext A --> A == trunc B
6368 // (B & (Pow2C-1)) != zext A --> A != trunc B
6369 const APInt *MaskC;
6370 if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
6371 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
6372 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
6373 }
6374
6375 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
6376 // For lshr and ashr pairs.
6377 const APInt *AP1, *AP2;
6378 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6379 match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowPoison(AP2))))) ||
6380 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6381 match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowPoison(AP2)))))) {
6382 if (*AP1 != *AP2)
6383 return nullptr;
6384 unsigned TypeBits = AP1->getBitWidth();
6385 unsigned ShAmt = AP1->getLimitedValue(TypeBits);
6386 if (ShAmt < TypeBits && ShAmt != 0) {
6387 ICmpInst::Predicate NewPred =
6389 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6390 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
6391 return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
6392 }
6393 }
6394
6395 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
6396 ConstantInt *Cst1;
6397 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
6398 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
6399 unsigned TypeBits = Cst1->getBitWidth();
6400 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
6401 if (ShAmt < TypeBits && ShAmt != 0) {
6402 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6403 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
6404 Value *And =
6405 Builder.CreateAnd(Xor, Builder.getInt(AndVal), I.getName() + ".mask");
6406 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
6407 }
6408 }
6409
6410 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
6411 // "icmp (and X, mask), cst"
6412 uint64_t ShAmt = 0;
6413 if (Op0->hasOneUse() &&
6414 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
6415 match(Op1, m_ConstantInt(Cst1)) &&
6416 // Only do this when A has multiple uses. This is most important to do
6417 // when it exposes other optimizations.
6418 !A->hasOneUse()) {
6419 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
6420
6421 if (ShAmt < ASize) {
6422 APInt MaskV =
6424 MaskV <<= ShAmt;
6425
6426 APInt CmpV = Cst1->getValue().zext(ASize);
6427 CmpV <<= ShAmt;
6428
6429 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
6430 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
6431 }
6432 }
6433
6435 return ICmp;
6436
6437 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
6438 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
6439 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
6440 // few steps of instcombine.
6441 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6442 if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
6444 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
6445 (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
6447 Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
6448 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
6450 Add, ConstantInt::get(A->getType(), C.shl(1)));
6451 }
6452
6453 // Canonicalize:
6454 // Assume B_Pow2 != 0
6455 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
6456 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
6457 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
6458 isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, &I))
6459 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
6461
6462 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
6463 isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, &I))
6464 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
6465 ConstantInt::getNullValue(Op1->getType()));
6466
6467 // Canonicalize:
6468 // icmp eq/ne X, OneUse(rotate-right(X))
6469 // -> icmp eq/ne X, rotate-left(X)
6470 // We generally try to convert rotate-right -> rotate-left, this just
6471 // canonicalizes another case.
6472 if (match(&I, m_c_ICmp(m_Value(A),
6474 m_Deferred(A), m_Deferred(A), m_Value(B))))))
6475 return new ICmpInst(
6476 Pred, A,
6477 Builder.CreateIntrinsic(Op0->getType(), Intrinsic::fshl, {A, A, B}));
6478
6479 // Canonicalize:
6480 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
6481 Constant *Cst;
6484 return new ICmpInst(Pred, Builder.CreateXor(A, B), Cst);
6485
6486 {
6487 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6488 auto m_Matcher =
6491 m_Sub(m_Value(B), m_Deferred(A)));
6492 std::optional<bool> IsZero = std::nullopt;
6493 if (match(&I, m_c_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)),
6494 m_Deferred(A))))
6495 IsZero = false;
6496 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6497 else if (match(&I,
6498 m_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)), m_Zero())))
6499 IsZero = true;
6500
6501 if (IsZero && isKnownToBeAPowerOfTwo(A, /* OrZero */ true, &I))
6502 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6503 // -> (icmp eq/ne (and X, P2), 0)
6504 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6505 // -> (icmp eq/ne (and X, P2), P2)
6506 return new ICmpInst(Pred, Builder.CreateAnd(B, A),
6507 *IsZero ? A
6508 : ConstantInt::getNullValue(A->getType()));
6509 }
6510
6511 if (auto *Res = foldICmpEqualityWithOffset(
6512 I, Builder, getSimplifyQuery().getWithInstruction(&I)))
6513 return Res;
6514
6515 return nullptr;
6516}
6517
6519 ICmpInst::Predicate Pred = ICmp.getPredicate();
6520 Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
6521
6522 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6523 // The trunc masks high bits while the compare may effectively mask low bits.
6524 Value *X;
6525 const APInt *C;
6526 if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
6527 return nullptr;
6528
6529 // This matches patterns corresponding to tests of the signbit as well as:
6530 // (trunc X) pred C2 --> (X & Mask) == C
6531 if (auto Res = decomposeBitTestICmp(Op0, Op1, Pred, /*LookThroughTrunc=*/true,
6532 /*AllowNonZeroC=*/true)) {
6533 Value *And = Builder.CreateAnd(Res->X, Res->Mask);
6534 Constant *C = ConstantInt::get(Res->X->getType(), Res->C);
6535 return new ICmpInst(Res->Pred, And, C);
6536 }
6537
6538 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6539 if (auto *II = dyn_cast<IntrinsicInst>(X)) {
6540 if (II->getIntrinsicID() == Intrinsic::cttz ||
6541 II->getIntrinsicID() == Intrinsic::ctlz) {
6542 unsigned MaxRet = SrcBits;
6543 // If the "is_zero_poison" argument is set, then we know at least
6544 // one bit is set in the input, so the result is always at least one
6545 // less than the full bitwidth of that input.
6546 if (match(II->getArgOperand(1), m_One()))
6547 MaxRet--;
6548
6549 // Make sure the destination is wide enough to hold the largest output of
6550 // the intrinsic.
6551 if (llvm::Log2_32(MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6552 if (Instruction *I =
6553 foldICmpIntrinsicWithConstant(ICmp, II, C->zext(SrcBits)))
6554 return I;
6555 }
6556 }
6557
6558 return nullptr;
6559}
6560
6562 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6563 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
6564 Value *X;
6565 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
6566 return nullptr;
6567
6568 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6569 bool IsSignedCmp = ICmp.isSigned();
6570
6571 // icmp Pred (ext X), (ext Y)
6572 Value *Y;
6573 if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
6574 bool IsZext0 = isa<ZExtInst>(ICmp.getOperand(0));
6575 bool IsZext1 = isa<ZExtInst>(ICmp.getOperand(1));
6576
6577 if (IsZext0 != IsZext1) {
6578 // If X and Y and both i1
6579 // (icmp eq/ne (zext X) (sext Y))
6580 // eq -> (icmp eq (or X, Y), 0)
6581 // ne -> (icmp ne (or X, Y), 0)
6582 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(1) &&
6583 Y->getType()->isIntOrIntVectorTy(1))
6584 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
6585 Constant::getNullValue(X->getType()));
6586
6587 // If we have mismatched casts and zext has the nneg flag, we can
6588 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6589
6590 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(0));
6591 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(1));
6592
6593 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6594 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6595
6596 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6597 IsSignedExt = true;
6598 else
6599 return nullptr;
6600 }
6601
6602 // Not an extension from the same type?
6603 Type *XTy = X->getType(), *YTy = Y->getType();
6604 if (XTy != YTy) {
6605 // One of the casts must have one use because we are creating a new cast.
6606 if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
6607 return nullptr;
6608 // Extend the narrower operand to the type of the wider operand.
6609 CastInst::CastOps CastOpcode =
6610 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6611 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6612 X = Builder.CreateCast(CastOpcode, X, YTy);
6613 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6614 Y = Builder.CreateCast(CastOpcode, Y, XTy);
6615 else
6616 return nullptr;
6617 }
6618
6619 // (zext X) == (zext Y) --> X == Y
6620 // (sext X) == (sext Y) --> X == Y
6621 if (ICmp.isEquality())
6622 return new ICmpInst(ICmp.getPredicate(), X, Y);
6623
6624 // A signed comparison of sign extended values simplifies into a
6625 // signed comparison.
6626 if (IsSignedCmp && IsSignedExt)
6627 return new ICmpInst(ICmp.getPredicate(), X, Y);
6628
6629 // The other three cases all fold into an unsigned comparison.
6630 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6631 }
6632
6633 // Below here, we are only folding a compare with constant.
6634 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
6635 if (!C)
6636 return nullptr;
6637
6638 // If a lossless truncate is possible...
6639 Type *SrcTy = CastOp0->getSrcTy();
6640 Constant *Res = getLosslessInvCast(C, SrcTy, CastOp0->getOpcode(), DL);
6641 if (Res) {
6642 if (ICmp.isEquality())
6643 return new ICmpInst(ICmp.getPredicate(), X, Res);
6644
6645 // A signed comparison of sign extended values simplifies into a
6646 // signed comparison.
6647 if (IsSignedExt && IsSignedCmp)
6648 return new ICmpInst(ICmp.getPredicate(), X, Res);
6649
6650 // The other three cases all fold into an unsigned comparison.
6651 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6652 }
6653
6654 // The re-extended constant changed, partly changed (in the case of a vector),
6655 // or could not be determined to be equal (in the case of a constant
6656 // expression), so the constant cannot be represented in the shorter type.
6657 // All the cases that fold to true or false will have already been handled
6658 // by simplifyICmpInst, so only deal with the tricky case.
6659 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
6660 return nullptr;
6661
6662 // Is source op positive?
6663 // icmp ult (sext X), C --> icmp sgt X, -1
6664 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6666
6667 // Is source op negative?
6668 // icmp ugt (sext X), C --> icmp slt X, 0
6669 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6671}
6672
6673/// Handle icmp (cast x), (cast or constant).
6675 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6676 // icmp compares only pointer's value.
6677 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6678 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
6679 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
6680 if (SimplifiedOp0 || SimplifiedOp1)
6681 return new ICmpInst(ICmp.getPredicate(),
6682 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
6683 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
6684
6685 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
6686 Value *Op1 = ICmp.getOperand(1);
6687 if (!CastOp0)
6688 return nullptr;
6689 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
6690 return nullptr;
6691
6692 Value *Op0Src = CastOp0->getOperand(0);
6693 Type *SrcTy = CastOp0->getSrcTy();
6694 Type *DestTy = CastOp0->getDestTy();
6695
6696 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6697 // integer type is the same size as the pointer type.
6698 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6699 unsigned IntWidth = IntTy->getScalarType()->getIntegerBitWidth();
6700 unsigned IndexWidth = DL.getAddressSizeInBits(PtrTy);
6701 unsigned PtrWidth = DL.getPointerTypeSizeInBits(PtrTy);
6702 // For ptrtoint/inttoptr, we must check that IntWidth == IndexWidth and also
6703 // IndexWidth == PtrWidth to (not) handle non-integral pointers.
6704 return IntWidth == IndexWidth && IndexWidth == PtrWidth;
6705 };
6706 if (isa<PtrToIntInst, PtrToAddrInst>(CastOp0)) {
6707 bool HasPtrToInt = isa<PtrToIntInst>(CastOp0);
6708 Value *NewOp1 = nullptr;
6709 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(Op1)) {
6710 NewOp1 = PtrToIntOp1->getOperand(0);
6711 HasPtrToInt = true;
6712 } else if (auto *PtrToAddrOp1 = dyn_cast<PtrToAddrOperator>(Op1)) {
6713 NewOp1 = PtrToAddrOp1->getOperand(0);
6714 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6715 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6716 }
6717
6718 // For ptrtoaddr, IntWidth == IndexWidth is implied and we don't need to
6719 // check PtrWidth.
6720 if ((!HasPtrToInt || CompatibleSizes(SrcTy, DestTy)) &&
6721 (NewOp1 && NewOp1->getType() == Op0Src->getType()))
6722 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6723 }
6724
6725 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6726 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6727 CompatibleSizes(DestTy, SrcTy)) {
6728 Value *NewOp1 = nullptr;
6729 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(Op1)) {
6730 Value *IntSrc = IntToPtrOp1->getOperand(0);
6731 if (IntSrc->getType() == Op0Src->getType())
6732 NewOp1 = IntToPtrOp1->getOperand(0);
6733 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6734 NewOp1 = ConstantFoldConstant(ConstantExpr::getPtrToInt(RHSC, SrcTy), DL);
6735 }
6736
6737 if (NewOp1)
6738 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6739 }
6740
6741 if (Instruction *R = foldICmpWithTrunc(ICmp))
6742 return R;
6743
6744 return foldICmpWithZextOrSext(ICmp);
6745}
6746
6748 bool IsSigned) {
6749 switch (BinaryOp) {
6750 default:
6751 llvm_unreachable("Unsupported binary op");
6752 case Instruction::Add:
6753 case Instruction::Sub:
6754 return match(RHS, m_Zero());
6755 case Instruction::Mul:
6756 return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
6757 match(RHS, m_One());
6758 }
6759}
6760
6763 bool IsSigned, Value *LHS, Value *RHS,
6764 Instruction *CtxI) const {
6765 switch (BinaryOp) {
6766 default:
6767 llvm_unreachable("Unsupported binary op");
6768 case Instruction::Add:
6769 if (IsSigned)
6770 return computeOverflowForSignedAdd(LHS, RHS, CtxI);
6771 else
6772 return computeOverflowForUnsignedAdd(LHS, RHS, CtxI);
6773 case Instruction::Sub:
6774 if (IsSigned)
6775 return computeOverflowForSignedSub(LHS, RHS, CtxI);
6776 else
6777 return computeOverflowForUnsignedSub(LHS, RHS, CtxI);
6778 case Instruction::Mul:
6779 if (IsSigned)
6780 return computeOverflowForSignedMul(LHS, RHS, CtxI);
6781 else
6782 return computeOverflowForUnsignedMul(LHS, RHS, CtxI);
6783 }
6784}
6785
6786bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6787 bool IsSigned, Value *LHS,
6788 Value *RHS, Instruction &OrigI,
6789 Value *&Result,
6790 Constant *&Overflow) {
6791 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
6792 std::swap(LHS, RHS);
6793
6794 // If the overflow check was an add followed by a compare, the insertion point
6795 // may be pointing to the compare. We want to insert the new instructions
6796 // before the add in case there are uses of the add between the add and the
6797 // compare.
6798 Builder.SetInsertPoint(&OrigI);
6799
6800 Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
6801 if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
6802 OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
6803
6804 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6805 Result = LHS;
6806 Overflow = ConstantInt::getFalse(OverflowTy);
6807 return true;
6808 }
6809
6810 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
6812 return false;
6815 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6816 Result->takeName(&OrigI);
6817 Overflow = ConstantInt::getTrue(OverflowTy);
6818 return true;
6820 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6821 Result->takeName(&OrigI);
6822 Overflow = ConstantInt::getFalse(OverflowTy);
6823 if (auto *Inst = dyn_cast<Instruction>(Result)) {
6824 if (IsSigned)
6825 Inst->setHasNoSignedWrap();
6826 else
6827 Inst->setHasNoUnsignedWrap();
6828 }
6829 return true;
6830 }
6831
6832 llvm_unreachable("Unexpected overflow result");
6833}
6834
6835/// Recognize and process idiom involving test for unsigned
6836/// overflow.
6837///
6838/// The caller has matched a pattern of the form:
6839/// I = cmp u (add(zext A, zext B), V
6840/// I = cmp u (mul(zext A, zext B), V
6841/// The function checks if this is a test for overflow and if so replaces
6842/// addition/multiplication with call to the umul intrinsic or the canonical
6843/// form of uadd overflow.
6844///
6845/// \param I Compare instruction.
6846/// \param Val Result of add/mul instruction. It is one of the arguments of
6847/// the compare instruction. Must be of integer type.
6848/// \param OtherVal The other argument of compare instruction.
6849/// \returns Instruction which must replace the compare instruction, NULL if no
6850/// replacement required.
6852 const APInt *OtherVal,
6853 InstCombinerImpl &IC) {
6854 // Don't bother doing this transformation for pointers, don't do it for
6855 // vectors.
6856 if (!isa<IntegerType>(Val->getType()))
6857 return nullptr;
6858
6859 auto *Instr = cast<Instruction>(Val);
6860 unsigned Opcode = Instr->getOpcode();
6861 assert(Opcode == Instruction::Add || Opcode == Instruction::Mul);
6862
6863 auto *LHS = cast<ZExtInst>(Instr->getOperand(0)),
6864 *RHS = cast<ZExtInst>(Instr->getOperand(1));
6865 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
6866
6867 // Calculate type and width of the result produced by add/mul.with.overflow.
6868 Type *TyA = A->getType(), *TyB = B->getType();
6869 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6870 WidthB = TyB->getPrimitiveSizeInBits();
6871 unsigned ResultWidth;
6872 Type *ResultType;
6873 if (WidthB > WidthA) {
6874 ResultWidth = WidthB;
6875 ResultType = TyB;
6876 } else {
6877 ResultWidth = WidthA;
6878 ResultType = TyA;
6879 }
6880
6881 // In order to replace the original result with a narrower one, all uses must
6882 // ignore upper bits of the result. The number of used low bits must be not
6883 // greater than the width of add or mul.with.overflow.
6884 if (Val->hasNUsesOrMore(2))
6885 for (User *U : Val->users()) {
6886 if (U == &I)
6887 continue;
6888 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6889 // Check if truncation ignores bits above ResultWidth.
6890 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
6891 if (TruncWidth > ResultWidth)
6892 return nullptr;
6893 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6894 // Check if AND ignores bits above ResultWidth.
6895 if (BO->getOpcode() != Instruction::And)
6896 return nullptr;
6897 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6898 const APInt &CVal = CI->getValue();
6899 if (CVal.getBitWidth() - CVal.countl_zero() > ResultWidth)
6900 return nullptr;
6901 } else {
6902 // In this case we could have the operand of the binary operation
6903 // being defined in another block, and performing the replacement
6904 // could break the dominance relation.
6905 return nullptr;
6906 }
6907 } else {
6908 // Other uses prohibit this transformation.
6909 return nullptr;
6910 }
6911 }
6912
6913 // Recognize patterns
6914 switch (I.getPredicate()) {
6915 case ICmpInst::ICMP_UGT: {
6916 // Recognize pattern:
6917 // val = add/mul(zext A, zext B)
6918 // cmp ugt val, max
6919 APInt MaxVal = APInt::getMaxValue(ResultWidth);
6920 MaxVal = MaxVal.zext(OtherVal->getBitWidth());
6921 if (MaxVal.eq(*OtherVal))
6922 break; // Recognized
6923 return nullptr;
6924 }
6925
6926 case ICmpInst::ICMP_ULT: {
6927 // Recognize pattern:
6928 // val = add/mul(zext A, zext B)
6929 // cmp ult val, max + 1
6930 APInt MaxVal = APInt::getOneBitSet(OtherVal->getBitWidth(), ResultWidth);
6931 if (MaxVal.eq(*OtherVal))
6932 break; // Recognized
6933 return nullptr;
6934 }
6935
6936 default:
6937 return nullptr;
6938 }
6939
6940 InstCombiner::BuilderTy &Builder = IC.Builder;
6941 Builder.SetInsertPoint(Instr);
6942
6943 // Replace: add/mul(zext A, zext B) --> canonical add/mul + overflow check
6944 Value *ResultA = A, *ResultB = B;
6945 if (WidthA < ResultWidth)
6946 ResultA = Builder.CreateZExt(A, ResultType);
6947 if (WidthB < ResultWidth)
6948 ResultB = Builder.CreateZExt(B, ResultType);
6949
6950 Value *ArithResult;
6951 Value *OverflowCheck;
6952
6953 if (Opcode == Instruction::Add) {
6954 // Canonical add overflow check: add + compare
6955 ArithResult = Builder.CreateAdd(ResultA, ResultB, "add");
6956 // Overflow if result < either operand (for unsigned add)
6957 if (I.getPredicate() == ICmpInst::ICMP_ULT)
6958 OverflowCheck =
6959 Builder.CreateICmpUGE(ArithResult, ResultA, "not.add.overflow");
6960 else
6961 OverflowCheck =
6962 Builder.CreateICmpULT(ArithResult, ResultA, "add.overflow");
6963 } else {
6964 // For multiplication, the intrinsic is actually the canonical form
6965 Value *Call = Builder.CreateIntrinsic(Intrinsic::umul_with_overflow,
6966 ResultType, {ResultA, ResultB},
6967 /*FMFSource=*/nullptr, "umul");
6968 ArithResult = Builder.CreateExtractValue(Call, 0, "umul.value");
6969 OverflowCheck = Builder.CreateExtractValue(Call, 1, "umul.overflow");
6970 if (I.getPredicate() == ICmpInst::ICMP_ULT)
6971 OverflowCheck = Builder.CreateNot(OverflowCheck);
6972 }
6973
6974 IC.addToWorklist(Instr);
6975
6976 // Replace uses of the original add/mul result with the new arithmetic result
6977 if (Val->hasNUsesOrMore(2)) {
6978 for (User *U : make_early_inc_range(Val->users())) {
6979 if (U == &I)
6980 continue;
6981 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6982 if (TI->getType()->getPrimitiveSizeInBits() == ResultWidth)
6983 IC.replaceInstUsesWith(*TI, ArithResult);
6984 else
6985 TI->setOperand(0, ArithResult);
6986 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6987 assert(BO->getOpcode() == Instruction::And);
6988 // Replace (ArithResult & mask) --> zext (ArithResult & short_mask)
6989 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
6990 APInt ShortMask = CI->getValue().trunc(ResultWidth);
6991 Value *ShortAnd = Builder.CreateAnd(ArithResult, ShortMask);
6992 Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
6993 IC.replaceInstUsesWith(*BO, Zext);
6994 } else {
6995 llvm_unreachable("Unexpected Binary operation");
6996 }
6998 }
6999 }
7000
7001 return IC.replaceInstUsesWith(I, OverflowCheck);
7002}
7003
7004/// When performing a comparison against a constant, it is possible that not all
7005/// the bits in the LHS are demanded. This helper method computes the mask that
7006/// IS demanded.
7008 const APInt *RHS;
7009 if (!match(I.getOperand(1), m_APInt(RHS)))
7011
7012 // If this is a normal comparison, it demands all bits. If it is a sign bit
7013 // comparison, it only demands the sign bit.
7014 bool UnusedBit;
7015 if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
7017
7018 switch (I.getPredicate()) {
7019 // For a UGT comparison, we don't care about any bits that
7020 // correspond to the trailing ones of the comparand. The value of these
7021 // bits doesn't impact the outcome of the comparison, because any value
7022 // greater than the RHS must differ in a bit higher than these due to carry.
7023 case ICmpInst::ICMP_UGT:
7024 return APInt::getBitsSetFrom(BitWidth, RHS->countr_one());
7025
7026 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
7027 // Any value less than the RHS must differ in a higher bit because of carries.
7028 case ICmpInst::ICMP_ULT:
7029 return APInt::getBitsSetFrom(BitWidth, RHS->countr_zero());
7030
7031 default:
7033 }
7034}
7035
7036/// Check that one use is in the same block as the definition and all
7037/// other uses are in blocks dominated by a given block.
7038///
7039/// \param DI Definition
7040/// \param UI Use
7041/// \param DB Block that must dominate all uses of \p DI outside
7042/// the parent block
7043/// \return true when \p UI is the only use of \p DI in the parent block
7044/// and all other uses of \p DI are in blocks dominated by \p DB.
7045///
7047 const Instruction *UI,
7048 const BasicBlock *DB) const {
7049 assert(DI && UI && "Instruction not defined\n");
7050 // Ignore incomplete definitions.
7051 if (!DI->getParent())
7052 return false;
7053 // DI and UI must be in the same block.
7054 if (DI->getParent() != UI->getParent())
7055 return false;
7056 // Protect from self-referencing blocks.
7057 if (DI->getParent() == DB)
7058 return false;
7059 for (const User *U : DI->users()) {
7060 auto *Usr = cast<Instruction>(U);
7061 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
7062 return false;
7063 }
7064 return true;
7065}
7066
7067/// Return true when the instruction sequence within a block is select-cmp-br.
7069 const BasicBlock *BB = SI->getParent();
7070 if (!BB)
7071 return false;
7073 if (!BI)
7074 return false;
7075 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
7076 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
7077 return false;
7078 return true;
7079}
7080
7081/// True when a select result is replaced by one of its operands
7082/// in select-icmp sequence. This will eventually result in the elimination
7083/// of the select.
7084///
7085/// \param SI Select instruction
7086/// \param Icmp Compare instruction
7087/// \param SIOpd Operand that replaces the select
7088///
7089/// Notes:
7090/// - The replacement is global and requires dominator information
7091/// - The caller is responsible for the actual replacement
7092///
7093/// Example:
7094///
7095/// entry:
7096/// %4 = select i1 %3, %C* %0, %C* null
7097/// %5 = icmp eq %C* %4, null
7098/// br i1 %5, label %9, label %7
7099/// ...
7100/// ; <label>:7 ; preds = %entry
7101/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
7102/// ...
7103///
7104/// can be transformed to
7105///
7106/// %5 = icmp eq %C* %0, null
7107/// %6 = select i1 %3, i1 %5, i1 true
7108/// br i1 %6, label %9, label %7
7109/// ...
7110/// ; <label>:7 ; preds = %entry
7111/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
7112///
7113/// Similar when the first operand of the select is a constant or/and
7114/// the compare is for not equal rather than equal.
7115///
7116/// NOTE: The function is only called when the select and compare constants
7117/// are equal, the optimization can work only for EQ predicates. This is not a
7118/// major restriction since a NE compare should be 'normalized' to an equal
7119/// compare, which usually happens in the combiner and test case
7120/// select-cmp-br.ll checks for it.
7122 const ICmpInst *Icmp,
7123 const unsigned SIOpd) {
7124 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
7126 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
7127 // The check for the single predecessor is not the best that can be
7128 // done. But it protects efficiently against cases like when SI's
7129 // home block has two successors, Succ and Succ1, and Succ1 predecessor
7130 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
7131 // replaced can be reached on either path. So the uniqueness check
7132 // guarantees that the path all uses of SI (outside SI's parent) are on
7133 // is disjoint from all other paths out of SI. But that information
7134 // is more expensive to compute, and the trade-off here is in favor
7135 // of compile-time. It should also be noticed that we check for a single
7136 // predecessor and not only uniqueness. This to handle the situation when
7137 // Succ and Succ1 points to the same basic block.
7138 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
7139 NumSel++;
7140 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
7141 return true;
7142 }
7143 }
7144 return false;
7145}
7146
7147/// Try to fold the comparison based on range information we can get by checking
7148/// whether bits are known to be zero or one in the inputs.
7150 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7151 Type *Ty = Op0->getType();
7152 ICmpInst::Predicate Pred = I.getPredicate();
7153
7154 // Get scalar or pointer size.
7155 unsigned BitWidth = Ty->isIntOrIntVectorTy()
7156 ? Ty->getScalarSizeInBits()
7157 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
7158
7159 if (!BitWidth)
7160 return nullptr;
7161
7162 KnownBits Op0Known(BitWidth);
7163 KnownBits Op1Known(BitWidth);
7164
7165 {
7166 // Don't use dominating conditions when folding icmp using known bits. This
7167 // may convert signed into unsigned predicates in ways that other passes
7168 // (especially IndVarSimplify) may not be able to reliably undo.
7169 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(&I);
7171 Op0Known, Q))
7172 return &I;
7173
7174 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, Q))
7175 return &I;
7176 }
7177
7178 // If an unsigned samesign comparison is not poison, both operands have the
7179 // same sign bit. Propagate a known sign bit between the temporary KnownBits
7180 // values so the existing range folds can use that constraint.
7181 if (I.hasSameSign() && I.isUnsigned()) {
7182 auto PropagateSignBit = [](const KnownBits &From, KnownBits &To) {
7183 if (To.isNegative() || To.isNonNegative())
7184 return;
7185 if (From.isNegative())
7186 To.makeNegative();
7187 else if (From.isNonNegative())
7188 To.makeNonNegative();
7189 };
7190 PropagateSignBit(Op0Known, Op1Known);
7191 PropagateSignBit(Op1Known, Op0Known);
7192 }
7193
7194 if (!isa<Constant>(Op0) && Op0Known.isConstant())
7195 return new ICmpInst(
7196 Pred, ConstantExpr::getIntegerValue(Ty, Op0Known.getConstant()), Op1);
7197 if (!isa<Constant>(Op1) && Op1Known.isConstant())
7198 return new ICmpInst(
7199 Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Known.getConstant()));
7200
7201 if (std::optional<bool> Res = ICmpInst::compare(Op0Known, Op1Known, Pred))
7202 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *Res));
7203
7204 // Given the known and unknown bits, compute a range that the LHS could be
7205 // in. Compute the Min, Max and RHS values based on the known bits. For the
7206 // EQ and NE we use unsigned values.
7207 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
7208 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
7209 if (I.isSigned()) {
7210 Op0Min = Op0Known.getSignedMinValue();
7211 Op0Max = Op0Known.getSignedMaxValue();
7212 Op1Min = Op1Known.getSignedMinValue();
7213 Op1Max = Op1Known.getSignedMaxValue();
7214 } else {
7215 Op0Min = Op0Known.getMinValue();
7216 Op0Max = Op0Known.getMaxValue();
7217 Op1Min = Op1Known.getMinValue();
7218 Op1Max = Op1Known.getMaxValue();
7219 }
7220
7221 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
7222 // min/max canonical compare with some other compare. That could lead to
7223 // conflict with select canonicalization and infinite looping.
7224 // FIXME: This constraint may go away if min/max intrinsics are canonical.
7225 auto isMinMaxCmp = [&](Instruction &Cmp) {
7226 if (!Cmp.hasOneUse())
7227 return false;
7228 Value *A, *B;
7229 SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
7231 return false;
7232 return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
7233 match(Op1, m_MaxOrMin(m_Value(), m_Value()));
7234 };
7235 if (!isMinMaxCmp(I)) {
7236 switch (Pred) {
7237 default:
7238 break;
7239 case ICmpInst::ICMP_ULT: {
7240 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
7241 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7242 const APInt *CmpC;
7243 if (match(Op1, m_APInt(CmpC))) {
7244 // A <u C -> A == C-1 if min(A)+1 == C
7245 if (*CmpC == Op0Min + 1)
7246 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7247 ConstantInt::get(Op1->getType(), *CmpC - 1));
7248 // X <u C --> X == 0, if the number of zero bits in the bottom of X
7249 // exceeds the log2 of C.
7250 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
7251 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7252 Constant::getNullValue(Op1->getType()));
7253 }
7254 break;
7255 }
7256 case ICmpInst::ICMP_UGT: {
7257 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
7258 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7259 const APInt *CmpC;
7260 if (match(Op1, m_APInt(CmpC))) {
7261 // A >u C -> A == C+1 if max(a)-1 == C
7262 if (*CmpC == Op0Max - 1)
7263 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7264 ConstantInt::get(Op1->getType(), *CmpC + 1));
7265 // X >u C --> X != 0, if the number of zero bits in the bottom of X
7266 // exceeds the log2 of C.
7267 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
7268 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
7269 Constant::getNullValue(Op1->getType()));
7270 }
7271 break;
7272 }
7273 case ICmpInst::ICMP_SLT: {
7274 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
7275 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7276 const APInt *CmpC;
7277 if (match(Op1, m_APInt(CmpC))) {
7278 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
7279 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7280 ConstantInt::get(Op1->getType(), *CmpC - 1));
7281 }
7282 break;
7283 }
7284 case ICmpInst::ICMP_SGT: {
7285 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
7286 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7287 const APInt *CmpC;
7288 if (match(Op1, m_APInt(CmpC))) {
7289 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
7290 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7291 ConstantInt::get(Op1->getType(), *CmpC + 1));
7292 }
7293 break;
7294 }
7295 }
7296 }
7297
7298 // Based on the range information we know about the LHS, see if we can
7299 // simplify this comparison. For example, (x&4) < 8 is always true.
7300 switch (Pred) {
7301 default:
7302 break;
7303 case ICmpInst::ICMP_EQ:
7304 case ICmpInst::ICMP_NE: {
7305 // If all bits are known zero except for one, then we know at most one bit
7306 // is set. If the comparison is against zero, then this is a check to see if
7307 // *that* bit is set.
7308 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
7309 if (Op1Known.isZero()) {
7310 // If the LHS is an AND with the same constant, look through it.
7311 Value *LHS = nullptr;
7312 const APInt *LHSC;
7313 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
7314 *LHSC != Op0KnownZeroInverted)
7315 LHS = Op0;
7316
7317 Value *X;
7318 const APInt *C1;
7319 if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
7320 Type *XTy = X->getType();
7321 unsigned Log2C1 = C1->countr_zero();
7322 APInt C2 = Op0KnownZeroInverted;
7323 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
7324 if (C2Pow2.isPowerOf2()) {
7325 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
7326 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
7327 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
7328 unsigned Log2C2 = C2Pow2.countr_zero();
7329 auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
7330 auto NewPred =
7332 return new ICmpInst(NewPred, X, CmpC);
7333 }
7334 }
7335 }
7336
7337 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
7338 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
7339 (Op0Known & Op1Known) == Op0Known)
7340 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
7341 ConstantInt::getNullValue(Op1->getType()));
7342 break;
7343 }
7344 case ICmpInst::ICMP_SGE:
7345 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
7346 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7347 break;
7348 case ICmpInst::ICMP_SLE:
7349 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
7350 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7351 break;
7352 case ICmpInst::ICMP_UGE:
7353 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
7354 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7355 break;
7356 case ICmpInst::ICMP_ULE:
7357 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
7358 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7359 break;
7360 }
7361
7362 // Turn a signed comparison into an unsigned one if both operands are known to
7363 // have the same sign. Set samesign if possible (except for equality
7364 // predicates).
7365 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
7366 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
7367 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
7368 I.setPredicate(I.getUnsignedPredicate());
7369 I.setSameSign();
7370 return &I;
7371 }
7372
7373 return nullptr;
7374}
7375
7376/// If one operand of an icmp is effectively a bool (value range of {0,1}),
7377/// then try to reduce patterns based on that limit.
7379 Value *X, *Y;
7380 CmpPredicate Pred;
7381
7382 // X must be 0 and bool must be true for "ULT":
7383 // X <u (zext i1 Y) --> (X == 0) & Y
7384 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
7385 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
7386 return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
7387
7388 // X must be 0 or bool must be true for "ULE":
7389 // X <=u (sext i1 Y) --> (X == 0) | Y
7390 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
7391 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
7392 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
7393
7394 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
7395 CmpPredicate Pred1, Pred2;
7396 const APInt *C;
7397 Instruction *ExtI;
7398 if (match(&I, m_c_ICmp(Pred1, m_Value(X),
7401 m_APInt(C)))))) &&
7402 ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
7403 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
7404 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(0)->hasOneUse();
7405 auto CreateRangeCheck = [&] {
7406 Value *CmpV1 =
7407 Builder.CreateICmp(Pred1, X, Constant::getNullValue(X->getType()));
7408 Value *CmpV2 = Builder.CreateICmp(
7409 Pred1, X, ConstantInt::getSigned(X->getType(), IsSExt ? -1 : 1));
7411 Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
7412 CmpV1, CmpV2);
7413 };
7414 if (C->isZero()) {
7415 if (Pred2 == ICmpInst::ICMP_EQ) {
7416 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
7417 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
7418 return replaceInstUsesWith(
7419 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7420 } else if (!IsSExt || HasOneUse) {
7421 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
7422 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
7423 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
7424 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X != -1
7425 return CreateRangeCheck();
7426 }
7427 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
7428 if (Pred2 == ICmpInst::ICMP_NE) {
7429 // icmp eq X, (zext (icmp ne X, 1)) --> false
7430 // icmp ne X, (zext (icmp ne X, 1)) --> true
7431 // icmp eq X, (sext (icmp ne X, -1)) --> false
7432 // icmp ne X, (sext (icmp ne X, -1)) --> true
7433 return replaceInstUsesWith(
7434 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7435 } else if (!IsSExt || HasOneUse) {
7436 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
7437 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
7438 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
7439 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
7440 return CreateRangeCheck();
7441 }
7442 } else {
7443 // when C != 0 && C != 1:
7444 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
7445 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
7446 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
7447 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
7448 // when C != 0 && C != -1:
7449 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
7450 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
7451 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
7452 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
7453 return ICmpInst::Create(
7454 Instruction::ICmp, Pred1, X,
7455 ConstantInt::getSigned(X->getType(), Pred2 == ICmpInst::ICMP_NE
7456 ? (IsSExt ? -1 : 1)
7457 : 0));
7458 }
7459 }
7460
7461 return nullptr;
7462}
7463
7464/// If we have an icmp le or icmp ge instruction with a constant operand, turn
7465/// it into the appropriate icmp lt or icmp gt instruction. This transform
7466/// allows them to be folded in visitICmpInst.
7468 CmpPredicate Pred = I.getCmpPredicate();
7469 if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
7471 return nullptr;
7472
7473 Value *Op0 = I.getOperand(0);
7474 Value *Op1 = I.getOperand(1);
7475 auto *Op1C = dyn_cast<Constant>(Op1);
7476 if (!Op1C)
7477 return nullptr;
7478
7479 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
7480 if (!FlippedStrictness)
7481 return nullptr;
7482
7483 auto *NewCmp =
7484 new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7485 NewCmp->setSameSign(FlippedStrictness->first.hasSameSign());
7486 return NewCmp;
7487}
7488
7489/// If we have a comparison with a non-canonical predicate, if we can update
7490/// all the users, invert the predicate and adjust all the users.
7492 // Is the predicate already canonical?
7493 CmpInst::Predicate Pred = I.getPredicate();
7495 return nullptr;
7496
7497 // Can all users be adjusted to predicate inversion?
7498 if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
7499 return nullptr;
7500
7501 // Ok, we can canonicalize comparison!
7502 // Let's first invert the comparison's predicate.
7503 I.setPredicate(CmpInst::getInversePredicate(Pred));
7504 I.setName(I.getName() + ".not");
7505
7506 // And, adapt users.
7508
7509 return &I;
7510}
7511
7512/// Integer compare with boolean values can always be turned into bitwise ops.
7514 InstCombiner::BuilderTy &Builder) {
7515 Value *A = I.getOperand(0), *B = I.getOperand(1);
7516 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
7517
7518 // A boolean compared to true/false can be simplified to Op0/true/false in
7519 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
7520 // Cases not handled by InstSimplify are always 'not' of Op0.
7521 if (match(B, m_Zero())) {
7522 switch (I.getPredicate()) {
7523 case CmpInst::ICMP_EQ: // A == 0 -> !A
7524 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
7525 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7527 default:
7528 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7529 }
7530 } else if (match(B, m_One())) {
7531 switch (I.getPredicate()) {
7532 case CmpInst::ICMP_NE: // A != 1 -> !A
7533 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7534 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7536 default:
7537 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7538 }
7539 }
7540
7541 switch (I.getPredicate()) {
7542 default:
7543 llvm_unreachable("Invalid icmp instruction!");
7544 case ICmpInst::ICMP_EQ:
7545 // icmp eq i1 A, B -> ~(A ^ B)
7546 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
7547
7548 case ICmpInst::ICMP_NE:
7549 // icmp ne i1 A, B -> A ^ B
7550 return BinaryOperator::CreateXor(A, B);
7551
7552 case ICmpInst::ICMP_UGT:
7553 // icmp ugt -> icmp ult
7554 std::swap(A, B);
7555 [[fallthrough]];
7556 case ICmpInst::ICMP_ULT:
7557 // icmp ult i1 A, B -> ~A & B
7558 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
7559
7560 case ICmpInst::ICMP_SGT:
7561 // icmp sgt -> icmp slt
7562 std::swap(A, B);
7563 [[fallthrough]];
7564 case ICmpInst::ICMP_SLT:
7565 // icmp slt i1 A, B -> A & ~B
7566 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
7567
7568 case ICmpInst::ICMP_UGE:
7569 // icmp uge -> icmp ule
7570 std::swap(A, B);
7571 [[fallthrough]];
7572 case ICmpInst::ICMP_ULE:
7573 // icmp ule i1 A, B -> ~A | B
7574 return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
7575
7576 case ICmpInst::ICMP_SGE:
7577 // icmp sge -> icmp sle
7578 std::swap(A, B);
7579 [[fallthrough]];
7580 case ICmpInst::ICMP_SLE:
7581 // icmp sle i1 A, B -> A | ~B
7582 return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
7583 }
7584}
7585
7586// Transform pattern like:
7587// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7588// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7589// Into:
7590// (X l>> Y) != 0
7591// (X l>> Y) == 0
7593 InstCombiner::BuilderTy &Builder) {
7594 CmpPredicate Pred, NewPred;
7595 Value *X, *Y;
7596 if (match(&Cmp,
7597 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
7598 switch (Pred) {
7599 case ICmpInst::ICMP_ULE:
7600 NewPred = ICmpInst::ICMP_NE;
7601 break;
7602 case ICmpInst::ICMP_UGT:
7603 NewPred = ICmpInst::ICMP_EQ;
7604 break;
7605 default:
7606 return nullptr;
7607 }
7608 } else if (match(&Cmp, m_c_ICmp(Pred,
7611 m_Add(m_Shl(m_One(), m_Value(Y)),
7612 m_AllOnes()))),
7613 m_Value(X)))) {
7614 // The variant with 'add' is not canonical, (the variant with 'not' is)
7615 // we only get it because it has extra uses, and can't be canonicalized,
7616
7617 switch (Pred) {
7618 case ICmpInst::ICMP_ULT:
7619 NewPred = ICmpInst::ICMP_NE;
7620 break;
7621 case ICmpInst::ICMP_UGE:
7622 NewPred = ICmpInst::ICMP_EQ;
7623 break;
7624 default:
7625 return nullptr;
7626 }
7627 } else
7628 return nullptr;
7629
7630 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
7631 Constant *Zero = Constant::getNullValue(NewX->getType());
7632 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
7633}
7634
7636 InstCombiner::BuilderTy &Builder) {
7637 const CmpInst::Predicate Pred = Cmp.getPredicate();
7638 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
7639 Value *V1, *V2;
7640
7641 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7642 Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
7643 if (auto *I = dyn_cast<Instruction>(V))
7644 I->copyIRFlags(&Cmp);
7645 Module *M = Cmp.getModule();
7647 M, Intrinsic::vector_reverse, V->getType());
7648 return CallInst::Create(F, V);
7649 };
7650
7651 if (match(LHS, m_VecReverse(m_Value(V1)))) {
7652 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7653 if (match(RHS, m_VecReverse(m_Value(V2))) &&
7654 (LHS->hasOneUse() || RHS->hasOneUse()))
7655 return createCmpReverse(Pred, V1, V2);
7656
7657 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7658 if (LHS->hasOneUse() && isSplatValue(RHS))
7659 return createCmpReverse(Pred, V1, RHS);
7660 }
7661 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7662 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
7663 return createCmpReverse(Pred, LHS, V2);
7664
7665 ArrayRef<int> M;
7666 if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
7667 return nullptr;
7668
7669 // If both arguments of the cmp are shuffles that use the same mask and
7670 // shuffle within a single vector, move the shuffle after the cmp:
7671 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7672 Type *V1Ty = V1->getType();
7673 if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
7674 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7675 Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
7676 return new ShuffleVectorInst(NewCmp, M);
7677 }
7678
7679 // Try to canonicalize compare with splatted operand and splat constant.
7680 // TODO: We could generalize this for more than splats. See/use the code in
7681 // InstCombiner::foldVectorBinop().
7682 Constant *C;
7683 if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
7684 return nullptr;
7685
7686 // Length-changing splats are ok, so adjust the constants as needed:
7687 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7688 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7689 int MaskSplatIndex;
7690 if (ScalarC && match(M, m_SplatOrPoisonMask(MaskSplatIndex))) {
7691 // We allow poison in matching, but this transform removes it for safety.
7692 // Demanded elements analysis should be able to recover some/all of that.
7693 C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
7694 ScalarC);
7695 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7696 Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
7697 return new ShuffleVectorInst(NewCmp, NewM);
7698 }
7699
7700 return nullptr;
7701}
7702
7703// extract(uadd.with.overflow(A, B), 0) ult A
7704// -> extract(uadd.with.overflow(A, B), 1)
7706 CmpInst::Predicate Pred = I.getPredicate();
7707 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7708
7709 Value *UAddOv;
7710 Value *A, *B;
7711 auto UAddOvResultPat = m_ExtractValue<0>(
7713 if (match(Op0, UAddOvResultPat) &&
7714 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7715 (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
7716 (match(A, m_One()) || match(B, m_One()))) ||
7717 (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
7718 (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
7719 // extract(uadd.with.overflow(A, B), 0) < A
7720 // extract(uadd.with.overflow(A, 1), 0) == 0
7721 // extract(uadd.with.overflow(A, -1), 0) != -1
7722 UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
7723 else if (match(Op1, UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7724 (Op0 == A || Op0 == B))
7725 // A > extract(uadd.with.overflow(A, B), 0)
7726 UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
7727 else
7728 return nullptr;
7729
7730 return ExtractValueInst::Create(UAddOv, 1);
7731}
7732
7734 if (!I.getOperand(0)->getType()->isPointerTy() ||
7736 I.getParent()->getParent(),
7737 I.getOperand(0)->getType()->getPointerAddressSpace())) {
7738 return nullptr;
7739 }
7740 Value *Ptr;
7741 if (match(I.getOperand(0),
7743 match(I.getOperand(1), m_Zero())) {
7744 return ICmpInst::Create(Instruction::ICmp, I.getPredicate(), Ptr,
7745 I.getOperand(1));
7746 }
7747 return nullptr;
7748}
7749
7751 IRBuilderBase &Builder) {
7752 if (!ICmpInst::isEquality(I.getPredicate()))
7753 return nullptr;
7754
7755 // The caller puts constants after non-constants.
7756 Value *Op = I.getOperand(0);
7757 Value *Const = I.getOperand(1);
7758
7759 // For Cond an equality condition, fold
7760 //
7761 // icmp (eq|ne) (vreduce_(or|and) Op), (Zero|AllOnes) ->
7762 // icmp (eq|ne) Op, (Zero|AllOnes)
7763 //
7764 // with a bitcast.
7765 Value *Vec;
7766 if ((match(Const, m_ZeroInt()) &&
7768 m_Value(Vec))))) ||
7769 (match(Const, m_AllOnes()) &&
7771 m_Value(Vec)))))) {
7772 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
7773 if (!VecTy)
7774 return nullptr;
7775 Type *VecEltTy = VecTy->getElementType();
7776 unsigned ScalarBW =
7777 DL.getTypeSizeInBits(VecEltTy) * VecTy->getNumElements();
7778 if (!DL.fitsInLegalInteger(ScalarBW))
7779 return nullptr;
7780 Type *ScalarTy = IntegerType::get(I.getContext(), ScalarBW);
7781 Value *NewConst = match(Const, m_ZeroInt())
7782 ? ConstantInt::get(ScalarTy, 0)
7783 : ConstantInt::getAllOnesValue(ScalarTy);
7784 return CmpInst::Create(Instruction::ICmp, I.getPredicate(),
7785 Builder.CreateBitCast(Vec, ScalarTy), NewConst);
7786 }
7787 return nullptr;
7788}
7789
7790/// This function folds patterns produced by lowering of reduce idioms, such as
7791/// llvm.vector.reduce.and which are lowered into instruction chains. This code
7792/// attempts to generate fewer number of scalar comparisons instead of vector
7793/// comparisons when possible.
7795 InstCombiner::BuilderTy &Builder,
7796 const DataLayout &DL) {
7797 if (I.getType()->isVectorTy())
7798 return nullptr;
7799 CmpPredicate OuterPred, InnerPred;
7800 Value *LHS, *RHS;
7801
7802 // Match lowering of @llvm.vector.reduce.and. Turn
7803 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7804 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7805 /// %res = icmp <pred> i8 %scalar_ne, 0
7806 ///
7807 /// into
7808 ///
7809 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7810 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7811 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7812 ///
7813 /// for <pred> in {ne, eq}.
7814 if (!match(&I, m_ICmp(OuterPred,
7816 m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
7817 m_Zero())))
7818 return nullptr;
7819 auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
7820 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7821 return nullptr;
7822 unsigned NumBits =
7823 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7824 // TODO: Relax this to "not wider than max legal integer type"?
7825 if (!DL.isLegalInteger(NumBits))
7826 return nullptr;
7827
7828 if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7829 auto *ScalarTy = Builder.getIntNTy(NumBits);
7830 LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
7831 RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
7832 return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
7833 I.getName());
7834 }
7835
7836 return nullptr;
7837}
7838
7839// This helper will be called with icmp operands in both orders.
7841 Value *Op0, Value *Op1,
7842 ICmpInst &CtxI) {
7843 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7844 if (auto *GEP = dyn_cast<GEPOperator>(Op0))
7845 if (Instruction *NI = foldGEPICmp(GEP, Op1, Pred, CtxI))
7846 return NI;
7847
7848 if (auto *SI = dyn_cast<SelectInst>(Op0))
7849 if (Instruction *NI = foldSelectICmp(Pred, SI, Op1, CtxI))
7850 return NI;
7851
7852 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op0)) {
7853 if (Instruction *Res = foldICmpWithMinMax(CtxI, MinMax, Op1, Pred))
7854 return Res;
7855
7856 if (Instruction *Res = foldICmpWithClamp(CtxI, Op1, MinMax))
7857 return Res;
7858 }
7859
7860 {
7861 Value *X;
7862 const APInt *C;
7863 // icmp X+Cst, X
7864 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
7865 return foldICmpAddOpConst(X, *C, Pred);
7866 }
7867
7868 // abs(X) >= X --> true
7869 // abs(X) u<= X --> true
7870 // abs(X) < X --> false
7871 // abs(X) u> X --> false
7872 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7873 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7874 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7875 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7876 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7877 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7878 {
7879 Value *X;
7880 Constant *C;
7882 match(Op1, m_Specific(X))) {
7883 Value *NullValue = Constant::getNullValue(X->getType());
7884 Value *AllOnesValue = Constant::getAllOnesValue(X->getType());
7885 const APInt SMin =
7886 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits());
7887 bool IsIntMinPosion = C->isAllOnesValue();
7888 switch (Pred) {
7889 case CmpInst::ICMP_ULE:
7890 case CmpInst::ICMP_SGE:
7891 return replaceInstUsesWith(CtxI, ConstantInt::getTrue(CtxI.getType()));
7892 case CmpInst::ICMP_UGT:
7893 case CmpInst::ICMP_SLT:
7895 case CmpInst::ICMP_UGE:
7896 case CmpInst::ICMP_SLE:
7897 case CmpInst::ICMP_EQ: {
7898 return replaceInstUsesWith(
7899 CtxI, IsIntMinPosion
7900 ? Builder.CreateICmpSGT(X, AllOnesValue)
7901 : Builder.CreateICmpULT(
7902 X, ConstantInt::get(X->getType(), SMin + 1)));
7903 }
7904 case CmpInst::ICMP_ULT:
7905 case CmpInst::ICMP_SGT:
7906 case CmpInst::ICMP_NE: {
7907 return replaceInstUsesWith(
7908 CtxI, IsIntMinPosion
7909 ? Builder.CreateICmpSLT(X, NullValue)
7910 : Builder.CreateICmpUGT(
7911 X, ConstantInt::get(X->getType(), SMin)));
7912 }
7913 default:
7914 llvm_unreachable("Invalid predicate!");
7915 }
7916 }
7917 }
7918
7919 {
7920 // For a nonzero constant C:
7921 // usub.sat(X, C) == X --> X == 0
7922 // usub.sat(X, C) != X --> X != 0
7923 // usub.sat(X, C) < X --> X != 0
7925 m_NonZeroInt())) &&
7926 (CmpInst::isEquality(Pred) || Pred == ICmpInst::ICMP_ULT)) {
7927 ICmpInst::Predicate NewPred =
7928 CmpInst::isEquality(Pred) ? Pred.dropSameSign() : ICmpInst::ICMP_NE;
7929 return new ICmpInst(NewPred, Op1, Constant::getNullValue(Op1->getType()));
7930 }
7931 }
7932
7933 const SimplifyQuery Q = SQ.getWithInstruction(&CtxI);
7934 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, *this))
7935 return replaceInstUsesWith(CtxI, V);
7936
7937 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
7938 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(1); };
7939 {
7940 if (match(Op0, m_UDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7941 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7943 }
7944
7945 if (!ICmpInst::isUnsigned(Pred) &&
7946 match(Op0, m_SDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7947 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7949 }
7950 }
7951
7952 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
7953 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
7954 {
7955 if (match(Op0, m_LShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7956 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7958 }
7959
7960 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
7961 match(Op0, m_AShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7962 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7964 }
7965 }
7966
7967 // icmp (shl nsw/nuw X, L), (add nsw/nuw (shl nsw/nuw Y, L), K)
7968 // -> icmp X, (add nsw/nuw Y, K >> L)
7969 // We use AShr for nsw and LShr for nuw to safely peel off the shift.
7970 Value *X;
7971 uint64_t ShAmt;
7972 if (match(Op0, m_NUWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
7973 !CtxI.isSigned()) {
7974 if (ShAmt >= X->getType()->getScalarSizeInBits())
7975 return nullptr;
7976 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
7977 ShiftSemantics::Unsigned, &CtxI)) {
7978 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
7980 return new ICmpInst(Pred, X, NewOp1);
7981 }
7982 }
7983
7984 if (match(Op0, m_NSWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
7985 !CtxI.isUnsigned()) {
7986 if (ShAmt >= X->getType()->getScalarSizeInBits())
7987 return nullptr;
7988 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
7989 ShiftSemantics::Signed, &CtxI)) {
7990 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
7992 return new ICmpInst(Pred, X, NewOp1);
7993 }
7994 }
7995 return nullptr;
7996}
7997
7999 bool Changed = false;
8000 const SimplifyQuery Q = SQ.getWithInstruction(&I);
8001 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8002 unsigned Op0Cplxity = getComplexity(Op0);
8003 unsigned Op1Cplxity = getComplexity(Op1);
8004
8005 /// Orders the operands of the compare so that they are listed from most
8006 /// complex to least complex. This puts constants before unary operators,
8007 /// before binary operators.
8008 if (Op0Cplxity < Op1Cplxity) {
8009 I.swapOperands();
8010 std::swap(Op0, Op1);
8011 Changed = true;
8012 }
8013
8014 if (Value *V = simplifyICmpInst(I.getCmpPredicate(), Op0, Op1, Q))
8015 return replaceInstUsesWith(I, V);
8016
8017 // Comparing -val or val with non-zero is the same as just comparing val
8018 // ie, abs(val) != 0 -> val != 0
8019 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
8020 Value *Cond, *SelectTrue, *SelectFalse;
8021 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
8022 m_Value(SelectFalse)))) {
8023 if (Value *V = dyn_castNegVal(SelectTrue)) {
8024 if (V == SelectFalse)
8025 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
8026 } else if (Value *V = dyn_castNegVal(SelectFalse)) {
8027 if (V == SelectTrue)
8028 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
8029 }
8030 }
8031 }
8032
8034 return Res;
8035
8036 if (Op0->getType()->isIntOrIntVectorTy(1))
8038 return Res;
8039
8041 return Res;
8042
8044 return Res;
8045
8047 return Res;
8048
8050 return Res;
8051
8053 return Res;
8054
8056 return Res;
8057
8059 return Res;
8060
8061 // Test if the ICmpInst instruction is used exclusively by a select as
8062 // part of a minimum or maximum operation. If so, refrain from doing
8063 // any other folding. This helps out other analyses which understand
8064 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
8065 // and CodeGen. And in this case, at least one of the comparison
8066 // operands has at least one user besides the compare (the select),
8067 // which would often largely negate the benefit of folding anyway.
8068 //
8069 // Do the same for the other patterns recognized by matchSelectPattern.
8070 if (I.hasOneUse())
8071 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
8072 Value *A, *B;
8074 if (SPR.Flavor != SPF_UNKNOWN)
8075 return nullptr;
8076 }
8077
8078 // Do this after checking for min/max to prevent infinite looping.
8079 if (Instruction *Res = foldICmpWithZero(I))
8080 return Res;
8081
8082 Value *X;
8083 const APInt *C;
8084 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
8085 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
8086 match(Op1, m_Not(m_Specific(X)))) {
8087 if (C->isNonNegative())
8088 return new ICmpInst(ICmpInst::ICMP_SLT, X,
8089 Constant::getNullValue(X->getType()));
8090 return new ICmpInst(ICmpInst::ICMP_UGT, X,
8091 ConstantInt::get(X->getType(), ~*C));
8092 }
8093
8094 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
8095 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
8096 match(Op1, m_Not(m_Specific(X)))) {
8097 if (C->isNonNegative())
8098 return new ICmpInst(ICmpInst::ICMP_SGT, X,
8099 Constant::getAllOnesValue(X->getType()));
8100 return new ICmpInst(ICmpInst::ICMP_ULT, X,
8101 ConstantInt::get(X->getType(), ~*C));
8102 }
8103
8104 // FIXME: We only do this after checking for min/max to prevent infinite
8105 // looping caused by a reverse canonicalization of these patterns for min/max.
8106 // FIXME: The organization of folds is a mess. These would naturally go into
8107 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
8108 // down here after the min/max restriction.
8109 ICmpInst::Predicate Pred = I.getPredicate();
8110 if (match(Op1, m_APInt(C))) {
8111 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
8112 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
8113 Constant *Zero = Constant::getNullValue(Op0->getType());
8114 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
8115 }
8116
8117 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
8118 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
8120 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
8121 }
8122 }
8123
8124 // The folds in here may rely on wrapping flags and special constants, so
8125 // they can break up min/max idioms in some cases but not seemingly similar
8126 // patterns.
8127 // FIXME: It may be possible to enhance select folding to make this
8128 // unnecessary. It may also be moot if we canonicalize to min/max
8129 // intrinsics.
8130 if (Instruction *Res = foldICmpBinOp(I, Q))
8131 return Res;
8132
8134 return Res;
8135
8136 // Try to match comparison as a sign bit test. Intentionally do this after
8137 // foldICmpInstWithConstant() to potentially let other folds to happen first.
8138 if (Instruction *New = foldSignBitTest(I))
8139 return New;
8140
8141 if (auto *PN = dyn_cast<PHINode>(Op0))
8142 if (Instruction *NV = foldOpIntoPhi(I, PN))
8143 return NV;
8144 if (auto *PN = dyn_cast<PHINode>(Op1))
8145 if (Instruction *NV = foldOpIntoPhi(I, PN))
8146 return NV;
8147
8149 return Res;
8150
8151 if (Instruction *Res = foldICmpCommutative(I.getCmpPredicate(), Op0, Op1, I))
8152 return Res;
8153 if (Instruction *Res =
8154 foldICmpCommutative(I.getSwappedCmpPredicate(), Op1, Op0, I))
8155 return Res;
8156
8157 if (I.isCommutative()) {
8158 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
8159 replaceOperand(I, 0, Pair->first);
8160 replaceOperand(I, 1, Pair->second);
8161 return &I;
8162 }
8163 }
8164
8165 // Fold icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8166 // when all select arms are constants, via truth table.
8168 return R;
8169
8170 // In case of a comparison with two select instructions having the same
8171 // condition, check whether one of the resulting branches can be simplified.
8172 // If so, just compare the other branch and select the appropriate result.
8173 // For example:
8174 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
8175 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
8176 // %cmp2 = icmp slt i32 %tmp2, %tmp1
8177 // The icmp will result false for the false value of selects and the result
8178 // will depend upon the comparison of true values of selects if %cmp is
8179 // true. Thus, transform this into:
8180 // %cmp = icmp slt i32 %y, %z
8181 // %sel = select i1 %cond, i1 %cmp, i1 false
8182 // This handles similar cases to transform.
8183 {
8184 Value *Cond, *A, *B, *C, *D;
8185 if (match(Op0, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
8187 (Op0->hasOneUse() || Op1->hasOneUse())) {
8188 // Check whether comparison of TrueValues can be simplified
8189 if (Value *Res = simplifyICmpInst(Pred, A, C, SQ)) {
8190 Value *NewICMP = Builder.CreateICmp(Pred, B, D);
8191 return SelectInst::Create(Cond, Res, NewICMP, /*NameStr=*/"",
8192 /*InsertBefore=*/nullptr,
8193 cast<Instruction>(Op0));
8194 }
8195 // Check whether comparison of FalseValues can be simplified
8196 if (Value *Res = simplifyICmpInst(Pred, B, D, SQ)) {
8197 Value *NewICMP = Builder.CreateICmp(Pred, A, C);
8198 return SelectInst::Create(Cond, NewICMP, Res, /*NameStr=*/"",
8199 /*InsertBefore=*/nullptr,
8200 cast<Instruction>(Op0));
8201 }
8202 }
8203 }
8204
8205 // icmp slt (sub nsw x, y), (add nsw x, y) --> icmp sgt y, 0
8206 // icmp ult (sub nuw x, y), (add nuw x, y) --> icmp ugt y, 0
8207 // icmp eq (sub nsw/nuw x, y), (add nsw/nuw x, y) --> icmp eq y, 0
8208 {
8209 Value *A, *B;
8210 CmpPredicate CmpPred;
8211 if (match(&I, m_c_ICmp(CmpPred, m_Sub(m_Value(A), m_Value(B)),
8213 auto *I0 = cast<OverflowingBinaryOperator>(Op0);
8214 auto *I1 = cast<OverflowingBinaryOperator>(Op1);
8215 bool I0NUW = I0->hasNoUnsignedWrap();
8216 bool I1NUW = I1->hasNoUnsignedWrap();
8217 bool I0NSW = I0->hasNoSignedWrap();
8218 bool I1NSW = I1->hasNoSignedWrap();
8219 if ((ICmpInst::isUnsigned(Pred) && I0NUW && I1NUW) ||
8220 (ICmpInst::isSigned(Pred) && I0NSW && I1NSW) ||
8221 (ICmpInst::isEquality(Pred) &&
8222 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
8223 return new ICmpInst(CmpPredicate::getSwapped(CmpPred), B,
8224 ConstantInt::get(Op0->getType(), 0));
8225 }
8226 }
8227 }
8228
8229 // Try to optimize equality comparisons against alloca-based pointers.
8230 if (Op0->getType()->isPointerTy() && I.isEquality()) {
8231 assert(Op1->getType()->isPointerTy() &&
8232 "Comparing pointer with non-pointer?");
8233 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
8234 if (foldAllocaCmp(Alloca))
8235 return nullptr;
8236 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
8237 if (foldAllocaCmp(Alloca))
8238 return nullptr;
8239 }
8240
8241 if (Instruction *Res = foldICmpBitCast(I))
8242 return Res;
8243
8244 // TODO: Hoist this above the min/max bailout.
8246 return R;
8247
8248 // icmp (zext X), (and (trunc Y), Mask) -> icmp X, trunc Y IFF Mask exactly
8249 // covers the bits of X
8250 {
8251 Value *Y;
8252 const APInt *Mask;
8253 if (match(I.getOperand(1), m_ZExt(m_Value(X))) &&
8254 match(I.getOperand(0),
8255 m_OneUse(m_And(m_Trunc(m_Value(Y)), m_APInt(Mask))))) {
8256 Type *SmallType = X->getType();
8257 unsigned SmallWidth = SmallType->getScalarSizeInBits();
8258 if (Mask->isMask(SmallWidth) &&
8259 shouldChangeType(I.getOperand(0)->getType(), SmallType)) {
8260 Value *NewTrunc = Builder.CreateTrunc(Y, SmallType);
8261 return new ICmpInst(I.getUnsignedPredicate(), NewTrunc, X);
8262 }
8263 }
8264 }
8265
8266 {
8267 Value *X, *Y;
8268 // Transform (X & ~Y) == 0 --> (X & Y) != 0
8269 // and (X & ~Y) != 0 --> (X & Y) == 0
8270 // if A is a power of 2.
8271 if (match(Op0, m_And(m_Value(X), m_Not(m_Value(Y)))) &&
8272 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(X, false, &I) &&
8273 I.isEquality())
8274 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(X, Y),
8275 Op1);
8276
8277 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
8278 if (Op0->getType()->isIntOrIntVectorTy()) {
8279 bool ConsumesOp0, ConsumesOp1;
8280 if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
8281 isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
8282 (ConsumesOp0 || ConsumesOp1)) {
8283 Value *InvOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
8284 Value *InvOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
8285 assert(InvOp0 && InvOp1 &&
8286 "Mismatch between isFreeToInvert and getFreelyInverted");
8287 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
8288 }
8289 }
8290
8291 Instruction *AddI = nullptr;
8293 m_Instruction(AddI))) &&
8294 isa<IntegerType>(X->getType())) {
8295 Value *Result;
8296 Constant *Overflow;
8297 // m_UAddWithOverflow can match patterns that do not include an explicit
8298 // "add" instruction, so check the opcode of the matched op.
8299 if (AddI->getOpcode() == Instruction::Add &&
8300 OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, X, Y, *AddI,
8301 Result, Overflow)) {
8302 replaceInstUsesWith(*AddI, Result);
8303 eraseInstFromFunction(*AddI);
8304 return replaceInstUsesWith(I, Overflow);
8305 }
8306 }
8307
8308 // (zext X) + (zext Y) --> add + overflow check.
8309 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
8310 if ((match(Op0, m_NUWAdd(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) ||
8311 match(Op0, m_NUWMul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y))))) &&
8312 match(Op1, m_APInt(C))) {
8313 if (Instruction *R = processUZExtIdiom(I, Op0, C, *this))
8314 return R;
8315 }
8316
8317 // Signbit test folds
8318 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
8319 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
8320 Instruction *ExtI;
8321 if ((I.isUnsigned() || I.isEquality()) &&
8322 match(Op1,
8324 Y->getType()->getScalarSizeInBits() == 1 &&
8325 (Op0->hasOneUse() || Op1->hasOneUse())) {
8326 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
8327 Instruction *ShiftI;
8328 if (match(Op0, m_CombineAnd(m_Instruction(ShiftI),
8330 OpWidth - 1))))) {
8331 unsigned ExtOpc = ExtI->getOpcode();
8332 unsigned ShiftOpc = ShiftI->getOpcode();
8333 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
8334 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
8335 Value *SLTZero =
8336 Builder.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
8337 Value *Cmp = Builder.CreateICmp(Pred, SLTZero, Y, I.getName());
8338 return replaceInstUsesWith(I, Cmp);
8339 }
8340 }
8341 }
8342 }
8343
8344 if (Instruction *Res = foldICmpEquality(I))
8345 return Res;
8346
8348 return Res;
8349
8350 if (Instruction *Res = foldICmpOfUAddOv(I))
8351 return Res;
8352
8354 return Res;
8355
8356 // The 'cmpxchg' instruction returns an aggregate containing the old value and
8357 // an i1 which indicates whether or not we successfully did the swap.
8358 //
8359 // Replace comparisons between the old value and the expected value with the
8360 // indicator that 'cmpxchg' returns.
8361 //
8362 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
8363 // spuriously fail. In those cases, the old value may equal the expected
8364 // value but it is possible for the swap to not occur.
8365 if (I.getPredicate() == ICmpInst::ICMP_EQ)
8366 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
8367 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
8368 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
8369 !ACXI->isWeak())
8370 return ExtractValueInst::Create(ACXI, 1);
8371
8373 return Res;
8374
8375 if (I.getType()->isVectorTy())
8376 if (Instruction *Res = foldVectorCmp(I, Builder))
8377 return Res;
8378
8380 return Res;
8381
8383 return Res;
8384
8385 {
8386 Value *A;
8387 const APInt *C1, *C2;
8388 ICmpInst::Predicate Pred = I.getPredicate();
8389 if (ICmpInst::isEquality(Pred)) {
8390 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
8391 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
8392 if (match(Op0, m_And(m_SExt(m_Value(A)), m_APInt(C1))) &&
8393 match(Op1, m_APInt(C2))) {
8394 Type *InputTy = A->getType();
8395 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
8396 // c2 must be non-negative at the bitwidth of a.
8397 if (C2->getActiveBits() < InputBitWidth) {
8398 APInt TruncC1 = C1->trunc(InputBitWidth);
8399 // Check if there are 1s in C1 high bits of size InputBitWidth.
8400 if (C1->uge(APInt::getOneBitSet(C1->getBitWidth(), InputBitWidth)))
8401 TruncC1.setBit(InputBitWidth - 1);
8402 Value *AndInst = Builder.CreateAnd(A, TruncC1);
8403 return new ICmpInst(
8404 Pred, AndInst,
8405 ConstantInt::get(InputTy, C2->trunc(InputBitWidth)));
8406 }
8407 }
8408 }
8409 }
8410
8411 return Changed ? &I : nullptr;
8412}
8413
8414/// Fold fcmp ([us]itofp x, cst) if possible.
8416 Instruction *LHSI,
8417 Constant *RHSC) {
8418 const APFloat *RHS;
8419 if (!match(RHSC, m_APFloat(RHS)))
8420 return nullptr;
8421
8422 // Get the width of the mantissa. We don't want to hack on conversions that
8423 // might lose information from the integer, e.g. "i64 -> float"
8424 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8425 if (MantissaWidth == -1)
8426 return nullptr; // Unknown.
8427
8428 Type *IntTy = LHSI->getOperand(0)->getType();
8429 unsigned IntWidth = IntTy->getScalarSizeInBits();
8430 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
8431
8432 if (I.isEquality()) {
8433 FCmpInst::Predicate P = I.getPredicate();
8434 bool IsExact = false;
8435 APSInt RHSCvt(IntWidth, LHSUnsigned);
8436 RHS->convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
8437
8438 // If the floating point constant isn't an integer value, we know if we will
8439 // ever compare equal / not equal to it.
8440 if (!IsExact) {
8441 // TODO: Can never be -0.0 and other non-representable values
8442 APFloat RHSRoundInt(*RHS);
8444 if (*RHS != RHSRoundInt) {
8446 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8447
8449 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8450 }
8451 }
8452
8453 // TODO: If the constant is exactly representable, is it always OK to do
8454 // equality compares as integer?
8455 }
8456
8457 // Check to see that the input is converted from an integer type that is small
8458 // enough that preserves all bits. TODO: check here for "known" sign bits.
8459 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
8460
8461 // Following test does NOT adjust IntWidth downwards for signed inputs,
8462 // because the most negative value still requires all the mantissa bits
8463 // to distinguish it from one less than that value.
8464 if ((int)IntWidth > MantissaWidth) {
8465 // Conversion would lose accuracy. Check if loss can impact comparison.
8466 int Exp = ilogb(*RHS);
8467 if (Exp == APFloat::IEK_Inf) {
8468 int MaxExponent = ilogb(APFloat::getLargest(RHS->getSemantics()));
8469 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
8470 // Conversion could create infinity.
8471 return nullptr;
8472 } else {
8473 // Note that if RHS is zero or NaN, then Exp is negative
8474 // and first condition is trivially false.
8475 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
8476 // Conversion could affect comparison.
8477 return nullptr;
8478 }
8479 }
8480
8481 // Otherwise, we can potentially simplify the comparison. We know that it
8482 // will always come through as an integer value and we know the constant is
8483 // not a NAN (it would have been previously simplified).
8484 assert(!RHS->isNaN() && "NaN comparison not already folded!");
8485
8487 switch (I.getPredicate()) {
8488 default:
8489 llvm_unreachable("Unexpected predicate!");
8490 case FCmpInst::FCMP_UEQ:
8491 case FCmpInst::FCMP_OEQ:
8492 Pred = ICmpInst::ICMP_EQ;
8493 break;
8494 case FCmpInst::FCMP_UGT:
8495 case FCmpInst::FCMP_OGT:
8496 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
8497 break;
8498 case FCmpInst::FCMP_UGE:
8499 case FCmpInst::FCMP_OGE:
8500 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
8501 break;
8502 case FCmpInst::FCMP_ULT:
8503 case FCmpInst::FCMP_OLT:
8504 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
8505 break;
8506 case FCmpInst::FCMP_ULE:
8507 case FCmpInst::FCMP_OLE:
8508 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
8509 break;
8510 case FCmpInst::FCMP_UNE:
8511 case FCmpInst::FCMP_ONE:
8512 Pred = ICmpInst::ICMP_NE;
8513 break;
8514 case FCmpInst::FCMP_ORD:
8515 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8516 case FCmpInst::FCMP_UNO:
8517 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8518 }
8519
8520 // Now we know that the APFloat is a normal number, zero or inf.
8521
8522 // See if the FP constant is too large for the integer. For example,
8523 // comparing an i8 to 300.0.
8524 if (!LHSUnsigned) {
8525 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
8526 // and large values.
8527 APFloat SMax(RHS->getSemantics());
8528 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
8530 if (SMax < *RHS) { // smax < 13123.0
8531 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
8532 Pred == ICmpInst::ICMP_SLE)
8533 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8534 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8535 }
8536 } else {
8537 // If the RHS value is > UnsignedMax, fold the comparison. This handles
8538 // +INF and large values.
8539 APFloat UMax(RHS->getSemantics());
8540 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
8542 if (UMax < *RHS) { // umax < 13123.0
8543 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
8544 Pred == ICmpInst::ICMP_ULE)
8545 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8546 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8547 }
8548 }
8549
8550 if (!LHSUnsigned) {
8551 // See if the RHS value is < SignedMin.
8552 APFloat SMin(RHS->getSemantics());
8553 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
8555 if (SMin > *RHS) { // smin > 12312.0
8556 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
8557 Pred == ICmpInst::ICMP_SGE)
8558 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8559 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8560 }
8561 } else {
8562 // See if the RHS value is < UnsignedMin.
8563 APFloat UMin(RHS->getSemantics());
8564 UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
8566 if (UMin > *RHS) { // umin > 12312.0
8567 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
8568 Pred == ICmpInst::ICMP_UGE)
8569 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8570 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8571 }
8572 }
8573
8574 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
8575 // [0, UMAX], but it may still be fractional. Check whether this is the case
8576 // using the IsExact flag.
8577 // Don't do this for zero, because -0.0 is not fractional.
8578 APSInt RHSInt(IntWidth, LHSUnsigned);
8579 bool IsExact;
8580 RHS->convertToInteger(RHSInt, APFloat::rmTowardZero, &IsExact);
8581 if (!RHS->isZero()) {
8582 if (!IsExact) {
8583 // If we had a comparison against a fractional value, we have to adjust
8584 // the compare predicate and sometimes the value. RHSC is rounded towards
8585 // zero at this point.
8586 switch (Pred) {
8587 default:
8588 llvm_unreachable("Unexpected integer comparison!");
8589 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
8590 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8591 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
8592 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8593 case ICmpInst::ICMP_ULE:
8594 // (float)int <= 4.4 --> int <= 4
8595 // (float)int <= -4.4 --> false
8596 if (RHS->isNegative())
8597 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8598 break;
8599 case ICmpInst::ICMP_SLE:
8600 // (float)int <= 4.4 --> int <= 4
8601 // (float)int <= -4.4 --> int < -4
8602 if (RHS->isNegative())
8603 Pred = ICmpInst::ICMP_SLT;
8604 break;
8605 case ICmpInst::ICMP_ULT:
8606 // (float)int < -4.4 --> false
8607 // (float)int < 4.4 --> int <= 4
8608 if (RHS->isNegative())
8609 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8610 Pred = ICmpInst::ICMP_ULE;
8611 break;
8612 case ICmpInst::ICMP_SLT:
8613 // (float)int < -4.4 --> int < -4
8614 // (float)int < 4.4 --> int <= 4
8615 if (!RHS->isNegative())
8616 Pred = ICmpInst::ICMP_SLE;
8617 break;
8618 case ICmpInst::ICMP_UGT:
8619 // (float)int > 4.4 --> int > 4
8620 // (float)int > -4.4 --> true
8621 if (RHS->isNegative())
8622 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8623 break;
8624 case ICmpInst::ICMP_SGT:
8625 // (float)int > 4.4 --> int > 4
8626 // (float)int > -4.4 --> int >= -4
8627 if (RHS->isNegative())
8628 Pred = ICmpInst::ICMP_SGE;
8629 break;
8630 case ICmpInst::ICMP_UGE:
8631 // (float)int >= -4.4 --> true
8632 // (float)int >= 4.4 --> int > 4
8633 if (RHS->isNegative())
8634 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8635 Pred = ICmpInst::ICMP_UGT;
8636 break;
8637 case ICmpInst::ICMP_SGE:
8638 // (float)int >= -4.4 --> int >= -4
8639 // (float)int >= 4.4 --> int > 4
8640 if (!RHS->isNegative())
8641 Pred = ICmpInst::ICMP_SGT;
8642 break;
8643 }
8644 }
8645 }
8646
8647 // Lower this FP comparison into an appropriate integer version of the
8648 // comparison.
8649 return new ICmpInst(Pred, LHSI->getOperand(0),
8650 ConstantInt::get(LHSI->getOperand(0)->getType(), RHSInt));
8651}
8652
8653/// Fold fcmp/icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8654/// where all true/false values are constants that allow the compare to be
8655/// constant-folded for every combination of C1 and C2.
8656/// We compute a 4-entry truth table and use createLogicFromTable to
8657/// synthesize a boolean expression of C1 and C2.
8659 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8660 Value *C1, *C2;
8661 Constant *TV1, *FV1, *TV2, *FV2;
8662
8663 if (!match(Op0, m_Select(m_Value(C1), m_Constant(TV1), m_Constant(FV1))) ||
8664 !match(Op1, m_Select(m_Value(C2), m_Constant(TV2), m_Constant(FV2))))
8665 return nullptr;
8666
8667 if (I.getType() != C1->getType() || I.getType() != C2->getType())
8668 return nullptr;
8669
8670 unsigned Pred = I.getPredicate();
8671 const DataLayout &DL = I.getDataLayout();
8672
8673 Constant *Res00 = ConstantFoldCompareInstOperands(Pred, FV1, FV2, DL);
8674 Constant *Res01 = ConstantFoldCompareInstOperands(Pred, FV1, TV2, DL);
8675 Constant *Res10 = ConstantFoldCompareInstOperands(Pred, TV1, FV2, DL);
8676 Constant *Res11 = ConstantFoldCompareInstOperands(Pred, TV1, TV2, DL);
8677
8678 if (!Res00 || !Res01 || !Res10 || !Res11)
8679 return nullptr;
8680
8681 if ((!Res00->isNullValue() && !Res00->isAllOnesValue()) ||
8682 (!Res01->isNullValue() && !Res01->isAllOnesValue()) ||
8683 (!Res10->isNullValue() && !Res10->isAllOnesValue()) ||
8684 (!Res11->isNullValue() && !Res11->isAllOnesValue()))
8685 return nullptr;
8686
8687 std::bitset<4> Table;
8688 if (!Res00->isNullValue())
8689 Table.set(0);
8690 if (!Res01->isNullValue())
8691 Table.set(1);
8692 if (!Res10->isNullValue())
8693 Table.set(2);
8694 if (!Res11->isNullValue())
8695 Table.set(3);
8696
8697 Value *Res = createLogicFromTable(Table, C1, C2, Builder,
8698 Op0->hasOneUse() && Op1->hasOneUse());
8699 if (!Res)
8700 return nullptr;
8701 return replaceInstUsesWith(I, Res);
8702}
8703
8704/// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
8706 Constant *RHSC) {
8707 // When C is not 0.0 and infinities are not allowed:
8708 // (C / X) < 0.0 is a sign-bit test of X
8709 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
8710 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
8711 //
8712 // Proof:
8713 // Multiply (C / X) < 0.0 by X * X / C.
8714 // - X is non zero, if it is the flag 'ninf' is violated.
8715 // - C defines the sign of X * X * C. Thus it also defines whether to swap
8716 // the predicate. C is also non zero by definition.
8717 //
8718 // Thus X * X / C is non zero and the transformation is valid. [qed]
8719
8720 FCmpInst::Predicate Pred = I.getPredicate();
8721
8722 // Check that predicates are valid.
8723 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
8724 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
8725 return nullptr;
8726
8727 // Check that RHS operand is zero.
8728 if (!match(RHSC, m_AnyZeroFP()))
8729 return nullptr;
8730
8731 // Check fastmath flags ('ninf').
8732 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
8733 return nullptr;
8734
8735 // Check the properties of the dividend. It must not be zero to avoid a
8736 // division by zero (see Proof).
8737 const APFloat *C;
8738 if (!match(LHSI->getOperand(0), m_APFloat(C)))
8739 return nullptr;
8740
8741 if (C->isZero())
8742 return nullptr;
8743
8744 // Get swapped predicate if necessary.
8745 if (C->isNegative())
8746 Pred = I.getSwappedPredicate();
8747
8748 return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
8749}
8750
8751// Transform 'fptrunc(x) cmp C' to 'x cmp ext(C)' if possible.
8752// Patterns include:
8753// fptrunc(x) < C --> x < ext(C)
8754// fptrunc(x) <= C --> x <= ext(C)
8755// fptrunc(x) > C --> x > ext(C)
8756// fptrunc(x) >= C --> x >= ext(C)
8757// fptrunc(x) ord/uno C --> x ord/uno 0
8758// where 'ext(C)' is the extension of 'C' to the type of 'x' with a small bias
8759// due to precision loss.
8761 const Constant &C) {
8762 FCmpInst::Predicate Pred = I.getPredicate();
8763 Type *DestType = FPTrunc.getOperand(0)->getType();
8764
8765 const APFloat *CValue;
8766 // TODO: support vec
8767 if (!match(&C, m_APFloat(CValue)))
8768 return nullptr;
8769
8770 // Handle ord/uno
8771 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) {
8772 assert(!CValue->isNaN() &&
8773 "X ord/uno NaN should be folded away by simplifyFCmpInst()");
8774 return new FCmpInst(Pred, FPTrunc.getOperand(0),
8775 ConstantFP::getZero(DestType), "", &I);
8776 }
8777
8778 // Handle <, >, <=, >=
8779 bool RoundDown = false;
8780
8781 if (Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE ||
8782 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT)
8783 RoundDown = true;
8784 else if (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT ||
8785 Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)
8786 RoundDown = false;
8787 else
8788 return nullptr;
8789
8790 if (CValue->isNaN() || CValue->isInfinity())
8791 return nullptr;
8792
8793 auto ConvertFltSema = [](const APFloat &Src, const fltSemantics &Sema) {
8794 bool LosesInfo;
8795 APFloat Dest = Src;
8796 Dest.convert(Sema, APFloat::rmNearestTiesToEven, &LosesInfo);
8797 return Dest;
8798 };
8799
8800 auto NextValue = [](const APFloat &Value, bool RoundDown) {
8801 APFloat NextValue = Value;
8802 NextValue.next(RoundDown);
8803 return NextValue;
8804 };
8805
8806 APFloat NextCValue = NextValue(*CValue, RoundDown);
8807
8808 const fltSemantics &DestFltSema =
8809 DestType->getScalarType()->getFltSemantics();
8810
8811 APFloat ExtCValue = ConvertFltSema(*CValue, DestFltSema);
8812 APFloat ExtNextCValue = ConvertFltSema(NextCValue, DestFltSema);
8813
8814 // When 'NextCValue' is infinity, use an imaged 'NextCValue' that equals
8815 // 'CValue + bias' to avoid the infinity after conversion. The bias is
8816 // estimated as 'CValue - PrevCValue', where 'PrevCValue' is the previous
8817 // value of 'CValue'.
8818 if (NextCValue.isInfinity()) {
8819 APFloat PrevCValue = NextValue(*CValue, !RoundDown);
8820 APFloat Bias = ConvertFltSema(*CValue - PrevCValue, DestFltSema);
8821
8822 ExtNextCValue = ExtCValue + Bias;
8823 }
8824
8825 APFloat ExtMidValue =
8826 scalbn(ExtCValue + ExtNextCValue, -1, APFloat::rmNearestTiesToEven);
8827
8828 const fltSemantics &SrcFltSema =
8829 C.getType()->getScalarType()->getFltSemantics();
8830
8831 // 'MidValue' might be rounded to 'NextCValue'. Correct it here.
8832 APFloat MidValue = ConvertFltSema(ExtMidValue, SrcFltSema);
8833 if (MidValue != *CValue)
8834 ExtMidValue.next(!RoundDown);
8835
8836 // Check whether 'ExtMidValue' is a valid result since the assumption on
8837 // imaged 'NextCValue' might not hold for new float types.
8838 // ppc_fp128 can't pass here when converting from max float because of
8839 // APFloat implementation.
8840 if (NextCValue.isInfinity()) {
8841 // ExtMidValue --- narrowed ---> Finite
8842 if (ConvertFltSema(ExtMidValue, SrcFltSema).isInfinity())
8843 return nullptr;
8844
8845 // NextExtMidValue --- narrowed ---> Infinity
8846 APFloat NextExtMidValue = NextValue(ExtMidValue, RoundDown);
8847 if (ConvertFltSema(NextExtMidValue, SrcFltSema).isFinite())
8848 return nullptr;
8849 }
8850
8851 return new FCmpInst(Pred, FPTrunc.getOperand(0),
8852 ConstantFP::get(DestType, ExtMidValue), "", &I);
8853}
8854
8855/// Optimize fabs(X) compared with zero.
8857 Value *X;
8858 if (!match(I.getOperand(0), m_FAbs(m_Value(X))))
8859 return nullptr;
8860
8861 const APFloat *C;
8862 if (!match(I.getOperand(1), m_APFloat(C)))
8863 return nullptr;
8864
8865 if (!C->isPosZero()) {
8866 if (!C->isSmallestNormalized())
8867 return nullptr;
8868
8869 const Function *F = I.getFunction();
8870 DenormalMode Mode = F->getDenormalMode(C->getSemantics());
8871 if (Mode.Input == DenormalMode::PreserveSign ||
8873
8874 auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8875 Constant *Zero = ConstantFP::getZero(X->getType());
8876 return new FCmpInst(P, X, Zero, "", I);
8877 };
8878
8879 switch (I.getPredicate()) {
8880 case FCmpInst::FCMP_OLT:
8881 // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
8882 return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
8883 case FCmpInst::FCMP_UGE:
8884 // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
8885 return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
8886 case FCmpInst::FCMP_OGE:
8887 // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
8888 return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
8889 case FCmpInst::FCMP_ULT:
8890 // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
8891 return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
8892 default:
8893 break;
8894 }
8895 }
8896
8897 return nullptr;
8898 }
8899
8900 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8901 I->setPredicate(P);
8902 return IC.replaceOperand(*I, 0, X);
8903 };
8904
8905 switch (I.getPredicate()) {
8906 case FCmpInst::FCMP_UGE:
8907 case FCmpInst::FCMP_OLT:
8908 // fabs(X) >= 0.0 --> true
8909 // fabs(X) < 0.0 --> false
8910 llvm_unreachable("fcmp should have simplified");
8911
8912 case FCmpInst::FCMP_OGT:
8913 // fabs(X) > 0.0 --> X != 0.0
8914 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
8915
8916 case FCmpInst::FCMP_UGT:
8917 // fabs(X) u> 0.0 --> X u!= 0.0
8918 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
8919
8920 case FCmpInst::FCMP_OLE:
8921 // fabs(X) <= 0.0 --> X == 0.0
8922 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
8923
8924 case FCmpInst::FCMP_ULE:
8925 // fabs(X) u<= 0.0 --> X u== 0.0
8926 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
8927
8928 case FCmpInst::FCMP_OGE:
8929 // fabs(X) >= 0.0 --> !isnan(X)
8930 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8931 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
8932
8933 case FCmpInst::FCMP_ULT:
8934 // fabs(X) u< 0.0 --> isnan(X)
8935 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8936 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
8937
8938 case FCmpInst::FCMP_OEQ:
8939 case FCmpInst::FCMP_UEQ:
8940 case FCmpInst::FCMP_ONE:
8941 case FCmpInst::FCMP_UNE:
8942 case FCmpInst::FCMP_ORD:
8943 case FCmpInst::FCMP_UNO:
8944 // Look through the fabs() because it doesn't change anything but the sign.
8945 // fabs(X) == 0.0 --> X == 0.0,
8946 // fabs(X) != 0.0 --> X != 0.0
8947 // isnan(fabs(X)) --> isnan(X)
8948 // !isnan(fabs(X) --> !isnan(X)
8949 return replacePredAndOp0(&I, I.getPredicate(), X);
8950
8951 default:
8952 return nullptr;
8953 }
8954}
8955
8956/// Optimize sqrt(X) compared with zero.
8958 Value *X;
8959 if (!match(I.getOperand(0), m_Sqrt(m_Value(X))))
8960 return nullptr;
8961
8962 if (!match(I.getOperand(1), m_PosZeroFP()))
8963 return nullptr;
8964
8965 auto ReplacePredAndOp0 = [&](FCmpInst::Predicate P) {
8966 I.setPredicate(P);
8967 return IC.replaceOperand(I, 0, X);
8968 };
8969
8970 // Clear ninf flag if sqrt doesn't have it.
8971 if (!cast<Instruction>(I.getOperand(0))->hasNoInfs())
8972 I.setHasNoInfs(false);
8973
8974 switch (I.getPredicate()) {
8975 case FCmpInst::FCMP_OLT:
8976 case FCmpInst::FCMP_UGE:
8977 // sqrt(X) < 0.0 --> false
8978 // sqrt(X) u>= 0.0 --> true
8979 llvm_unreachable("fcmp should have simplified");
8980 case FCmpInst::FCMP_ULT:
8981 case FCmpInst::FCMP_ULE:
8982 case FCmpInst::FCMP_OGT:
8983 case FCmpInst::FCMP_OGE:
8984 case FCmpInst::FCMP_OEQ:
8985 case FCmpInst::FCMP_UNE:
8986 // sqrt(X) u< 0.0 --> X u< 0.0
8987 // sqrt(X) u<= 0.0 --> X u<= 0.0
8988 // sqrt(X) > 0.0 --> X > 0.0
8989 // sqrt(X) >= 0.0 --> X >= 0.0
8990 // sqrt(X) == 0.0 --> X == 0.0
8991 // sqrt(X) u!= 0.0 --> X u!= 0.0
8992 return IC.replaceOperand(I, 0, X);
8993
8994 case FCmpInst::FCMP_OLE:
8995 // sqrt(X) <= 0.0 --> X == 0.0
8996 return ReplacePredAndOp0(FCmpInst::FCMP_OEQ);
8997 case FCmpInst::FCMP_UGT:
8998 // sqrt(X) u> 0.0 --> X u!= 0.0
8999 return ReplacePredAndOp0(FCmpInst::FCMP_UNE);
9000 case FCmpInst::FCMP_UEQ:
9001 // sqrt(X) u== 0.0 --> X u<= 0.0
9002 return ReplacePredAndOp0(FCmpInst::FCMP_ULE);
9003 case FCmpInst::FCMP_ONE:
9004 // sqrt(X) != 0.0 --> X > 0.0
9005 return ReplacePredAndOp0(FCmpInst::FCMP_OGT);
9006 case FCmpInst::FCMP_ORD:
9007 // !isnan(sqrt(X)) --> X >= 0.0
9008 return ReplacePredAndOp0(FCmpInst::FCMP_OGE);
9009 case FCmpInst::FCMP_UNO:
9010 // isnan(sqrt(X)) --> X u< 0.0
9011 return ReplacePredAndOp0(FCmpInst::FCMP_ULT);
9012 default:
9013 llvm_unreachable("Unexpected predicate!");
9014 }
9015}
9016
9018 CmpInst::Predicate Pred = I.getPredicate();
9019 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
9020
9021 // Canonicalize fneg as Op1.
9022 if (match(Op0, m_FNeg(m_Value())) && !match(Op1, m_FNeg(m_Value()))) {
9023 std::swap(Op0, Op1);
9024 Pred = I.getSwappedPredicate();
9025 }
9026
9027 if (!match(Op1, m_FNeg(m_Specific(Op0))))
9028 return nullptr;
9029
9030 // Replace the negated operand with 0.0:
9031 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
9032 Constant *Zero = ConstantFP::getZero(Op0->getType());
9033 return new FCmpInst(Pred, Op0, Zero, "", &I);
9034}
9035
9037 Constant *RHSC, InstCombinerImpl &CI) {
9038 const CmpInst::Predicate Pred = I.getPredicate();
9039 Value *X = LHSI->getOperand(0);
9040 Value *Y = LHSI->getOperand(1);
9041 switch (Pred) {
9042 default:
9043 break;
9044 case FCmpInst::FCMP_UGT:
9045 case FCmpInst::FCMP_ULT:
9046 case FCmpInst::FCMP_UNE:
9047 case FCmpInst::FCMP_OEQ:
9048 case FCmpInst::FCMP_OGE:
9049 case FCmpInst::FCMP_OLE:
9050 // The optimization is not valid if X and Y are infinities of the same
9051 // sign, i.e. the inf - inf = nan case. If the fsub has the ninf or nnan
9052 // flag then we can assume we do not have that case. Otherwise we might be
9053 // able to prove that either X or Y is not infinity.
9054 if (!LHSI->hasNoNaNs() && !LHSI->hasNoInfs() &&
9058 break;
9059
9060 [[fallthrough]];
9061 case FCmpInst::FCMP_OGT:
9062 case FCmpInst::FCMP_OLT:
9063 case FCmpInst::FCMP_ONE:
9064 case FCmpInst::FCMP_UEQ:
9065 case FCmpInst::FCMP_UGE:
9066 case FCmpInst::FCMP_ULE:
9067 // fcmp pred (x - y), 0 --> fcmp pred x, y
9068 if (match(RHSC, m_AnyZeroFP()) &&
9069 I.getFunction()->getDenormalMode(
9070 LHSI->getType()->getScalarType()->getFltSemantics()) ==
9072 CI.replaceOperand(I, 0, X);
9073 CI.replaceOperand(I, 1, Y);
9074 I.setHasNoInfs(LHSI->hasNoInfs());
9075 if (LHSI->hasNoNaNs())
9076 I.setHasNoNaNs(true);
9077 return &I;
9078 }
9079 // fcmp `pred (C - Y), C` -> `fcmp swap(pred), Y, 0`
9080 // where C and Y can't be arbitrary floating-point values.
9081 // For example, with `C = 1.0f` and `Y = 0x1p-149`, `1.0f - Y` rounds back
9082 // to `1.0f`, so the source compare is false while the rewritten compare is
9083 // true.
9084 // We need to make sure (C - Y) never rounds back to C
9085 const APFloat *C;
9086 Value *IntSrc;
9087 if (match(RHSC, m_APFloat(C)) &&
9088 match(LHSI, m_FSub(m_Specific(RHSC), m_IToFP(m_Value(IntSrc)))) &&
9089 C->isNormal()) {
9090 // Requirements on C and Y:
9091 // 1. C is finite, nonzero, normal.
9092 // 2. C shouldn't be too large, that is, ULP(C) <= 1.
9093 // 3. Y must be the form of `[su]itofp`, so the finite nonzero result of Y
9094 // must be integer-valued with an absolute value of at least 1;
9095 // as long as the step size near C does not exceed 1,
9096 // C - Y cannot be rounded back to C when Y != 0.
9097 // 4. If Y = 0, `fcmp pred (C - 0), C` are equivalent to `fcmp swap(pred)
9098 // 0, 0` for ordered and unordered predicates as long as C is finite and
9099 // nonzero.
9100 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
9101 if (MantissaWidth != -1 && ilogb(*C) < MantissaWidth) {
9102 Constant *ZeroC = ConstantFP::getZero(LHSI->getType());
9103 I.setPredicate(I.getSwappedPredicate());
9104 CI.replaceOperand(I, 0, Y);
9105 CI.replaceOperand(I, 1, ZeroC);
9106 return &I;
9107 }
9108 }
9109 break;
9110 }
9111
9112 return nullptr;
9113}
9114
9115/// Fold: fabs(uitofp(a) - uitofp(b)) pred C --> a == b
9116/// where 'pred' is olt, ult, ogt, ugt, oge or uge and C is a positive, Non-NaN
9117/// float when the uitofp casts are exact and C is in the valid range.
9118///
9119/// Since exact uitofp means distinct integers map to distinct floats, the only
9120/// values fabs(uitofp(a) - uitofp(b)) can take are {0.0, 1.0, 2.0, ...}.
9121/// There are no values in the open interval (0, 1), so:
9122/// fabs(...) < C where 0 < C <= 1.0 --> a == b (strict lt: C=1.0 ok)
9123// fabs(..) >= C where C >= 1.0 -> a != b
9124///
9125/// The same logic applies to sitofp.
9127 Value *FAbsArg;
9128 if (!match(I.getOperand(0), m_FAbs(m_Value(FAbsArg))))
9129 return nullptr;
9130
9131 const APFloat *C;
9132 if (!match(I.getOperand(1), PatternMatch::m_FiniteNonZero(C)))
9133 return nullptr;
9134
9135 FCmpInst::Predicate Pred = I.getPredicate();
9136 bool IsStrictLt = Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT;
9137 bool IsLe = Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE;
9138 bool IsStrictGt = Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT;
9139 bool IsGe = Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
9140 if (!IsStrictLt && !IsStrictGt && !IsGe)
9141 return nullptr;
9142
9143 APFloat One = APFloat::getOne(C->getSemantics());
9144 APFloat::cmpResult Cmp = C->compare(One);
9145
9146 // For strict-lt (olt/ult): C must be in (0, 1.0] -- C == 1.0 is fine since
9147 // the next possible value after 0.0 is 1.0, and < 1.0 excludes it.
9148 if (IsStrictLt && Cmp == APFloat::cmpGreaterThan)
9149 return nullptr;
9150 if (IsGe && Cmp == APFloat::cmpGreaterThan)
9151 return nullptr;
9152 if (IsLe && Cmp != APFloat::cmpGreaterThan)
9153 return nullptr;
9154 if (IsStrictGt && Cmp != APFloat::cmpLessThan)
9155 return nullptr;
9156
9157 // Match: fsub(uitofp(A), uitofp(B)) where both casts are uitofp or sitofp
9158 Value *A, *B;
9159 bool IsSigned;
9160 if (match(FAbsArg, m_FSub(m_UIToFP(m_Value(A)), m_UIToFP(m_Value(B))))) {
9161 IsSigned = false;
9162 } else if (match(FAbsArg,
9164 IsSigned = true;
9165 } else {
9166 return nullptr;
9167 }
9168
9169 // A and B must have the same integer type
9170 if (A->getType() != B->getType())
9171 return nullptr;
9172
9173 Type *FPTy = FAbsArg->getType();
9174 if (!IC.canBeCastedExactlyIntToFP(A, FPTy, IsSigned, &I) ||
9175 !IC.canBeCastedExactlyIntToFP(B, FPTy, IsSigned, &I))
9176 return nullptr;
9177 ICmpInst::Predicate ResultPred =
9178 IsStrictLt || IsLe ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9179 return new ICmpInst(ResultPred, A, B);
9180}
9181
9183 InstCombinerImpl &IC) {
9184 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
9185 Type *OpType = LHS->getType();
9186 CmpInst::Predicate Pred = I.getPredicate();
9187
9190
9191 if (!FloorX && !CeilX) {
9194 std::swap(LHS, RHS);
9195 Pred = I.getSwappedPredicate();
9196 }
9197 }
9198
9199 if ((FloorX || CeilX) && FCmpInst::isCommutative(Pred) && LHS->hasOneUse()) {
9200 // fcmp pred floor(x), x => fcmp pred trunc(x), x
9201 // fcmp pred ceil(x), x => fcmp pred trunc(x), x
9202 // where pred is oeq, one, ord, ueq, une, uno.
9203 Value *TruncX = IC.Builder.CreateUnaryIntrinsic(Intrinsic::trunc, RHS);
9204 return new FCmpInst(Pred, TruncX, RHS, "", &I);
9205 }
9206
9207 switch (Pred) {
9208 case FCmpInst::FCMP_OLE:
9209 // fcmp ole floor(x), x => fcmp ord x, 0
9210 if (FloorX)
9212 "", &I);
9213 break;
9214 case FCmpInst::FCMP_OGT:
9215 // fcmp ogt floor(x), x => false
9216 if (FloorX)
9217 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9218 break;
9219 case FCmpInst::FCMP_OGE:
9220 // fcmp oge ceil(x), x => fcmp ord x, 0
9221 if (CeilX)
9223 "", &I);
9224 break;
9225 case FCmpInst::FCMP_OLT:
9226 // fcmp olt ceil(x), x => false
9227 if (CeilX)
9228 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9229 break;
9230 case FCmpInst::FCMP_ULE:
9231 // fcmp ule floor(x), x => true
9232 if (FloorX)
9233 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9234 break;
9235 case FCmpInst::FCMP_UGT:
9236 // fcmp ugt floor(x), x => fcmp uno x, 0
9237 if (FloorX)
9239 "", &I);
9240 break;
9241 case FCmpInst::FCMP_UGE:
9242 // fcmp uge ceil(x), x => true
9243 if (CeilX)
9244 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9245 break;
9246 case FCmpInst::FCMP_ULT:
9247 // fcmp ult ceil(x), x => fcmp uno x, 0
9248 if (CeilX)
9250 "", &I);
9251 break;
9252 default:
9253 break;
9254 }
9255
9256 return nullptr;
9257}
9258
9259/// Returns true if a select that implements a min/max is redundant and
9260/// select result can be replaced with its non-constant operand, e.g.,
9261/// select ( (si/ui-to-fp A) <= C ), C, (si/ui-to-fp A)
9262/// where C is the FP constant equal to the minimum integer value
9263/// representable by A.
9265 Value *B) {
9266 const APFloat *APF;
9267 if (!match(B, m_APFloat(APF)))
9268 return false;
9269
9270 auto *I = dyn_cast<Instruction>(A);
9271 if (!I || !(I->getOpcode() == Instruction::SIToFP ||
9272 I->getOpcode() == Instruction::UIToFP))
9273 return false;
9274
9275 bool IsUnsigned = I->getOpcode() == Instruction::UIToFP;
9276 unsigned BitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
9277 APSInt IntBoundary = (Flavor == SPF_FMAXNUM)
9278 ? APSInt::getMinValue(BitWidth, IsUnsigned)
9279 : APSInt::getMaxValue(BitWidth, IsUnsigned);
9280 APSInt ConvertedInt(BitWidth, IsUnsigned);
9281 bool IsExact;
9283 APF->convertToInteger(ConvertedInt, APFloat::rmTowardZero, &IsExact);
9284 return Status == APFloat::opOK && IsExact && ConvertedInt == IntBoundary;
9285}
9286
9288 bool Changed = false;
9289
9290 /// Orders the operands of the compare so that they are listed from most
9291 /// complex to least complex. This puts constants before unary operators,
9292 /// before binary operators.
9293 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
9294 I.swapOperands();
9295 Changed = true;
9296 }
9297
9298 const CmpInst::Predicate Pred = I.getPredicate();
9299 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
9300 if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
9301 SQ.getWithInstruction(&I)))
9302 return replaceInstUsesWith(I, V);
9303
9304 // Simplify 'fcmp pred X, X'
9305 Type *OpType = Op0->getType();
9306 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
9307 if (Op0 == Op1) {
9308 switch (Pred) {
9309 default:
9310 break;
9311 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
9312 case FCmpInst::FCMP_ULT: // True if unordered or less than
9313 case FCmpInst::FCMP_UGT: // True if unordered or greater than
9314 case FCmpInst::FCMP_UNE: // True if unordered or not equal
9315 // Canonicalize these to be 'fcmp uno %X, 0.0'.
9316 I.setPredicate(FCmpInst::FCMP_UNO);
9317 I.setOperand(1, Constant::getNullValue(OpType));
9318 return &I;
9319
9320 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
9321 case FCmpInst::FCMP_OEQ: // True if ordered and equal
9322 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
9323 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
9324 // Canonicalize these to be 'fcmp ord %X, 0.0'.
9325 I.setPredicate(FCmpInst::FCMP_ORD);
9326 I.setOperand(1, Constant::getNullValue(OpType));
9327 return &I;
9328 }
9329 }
9330
9331 if (I.isCommutative()) {
9332 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
9333 replaceOperand(I, 0, Pair->first);
9334 replaceOperand(I, 1, Pair->second);
9335 return &I;
9336 }
9337 }
9338
9339 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
9340 // then canonicalize the operand to 0.0.
9341 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
9342 if (!match(Op0, m_PosZeroFP()) &&
9343 isKnownNeverNaN(Op0, getSimplifyQuery().getWithInstruction(&I)))
9344 return replaceOperand(I, 0, ConstantFP::getZero(OpType));
9345
9346 if (!match(Op1, m_PosZeroFP()) &&
9347 isKnownNeverNaN(Op1, getSimplifyQuery().getWithInstruction(&I)))
9348 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
9349 }
9350
9351 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
9352 Value *X, *Y;
9353 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
9354 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
9355
9357 return R;
9358
9359 // Test if the FCmpInst instruction is used exclusively by a select as
9360 // part of a minimum or maximum operation. If so, refrain from doing
9361 // any other folding. This helps out other analyses which understand
9362 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
9363 // and CodeGen. And in this case, at least one of the comparison
9364 // operands has at least one user besides the compare (the select),
9365 // which would often largely negate the benefit of folding anyway.
9366 if (I.hasOneUse())
9367 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
9368 Value *A, *B;
9370 bool IsRedundantMinMaxClamp =
9371 (SPR.Flavor == SPF_FMAXNUM || SPR.Flavor == SPF_FMINNUM) &&
9373 if (SPR.Flavor != SPF_UNKNOWN && !IsRedundantMinMaxClamp)
9374 return nullptr;
9375 }
9376
9377 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
9378 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
9379 if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP()))
9380 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
9381
9382 // Canonicalize:
9383 // fcmp olt X, +inf -> fcmp one X, +inf
9384 // fcmp ole X, +inf -> fcmp ord X, 0
9385 // fcmp ogt X, +inf -> false
9386 // fcmp oge X, +inf -> fcmp oeq X, +inf
9387 // fcmp ult X, +inf -> fcmp une X, +inf
9388 // fcmp ule X, +inf -> true
9389 // fcmp ugt X, +inf -> fcmp uno X, 0
9390 // fcmp uge X, +inf -> fcmp ueq X, +inf
9391 // fcmp olt X, -inf -> false
9392 // fcmp ole X, -inf -> fcmp oeq X, -inf
9393 // fcmp ogt X, -inf -> fcmp one X, -inf
9394 // fcmp oge X, -inf -> fcmp ord X, 0
9395 // fcmp ult X, -inf -> fcmp uno X, 0
9396 // fcmp ule X, -inf -> fcmp ueq X, -inf
9397 // fcmp ugt X, -inf -> fcmp une X, -inf
9398 // fcmp uge X, -inf -> true
9399 const APFloat *C;
9400 if (match(Op1, m_APFloat(C)) && C->isInfinity()) {
9401 switch (C->isNegative() ? FCmpInst::getSwappedPredicate(Pred) : Pred) {
9402 default:
9403 break;
9404 case FCmpInst::FCMP_ORD:
9405 case FCmpInst::FCMP_UNO:
9408 case FCmpInst::FCMP_OGT:
9409 case FCmpInst::FCMP_ULE:
9410 llvm_unreachable("Should be simplified by InstSimplify");
9411 case FCmpInst::FCMP_OLT:
9412 return new FCmpInst(FCmpInst::FCMP_ONE, Op0, Op1, "", &I);
9413 case FCmpInst::FCMP_OLE:
9414 return new FCmpInst(FCmpInst::FCMP_ORD, Op0, ConstantFP::getZero(OpType),
9415 "", &I);
9416 case FCmpInst::FCMP_OGE:
9417 return new FCmpInst(FCmpInst::FCMP_OEQ, Op0, Op1, "", &I);
9418 case FCmpInst::FCMP_ULT:
9419 return new FCmpInst(FCmpInst::FCMP_UNE, Op0, Op1, "", &I);
9420 case FCmpInst::FCMP_UGT:
9421 return new FCmpInst(FCmpInst::FCMP_UNO, Op0, ConstantFP::getZero(OpType),
9422 "", &I);
9423 case FCmpInst::FCMP_UGE:
9424 return new FCmpInst(FCmpInst::FCMP_UEQ, Op0, Op1, "", &I);
9425 }
9426 }
9427
9428 // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
9429 // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
9430 if (match(Op1, m_PosZeroFP()) &&
9432 X->getType()->isIntOrIntVectorTy() &&
9433 !F.getDenormalMode(Op1->getType()->getScalarType()->getFltSemantics())
9434 .inputsMayBeZero()) {
9436 if (Pred == FCmpInst::FCMP_OEQ)
9437 IntPred = ICmpInst::ICMP_EQ;
9438 else if (Pred == FCmpInst::FCMP_UNE)
9439 IntPred = ICmpInst::ICMP_NE;
9440
9441 if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
9442 Type *IntTy = X->getType();
9443 const APInt &SignMask = ~APInt::getSignMask(IntTy->getScalarSizeInBits());
9444 Value *MaskX = Builder.CreateAnd(X, ConstantInt::get(IntTy, SignMask));
9445 return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(IntTy));
9446 }
9447 }
9448
9449 // Handle fcmp with instruction LHS and constant RHS.
9450 Instruction *LHSI;
9451 Constant *RHSC;
9452 if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
9453 switch (LHSI->getOpcode()) {
9454 case Instruction::Select:
9455 // fcmp eq (cond ? x : -x), 0 --> fcmp eq x, 0
9456 if (FCmpInst::isEquality(Pred) && match(RHSC, m_AnyZeroFP()) &&
9458 return replaceOperand(I, 0, X);
9460 return NV;
9461 break;
9462 case Instruction::FSub:
9463 if (LHSI->hasOneUse())
9464 if (Instruction *NV = foldFCmpFSubIntoFCmp(I, LHSI, RHSC, *this))
9465 return NV;
9466 break;
9467 case Instruction::PHI:
9468 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
9469 return NV;
9470 break;
9471 case Instruction::SIToFP:
9472 case Instruction::UIToFP:
9473 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
9474 return NV;
9475 break;
9476 case Instruction::FDiv:
9477 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
9478 return NV;
9479 break;
9480 case Instruction::Load:
9481 if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
9482 if (Instruction *Res =
9484 return Res;
9485 break;
9486 case Instruction::FPTrunc:
9487 if (Instruction *NV = foldFCmpFpTrunc(I, *LHSI, *RHSC))
9488 return NV;
9489 break;
9490 }
9491 }
9492
9493 if (Instruction *R = foldFabsWithFcmpZero(I, *this))
9494 return R;
9495
9496 if (Instruction *R = foldFCmpFAbsFSubIntToFP(I, *this))
9497 return R;
9498
9499 if (Instruction *R = foldSqrtWithFcmpZero(I, *this))
9500 return R;
9501
9502 if (Instruction *R = foldFCmpWithFloorAndCeil(I, *this))
9503 return R;
9504
9506 return R;
9507
9508 if (match(Op0, m_FNeg(m_Value(X)))) {
9509 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
9510 Constant *C;
9511 if (match(Op1, m_Constant(C)))
9512 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
9513 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
9514 }
9515
9516 // fcmp (fadd X, 0.0), Y --> fcmp X, Y
9517 if (match(Op0, m_FAdd(m_Value(X), m_AnyZeroFP())))
9518 return new FCmpInst(Pred, X, Op1, "", &I);
9519
9520 // fcmp X, (fadd Y, 0.0) --> fcmp X, Y
9521 if (match(Op1, m_FAdd(m_Value(Y), m_AnyZeroFP())))
9522 return new FCmpInst(Pred, Op0, Y, "", &I);
9523
9524 // fcmp ord/uno (fptrunc X), (fptrunc Y) -> fcmp ord/uno X, Y
9525 if ((Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) &&
9526 match(Op0, m_FPTrunc(m_Value(X))) && match(Op1, m_FPTrunc(m_Value(Y))) &&
9527 X->getType() == Y->getType())
9528 return new FCmpInst(Pred, X, Y, "", &I);
9529
9530 if (match(Op0, m_FPExt(m_Value(X)))) {
9531 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
9532 if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
9533 return new FCmpInst(Pred, X, Y, "", &I);
9534
9535 const APFloat *C;
9536 if (match(Op1, m_APFloat(C))) {
9537 const fltSemantics &FPSem =
9538 X->getType()->getScalarType()->getFltSemantics();
9539 bool Lossy;
9540 APFloat TruncC = *C;
9542
9543 if (Lossy) {
9544 // X can't possibly equal the higher-precision constant, so reduce any
9545 // equality comparison.
9546 // TODO: Other predicates can be handled via getFCmpCode().
9547 switch (Pred) {
9548 case FCmpInst::FCMP_OEQ:
9549 // X is ordered and equal to an impossible constant --> false
9550 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9551 case FCmpInst::FCMP_ONE:
9552 // X is ordered and not equal to an impossible constant --> ordered
9553 return new FCmpInst(FCmpInst::FCMP_ORD, X,
9554 ConstantFP::getZero(X->getType()));
9555 case FCmpInst::FCMP_UEQ:
9556 // X is unordered or equal to an impossible constant --> unordered
9557 return new FCmpInst(FCmpInst::FCMP_UNO, X,
9558 ConstantFP::getZero(X->getType()));
9559 case FCmpInst::FCMP_UNE:
9560 // X is unordered or not equal to an impossible constant --> true
9561 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9562 default:
9563 break;
9564 }
9565 }
9566
9567 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
9568 // Avoid lossy conversions and denormals.
9569 // Zero is a special case that's OK to convert.
9570 APFloat Fabs = TruncC;
9571 Fabs.clearSign();
9572 if (!Lossy &&
9573 (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(FPSem)))) {
9574 Constant *NewC = ConstantFP::get(X->getType(), TruncC);
9575 return new FCmpInst(Pred, X, NewC, "", &I);
9576 }
9577 }
9578 }
9579
9580 // Convert a sign-bit test of an FP value into a cast and integer compare.
9581 // TODO: Simplify if the copysign constant is 0.0 or NaN.
9582 // TODO: Handle non-zero compare constants.
9583 // TODO: Handle other predicates.
9585 m_Value(X)))) &&
9586 match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
9587 Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits());
9588 if (auto *VecTy = dyn_cast<VectorType>(OpType))
9589 IntType = VectorType::get(IntType, VecTy->getElementCount());
9590
9591 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
9592 if (Pred == FCmpInst::FCMP_OLT) {
9593 Value *IntX = Builder.CreateBitCast(X, IntType);
9594 return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
9595 ConstantInt::getNullValue(IntType));
9596 }
9597 }
9598
9599 {
9600 Value *CanonLHS = nullptr;
9602 // (canonicalize(x) == x) => (x == x)
9603 if (CanonLHS == Op1)
9604 return new FCmpInst(Pred, Op1, Op1, "", &I);
9605
9606 Value *CanonRHS = nullptr;
9608 // (x == canonicalize(x)) => (x == x)
9609 if (CanonRHS == Op0)
9610 return new FCmpInst(Pred, Op0, Op0, "", &I);
9611
9612 // (canonicalize(x) == canonicalize(y)) => (x == y)
9613 if (CanonLHS && CanonRHS)
9614 return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
9615 }
9616
9617 if (I.getType()->isVectorTy())
9618 if (Instruction *Res = foldVectorCmp(I, Builder))
9619 return Res;
9620
9621 return Changed ? &I : nullptr;
9622}
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 a class to represent arbitrary precision integral constant values and operations...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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 * processUZExtIdiom(ICmpInst &I, Value *Val, const APInt *OtherVal, InstCombinerImpl &IC)
Recognize and process idiom involving test for unsigned overflow.
static Instruction * foldICmpOfCmpIntrinsicWithConstant(CmpPredicate Pred, IntrinsicInst *I, const APInt &C, InstCombiner::BuilderTy &Builder)
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 Instruction * foldFCmpFAbsFSubIntToFP(FCmpInst &I, InstCombinerImpl &IC)
Fold: fabs(uitofp(a) - uitofp(b)) pred C --> a == b where 'pred' is olt, ult, ogt,...
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:540
#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")))
SI Fold Operands
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 SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:351
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:333
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:377
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6034
void clearSign()
Definition APFloat.h:1402
bool isNaN() const
Definition APFloat.h:1581
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition APFloat.h:1192
bool isZero() const
Definition APFloat.h:1579
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1262
APInt bitcastToAPInt() const
Definition APFloat.h:1475
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1436
opStatus next(bool nextDown)
Definition APFloat.h:1358
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1202
LLVM_ABI FPClassTest classify() const
Return the FPClassTest which will return true for the value.
Definition APFloat.cpp:5963
opStatus roundToIntegral(roundingMode RM)
Definition APFloat.h:1352
bool isInfinity() const
Definition APFloat.h:1580
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1796
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:445
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
unsigned ceilLogBase2() const
Definition APInt.h:1784
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
LLVM_ABI APInt usub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1986
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:462
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1966
bool eq(const APInt &RHS) const
Equality comparison.
Definition APInt.h:1083
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
void negate()
Negate this APInt in place.
Definition APInt.h:1488
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
void flipAllBits()
Toggle every bit to its opposite value.
Definition APInt.h:1472
unsigned countl_one() const
Count the number of leading one bits.
Definition APInt.h:1635
unsigned logBase2() const
Definition APInt.h:1781
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:471
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:401
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1979
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
unsigned countr_one() const
Count the number of trailing one bits.
Definition APInt.h:1676
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
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
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; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
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.
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:728
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate getStrictPredicate() const
For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT.
Definition InstrTypes.h:921
bool isEquality() const
Determine if this is an equals/not equals predicate.
Definition InstrTypes.h:978
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:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
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:934
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:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
bool isUnsigned() const
Definition InstrTypes.h:999
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.
Conditional Branch instruction.
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 ConstantFP * 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...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition Constants.cpp:68
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.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:758
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:767
iterator end()
Definition DenseMap.h:687
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 isCommutative(Predicate Pred)
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:390
LLVM_ABI Type * getSourceElementType() const
Definition Operator.cpp:86
Value * getPointerOperand()
Definition Operator.h:417
GEPNoWrapFlags getNoWrapFlags() const
Definition Operator.h:385
bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
Definition Operator.h:464
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:111
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1575
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:199
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2501
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1597
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition IRBuilder.h:489
LLVM_ABI Value * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *Op, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2918
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.
OverflowResult computeOverflow(Instruction::BinaryOps BinaryOp, bool IsSigned, Value *LHS, Value *RHS, Instruction *CtxI) const
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 * 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 * foldCmpSelectOfConstants(CmpInst &I)
Fold fcmp/icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2) where all true/false values are cons...
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,...
const InstCombineCLOptions & CLOpts
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 * foldICmpCommutative(CmpPredicate Pred, Value *Op0, Value *Op1, ICmpInst &CtxI)
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)
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.
SimplifyQuery SQ
OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const Instruction *CtxI) const
Module & getModule() const
LLVM_ABI bool canBeCastedExactlyIntToFP(Value *V, Type *FPTy, bool IsSigned, const Instruction *CtxI=nullptr) const
bool isFreeToInvert(Value *V, bool WillInvertAllUses, bool &DoesConsume)
Return true if the specified value is free to invert (apply ~ to).
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
unsigned ComputeMaxSignificantBits(const Value *Op, const Instruction *CtxI=nullptr, unsigned Depth=0) const
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, const Instruction *CtxI=nullptr, unsigned Depth=0)
TargetLibraryInfo & TLI
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
static Constant * SubOne(Constant *C)
Subtract one from a Constant.
OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const Instruction *CtxI) 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
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
bool canFreelyInvertAllUsersOf(Instruction *V, Value *IgnoredUser)
Given i1 V, can every user of V be freely adapted if V is changed to !V ?
OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const Instruction *CtxI) const
void addToWorklist(Instruction *I)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const Instruction *CtxI, bool IsNSW=false) const
OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const Instruction *CtxI) const
DominatorTree & DT
OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const Instruction *CtxI) const
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CtxI, unsigned Depth=0) const
Value * getFreelyInverted(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume)
const SimplifyQuery & getSimplifyQuery() const
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.
iterator_range< user_iterator > users()
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:338
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:68
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:258
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
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:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition Type.h:167
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
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:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
LLVM_ABI int getFPMantissaWidth() const
Return the width of the mantissa of this type.
Definition Type.cpp:227
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
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:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI bool hasNUsesOrMore(unsigned N) const
Return true if this value has N uses or more.
Definition Value.cpp:155
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:712
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
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:2801
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:2819
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
auto m_PosZeroFP()
Matches a floating-point positive zero.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
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)
match_unless< Pattern > m_Unless(const Pattern &P)
Match if the inner matcher does NOT match.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_combine_and< Ty... > m_CombineAnd(const Ty &...Ps)
Combine pattern matchers matching all of Ps patterns.
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)
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)
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(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)
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)
auto m_Sqrt(const Opnd0 &Op0)
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.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
match_deferred< 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()...
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.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
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_or< CastInst_match< OpTy, UIToFPInst >, CastInst_match< OpTy, SIToFPInst > > m_IToFP(const OpTy &Op)
auto m_Value()
Match an arbitrary value and ignore it.
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)
auto m_Constant()
Match an arbitrary Constant and ignore it.
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.
cst_pred_ty< is_non_zero_int > m_NonZeroInt()
Match a non-zero integer or a vector with all non-zero elements.
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)
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.
cstfp_pred_ty< is_finitenonzero > m_FiniteNonZero()
Match a finite non-zero FP constant.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_FAbs(const Opnd0 &Op0)
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'.
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.
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
auto m_MaxOrMin(const Opnd0 &Op0, const Opnd1 &Op1)
CastInst_match< OpTy, FPTruncInst > m_FPTrunc(const OpTy &Op)
auto m_Undef()
Match an arbitrary undef constant.
auto m_VecReverse(const Opnd0 &Op0)
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)
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)
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.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
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:846
@ 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.
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:1755
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.
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ BinaryOp
One of the operands is a binary op.
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,...
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:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=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 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:1692
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CtxI=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.
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 Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
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:326
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:263
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.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
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:972
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:1701
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:1769
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.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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:389
@ 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()).
IntPtrTy
Definition InstrProf.h:82
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:2035
LLVM_ABI bool isKnownNeverInfOrNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point value can never contain a NaN or infinity.
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:2182
@ Continue
Definition DWP.h:26
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.
LLVM_ABI 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.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#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:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
APInt getSignedMaxValue() const
Return the maximal signed value possible given these KnownBits.
Definition KnownBits.h:152
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
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:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
bool isStrictlyPositive() const
Returns true if this value is known to be positive.
Definition KnownBits.h:112
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
unsigned countMinPopulation() const
Returns the number of bits known to be one.
Definition KnownBits.h:300
APInt getSignedMinValue() const
Return the minimal signed value possible given these KnownBits.
Definition KnownBits.h:136
const APInt & getConstant() const
Returns the value when all bits have a known value.
Definition KnownBits.h:58
Linear expression BasePtr + Index * Scale + Offset.
Definition Loads.h:224
GEPNoWrapFlags Flags
Definition Loads.h:229
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 DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const Instruction * CtxI
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342
Capture information for a specific Use.