[llvm-objdump] - Remove one overload of reportError. NFCI.
[llvm-complete.git] / lib / Transforms / InstCombine / InstCombineCompares.cpp
blobc4491178018a605b74366e8775b982420145a4f1
1 //===- InstCombineCompares.cpp --------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visitICmp and visitFCmp functions.
11 //===----------------------------------------------------------------------===//
13 #include "InstCombineInternal.h"
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/ConstantFolding.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/TargetLibraryInfo.h"
20 #include "llvm/IR/ConstantRange.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/GetElementPtrTypeIterator.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/PatternMatch.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/KnownBits.h"
28 using namespace llvm;
29 using namespace PatternMatch;
31 #define DEBUG_TYPE "instcombine"
33 // How many times is a select replaced by one of its operands?
34 STATISTIC(NumSel, "Number of select opts");
37 /// Compute Result = In1+In2, returning true if the result overflowed for this
38 /// type.
39 static bool addWithOverflow(APInt &Result, const APInt &In1,
40 const APInt &In2, bool IsSigned = false) {
41 bool Overflow;
42 if (IsSigned)
43 Result = In1.sadd_ov(In2, Overflow);
44 else
45 Result = In1.uadd_ov(In2, Overflow);
47 return Overflow;
50 /// Compute Result = In1-In2, returning true if the result overflowed for this
51 /// type.
52 static bool subWithOverflow(APInt &Result, const APInt &In1,
53 const APInt &In2, bool IsSigned = false) {
54 bool Overflow;
55 if (IsSigned)
56 Result = In1.ssub_ov(In2, Overflow);
57 else
58 Result = In1.usub_ov(In2, Overflow);
60 return Overflow;
63 /// Given an icmp instruction, return true if any use of this comparison is a
64 /// branch on sign bit comparison.
65 static bool hasBranchUse(ICmpInst &I) {
66 for (auto *U : I.users())
67 if (isa<BranchInst>(U))
68 return true;
69 return false;
72 /// Given an exploded icmp instruction, return true if the comparison only
73 /// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if the
74 /// result of the comparison is true when the input value is signed.
75 static bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS,
76 bool &TrueIfSigned) {
77 switch (Pred) {
78 case ICmpInst::ICMP_SLT: // True if LHS s< 0
79 TrueIfSigned = true;
80 return RHS.isNullValue();
81 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
82 TrueIfSigned = true;
83 return RHS.isAllOnesValue();
84 case ICmpInst::ICMP_SGT: // True if LHS s> -1
85 TrueIfSigned = false;
86 return RHS.isAllOnesValue();
87 case ICmpInst::ICMP_UGT:
88 // True if LHS u> RHS and RHS == high-bit-mask - 1
89 TrueIfSigned = true;
90 return RHS.isMaxSignedValue();
91 case ICmpInst::ICMP_UGE:
92 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
93 TrueIfSigned = true;
94 return RHS.isSignMask();
95 default:
96 return false;
100 /// Returns true if the exploded icmp can be expressed as a signed comparison
101 /// to zero and updates the predicate accordingly.
102 /// The signedness of the comparison is preserved.
103 /// TODO: Refactor with decomposeBitTestICmp()?
104 static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
105 if (!ICmpInst::isSigned(Pred))
106 return false;
108 if (C.isNullValue())
109 return ICmpInst::isRelational(Pred);
111 if (C.isOneValue()) {
112 if (Pred == ICmpInst::ICMP_SLT) {
113 Pred = ICmpInst::ICMP_SLE;
114 return true;
116 } else if (C.isAllOnesValue()) {
117 if (Pred == ICmpInst::ICMP_SGT) {
118 Pred = ICmpInst::ICMP_SGE;
119 return true;
123 return false;
126 /// Given a signed integer type and a set of known zero and one bits, compute
127 /// the maximum and minimum values that could have the specified known zero and
128 /// known one bits, returning them in Min/Max.
129 /// TODO: Move to method on KnownBits struct?
130 static void computeSignedMinMaxValuesFromKnownBits(const KnownBits &Known,
131 APInt &Min, APInt &Max) {
132 assert(Known.getBitWidth() == Min.getBitWidth() &&
133 Known.getBitWidth() == Max.getBitWidth() &&
134 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
135 APInt UnknownBits = ~(Known.Zero|Known.One);
137 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
138 // bit if it is unknown.
139 Min = Known.One;
140 Max = Known.One|UnknownBits;
142 if (UnknownBits.isNegative()) { // Sign bit is unknown
143 Min.setSignBit();
144 Max.clearSignBit();
148 /// Given an unsigned integer type and a set of known zero and one bits, compute
149 /// the maximum and minimum values that could have the specified known zero and
150 /// known one bits, returning them in Min/Max.
151 /// TODO: Move to method on KnownBits struct?
152 static void computeUnsignedMinMaxValuesFromKnownBits(const KnownBits &Known,
153 APInt &Min, APInt &Max) {
154 assert(Known.getBitWidth() == Min.getBitWidth() &&
155 Known.getBitWidth() == Max.getBitWidth() &&
156 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
157 APInt UnknownBits = ~(Known.Zero|Known.One);
159 // The minimum value is when the unknown bits are all zeros.
160 Min = Known.One;
161 // The maximum value is when the unknown bits are all ones.
162 Max = Known.One|UnknownBits;
165 /// This is called when we see this pattern:
166 /// cmp pred (load (gep GV, ...)), cmpcst
167 /// where GV is a global variable with a constant initializer. Try to simplify
168 /// this into some simple computation that does not need the load. For example
169 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
171 /// If AndCst is non-null, then the loaded value is masked with that constant
172 /// before doing the comparison. This handles cases like "A[i]&4 == 0".
173 Instruction *InstCombiner::foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
174 GlobalVariable *GV,
175 CmpInst &ICI,
176 ConstantInt *AndCst) {
177 Constant *Init = GV->getInitializer();
178 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
179 return nullptr;
181 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
182 // Don't blow up on huge arrays.
183 if (ArrayElementCount > MaxArraySizeForCombine)
184 return nullptr;
186 // There are many forms of this optimization we can handle, for now, just do
187 // the simple index into a single-dimensional array.
189 // Require: GEP GV, 0, i {{, constant indices}}
190 if (GEP->getNumOperands() < 3 ||
191 !isa<ConstantInt>(GEP->getOperand(1)) ||
192 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
193 isa<Constant>(GEP->getOperand(2)))
194 return nullptr;
196 // Check that indices after the variable are constants and in-range for the
197 // type they index. Collect the indices. This is typically for arrays of
198 // structs.
199 SmallVector<unsigned, 4> LaterIndices;
201 Type *EltTy = Init->getType()->getArrayElementType();
202 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
203 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
204 if (!Idx) return nullptr; // Variable index.
206 uint64_t IdxVal = Idx->getZExtValue();
207 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
209 if (StructType *STy = dyn_cast<StructType>(EltTy))
210 EltTy = STy->getElementType(IdxVal);
211 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
212 if (IdxVal >= ATy->getNumElements()) return nullptr;
213 EltTy = ATy->getElementType();
214 } else {
215 return nullptr; // Unknown type.
218 LaterIndices.push_back(IdxVal);
221 enum { Overdefined = -3, Undefined = -2 };
223 // Variables for our state machines.
225 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
226 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
227 // and 87 is the second (and last) index. FirstTrueElement is -2 when
228 // undefined, otherwise set to the first true element. SecondTrueElement is
229 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
230 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
232 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
233 // form "i != 47 & i != 87". Same state transitions as for true elements.
234 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
236 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
237 /// define a state machine that triggers for ranges of values that the index
238 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
239 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
240 /// index in the range (inclusive). We use -2 for undefined here because we
241 /// use relative comparisons and don't want 0-1 to match -1.
242 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
244 // MagicBitvector - This is a magic bitvector where we set a bit if the
245 // comparison is true for element 'i'. If there are 64 elements or less in
246 // the array, this will fully represent all the comparison results.
247 uint64_t MagicBitvector = 0;
249 // Scan the array and see if one of our patterns matches.
250 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
251 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
252 Constant *Elt = Init->getAggregateElement(i);
253 if (!Elt) return nullptr;
255 // If this is indexing an array of structures, get the structure element.
256 if (!LaterIndices.empty())
257 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
259 // If the element is masked, handle it.
260 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
262 // Find out if the comparison would be true or false for the i'th element.
263 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
264 CompareRHS, DL, &TLI);
265 // If the result is undef for this element, ignore it.
266 if (isa<UndefValue>(C)) {
267 // Extend range state machines to cover this element in case there is an
268 // undef in the middle of the range.
269 if (TrueRangeEnd == (int)i-1)
270 TrueRangeEnd = i;
271 if (FalseRangeEnd == (int)i-1)
272 FalseRangeEnd = i;
273 continue;
276 // If we can't compute the result for any of the elements, we have to give
277 // up evaluating the entire conditional.
278 if (!isa<ConstantInt>(C)) return nullptr;
280 // Otherwise, we know if the comparison is true or false for this element,
281 // update our state machines.
282 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
284 // State machine for single/double/range index comparison.
285 if (IsTrueForElt) {
286 // Update the TrueElement state machine.
287 if (FirstTrueElement == Undefined)
288 FirstTrueElement = TrueRangeEnd = i; // First true element.
289 else {
290 // Update double-compare state machine.
291 if (SecondTrueElement == Undefined)
292 SecondTrueElement = i;
293 else
294 SecondTrueElement = Overdefined;
296 // Update range state machine.
297 if (TrueRangeEnd == (int)i-1)
298 TrueRangeEnd = i;
299 else
300 TrueRangeEnd = Overdefined;
302 } else {
303 // Update the FalseElement state machine.
304 if (FirstFalseElement == Undefined)
305 FirstFalseElement = FalseRangeEnd = i; // First false element.
306 else {
307 // Update double-compare state machine.
308 if (SecondFalseElement == Undefined)
309 SecondFalseElement = i;
310 else
311 SecondFalseElement = Overdefined;
313 // Update range state machine.
314 if (FalseRangeEnd == (int)i-1)
315 FalseRangeEnd = i;
316 else
317 FalseRangeEnd = Overdefined;
321 // If this element is in range, update our magic bitvector.
322 if (i < 64 && IsTrueForElt)
323 MagicBitvector |= 1ULL << i;
325 // If all of our states become overdefined, bail out early. Since the
326 // predicate is expensive, only check it every 8 elements. This is only
327 // really useful for really huge arrays.
328 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
329 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
330 FalseRangeEnd == Overdefined)
331 return nullptr;
334 // Now that we've scanned the entire array, emit our new comparison(s). We
335 // order the state machines in complexity of the generated code.
336 Value *Idx = GEP->getOperand(2);
338 // If the index is larger than the pointer size of the target, truncate the
339 // index down like the GEP would do implicitly. We don't have to do this for
340 // an inbounds GEP because the index can't be out of range.
341 if (!GEP->isInBounds()) {
342 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
343 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
344 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
345 Idx = Builder.CreateTrunc(Idx, IntPtrTy);
348 // If the comparison is only true for one or two elements, emit direct
349 // comparisons.
350 if (SecondTrueElement != Overdefined) {
351 // None true -> false.
352 if (FirstTrueElement == Undefined)
353 return replaceInstUsesWith(ICI, Builder.getFalse());
355 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
357 // True for one element -> 'i == 47'.
358 if (SecondTrueElement == Undefined)
359 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
361 // True for two elements -> 'i == 47 | i == 72'.
362 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
363 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
364 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
365 return BinaryOperator::CreateOr(C1, C2);
368 // If the comparison is only false for one or two elements, emit direct
369 // comparisons.
370 if (SecondFalseElement != Overdefined) {
371 // None false -> true.
372 if (FirstFalseElement == Undefined)
373 return replaceInstUsesWith(ICI, Builder.getTrue());
375 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
377 // False for one element -> 'i != 47'.
378 if (SecondFalseElement == Undefined)
379 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
381 // False for two elements -> 'i != 47 & i != 72'.
382 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
383 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
384 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
385 return BinaryOperator::CreateAnd(C1, C2);
388 // If the comparison can be replaced with a range comparison for the elements
389 // where it is true, emit the range check.
390 if (TrueRangeEnd != Overdefined) {
391 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
393 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
394 if (FirstTrueElement) {
395 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
396 Idx = Builder.CreateAdd(Idx, Offs);
399 Value *End = ConstantInt::get(Idx->getType(),
400 TrueRangeEnd-FirstTrueElement+1);
401 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
404 // False range check.
405 if (FalseRangeEnd != Overdefined) {
406 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
407 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
408 if (FirstFalseElement) {
409 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
410 Idx = Builder.CreateAdd(Idx, Offs);
413 Value *End = ConstantInt::get(Idx->getType(),
414 FalseRangeEnd-FirstFalseElement);
415 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
418 // If a magic bitvector captures the entire comparison state
419 // of this load, replace it with computation that does:
420 // ((magic_cst >> i) & 1) != 0
422 Type *Ty = nullptr;
424 // Look for an appropriate type:
425 // - The type of Idx if the magic fits
426 // - The smallest fitting legal type
427 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
428 Ty = Idx->getType();
429 else
430 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
432 if (Ty) {
433 Value *V = Builder.CreateIntCast(Idx, Ty, false);
434 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
435 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
436 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
440 return nullptr;
443 /// Return a value that can be used to compare the *offset* implied by a GEP to
444 /// zero. For example, if we have &A[i], we want to return 'i' for
445 /// "icmp ne i, 0". Note that, in general, indices can be complex, and scales
446 /// are involved. The above expression would also be legal to codegen as
447 /// "icmp ne (i*4), 0" (assuming A is a pointer to i32).
448 /// This latter form is less amenable to optimization though, and we are allowed
449 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
451 /// If we can't emit an optimized form for this expression, this returns null.
453 static Value *evaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
454 const DataLayout &DL) {
455 gep_type_iterator GTI = gep_type_begin(GEP);
457 // Check to see if this gep only has a single variable index. If so, and if
458 // any constant indices are a multiple of its scale, then we can compute this
459 // in terms of the scale of the variable index. For example, if the GEP
460 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
461 // because the expression will cross zero at the same point.
462 unsigned i, e = GEP->getNumOperands();
463 int64_t Offset = 0;
464 for (i = 1; i != e; ++i, ++GTI) {
465 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
466 // Compute the aggregate offset of constant indices.
467 if (CI->isZero()) continue;
469 // Handle a struct index, which adds its field offset to the pointer.
470 if (StructType *STy = GTI.getStructTypeOrNull()) {
471 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
472 } else {
473 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
474 Offset += Size*CI->getSExtValue();
476 } else {
477 // Found our variable index.
478 break;
482 // If there are no variable indices, we must have a constant offset, just
483 // evaluate it the general way.
484 if (i == e) return nullptr;
486 Value *VariableIdx = GEP->getOperand(i);
487 // Determine the scale factor of the variable element. For example, this is
488 // 4 if the variable index is into an array of i32.
489 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
491 // Verify that there are no other variable indices. If so, emit the hard way.
492 for (++i, ++GTI; i != e; ++i, ++GTI) {
493 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
494 if (!CI) return nullptr;
496 // Compute the aggregate offset of constant indices.
497 if (CI->isZero()) continue;
499 // Handle a struct index, which adds its field offset to the pointer.
500 if (StructType *STy = GTI.getStructTypeOrNull()) {
501 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
502 } else {
503 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
504 Offset += Size*CI->getSExtValue();
508 // Okay, we know we have a single variable index, which must be a
509 // pointer/array/vector index. If there is no offset, life is simple, return
510 // the index.
511 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
512 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
513 if (Offset == 0) {
514 // Cast to intptrty in case a truncation occurs. If an extension is needed,
515 // we don't need to bother extending: the extension won't affect where the
516 // computation crosses zero.
517 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
518 VariableIdx = IC.Builder.CreateTrunc(VariableIdx, IntPtrTy);
520 return VariableIdx;
523 // Otherwise, there is an index. The computation we will do will be modulo
524 // the pointer size.
525 Offset = SignExtend64(Offset, IntPtrWidth);
526 VariableScale = SignExtend64(VariableScale, IntPtrWidth);
528 // To do this transformation, any constant index must be a multiple of the
529 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
530 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
531 // multiple of the variable scale.
532 int64_t NewOffs = Offset / (int64_t)VariableScale;
533 if (Offset != NewOffs*(int64_t)VariableScale)
534 return nullptr;
536 // Okay, we can do this evaluation. Start by converting the index to intptr.
537 if (VariableIdx->getType() != IntPtrTy)
538 VariableIdx = IC.Builder.CreateIntCast(VariableIdx, IntPtrTy,
539 true /*Signed*/);
540 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
541 return IC.Builder.CreateAdd(VariableIdx, OffsetVal, "offset");
544 /// Returns true if we can rewrite Start as a GEP with pointer Base
545 /// and some integer offset. The nodes that need to be re-written
546 /// for this transformation will be added to Explored.
547 static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
548 const DataLayout &DL,
549 SetVector<Value *> &Explored) {
550 SmallVector<Value *, 16> WorkList(1, Start);
551 Explored.insert(Base);
553 // The following traversal gives us an order which can be used
554 // when doing the final transformation. Since in the final
555 // transformation we create the PHI replacement instructions first,
556 // we don't have to get them in any particular order.
558 // However, for other instructions we will have to traverse the
559 // operands of an instruction first, which means that we have to
560 // do a post-order traversal.
561 while (!WorkList.empty()) {
562 SetVector<PHINode *> PHIs;
564 while (!WorkList.empty()) {
565 if (Explored.size() >= 100)
566 return false;
568 Value *V = WorkList.back();
570 if (Explored.count(V) != 0) {
571 WorkList.pop_back();
572 continue;
575 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
576 !isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
577 // We've found some value that we can't explore which is different from
578 // the base. Therefore we can't do this transformation.
579 return false;
581 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
582 auto *CI = dyn_cast<CastInst>(V);
583 if (!CI->isNoopCast(DL))
584 return false;
586 if (Explored.count(CI->getOperand(0)) == 0)
587 WorkList.push_back(CI->getOperand(0));
590 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
591 // We're limiting the GEP to having one index. This will preserve
592 // the original pointer type. We could handle more cases in the
593 // future.
594 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
595 GEP->getType() != Start->getType())
596 return false;
598 if (Explored.count(GEP->getOperand(0)) == 0)
599 WorkList.push_back(GEP->getOperand(0));
602 if (WorkList.back() == V) {
603 WorkList.pop_back();
604 // We've finished visiting this node, mark it as such.
605 Explored.insert(V);
608 if (auto *PN = dyn_cast<PHINode>(V)) {
609 // We cannot transform PHIs on unsplittable basic blocks.
610 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
611 return false;
612 Explored.insert(PN);
613 PHIs.insert(PN);
617 // Explore the PHI nodes further.
618 for (auto *PN : PHIs)
619 for (Value *Op : PN->incoming_values())
620 if (Explored.count(Op) == 0)
621 WorkList.push_back(Op);
624 // Make sure that we can do this. Since we can't insert GEPs in a basic
625 // block before a PHI node, we can't easily do this transformation if
626 // we have PHI node users of transformed instructions.
627 for (Value *Val : Explored) {
628 for (Value *Use : Val->uses()) {
630 auto *PHI = dyn_cast<PHINode>(Use);
631 auto *Inst = dyn_cast<Instruction>(Val);
633 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
634 Explored.count(PHI) == 0)
635 continue;
637 if (PHI->getParent() == Inst->getParent())
638 return false;
641 return true;
644 // Sets the appropriate insert point on Builder where we can add
645 // a replacement Instruction for V (if that is possible).
646 static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
647 bool Before = true) {
648 if (auto *PHI = dyn_cast<PHINode>(V)) {
649 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
650 return;
652 if (auto *I = dyn_cast<Instruction>(V)) {
653 if (!Before)
654 I = &*std::next(I->getIterator());
655 Builder.SetInsertPoint(I);
656 return;
658 if (auto *A = dyn_cast<Argument>(V)) {
659 // Set the insertion point in the entry block.
660 BasicBlock &Entry = A->getParent()->getEntryBlock();
661 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
662 return;
664 // Otherwise, this is a constant and we don't need to set a new
665 // insertion point.
666 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
669 /// Returns a re-written value of Start as an indexed GEP using Base as a
670 /// pointer.
671 static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
672 const DataLayout &DL,
673 SetVector<Value *> &Explored) {
674 // Perform all the substitutions. This is a bit tricky because we can
675 // have cycles in our use-def chains.
676 // 1. Create the PHI nodes without any incoming values.
677 // 2. Create all the other values.
678 // 3. Add the edges for the PHI nodes.
679 // 4. Emit GEPs to get the original pointers.
680 // 5. Remove the original instructions.
681 Type *IndexType = IntegerType::get(
682 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
684 DenseMap<Value *, Value *> NewInsts;
685 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
687 // Create the new PHI nodes, without adding any incoming values.
688 for (Value *Val : Explored) {
689 if (Val == Base)
690 continue;
691 // Create empty phi nodes. This avoids cyclic dependencies when creating
692 // the remaining instructions.
693 if (auto *PHI = dyn_cast<PHINode>(Val))
694 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
695 PHI->getName() + ".idx", PHI);
697 IRBuilder<> Builder(Base->getContext());
699 // Create all the other instructions.
700 for (Value *Val : Explored) {
702 if (NewInsts.find(Val) != NewInsts.end())
703 continue;
705 if (auto *CI = dyn_cast<CastInst>(Val)) {
706 // Don't get rid of the intermediate variable here; the store can grow
707 // the map which will invalidate the reference to the input value.
708 Value *V = NewInsts[CI->getOperand(0)];
709 NewInsts[CI] = V;
710 continue;
712 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
713 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
714 : GEP->getOperand(1);
715 setInsertionPoint(Builder, GEP);
716 // Indices might need to be sign extended. GEPs will magically do
717 // this, but we need to do it ourselves here.
718 if (Index->getType()->getScalarSizeInBits() !=
719 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
720 Index = Builder.CreateSExtOrTrunc(
721 Index, NewInsts[GEP->getOperand(0)]->getType(),
722 GEP->getOperand(0)->getName() + ".sext");
725 auto *Op = NewInsts[GEP->getOperand(0)];
726 if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero())
727 NewInsts[GEP] = Index;
728 else
729 NewInsts[GEP] = Builder.CreateNSWAdd(
730 Op, Index, GEP->getOperand(0)->getName() + ".add");
731 continue;
733 if (isa<PHINode>(Val))
734 continue;
736 llvm_unreachable("Unexpected instruction type");
739 // Add the incoming values to the PHI nodes.
740 for (Value *Val : Explored) {
741 if (Val == Base)
742 continue;
743 // All the instructions have been created, we can now add edges to the
744 // phi nodes.
745 if (auto *PHI = dyn_cast<PHINode>(Val)) {
746 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
747 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
748 Value *NewIncoming = PHI->getIncomingValue(I);
750 if (NewInsts.find(NewIncoming) != NewInsts.end())
751 NewIncoming = NewInsts[NewIncoming];
753 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
758 for (Value *Val : Explored) {
759 if (Val == Base)
760 continue;
762 // Depending on the type, for external users we have to emit
763 // a GEP or a GEP + ptrtoint.
764 setInsertionPoint(Builder, Val, false);
766 // If required, create an inttoptr instruction for Base.
767 Value *NewBase = Base;
768 if (!Base->getType()->isPointerTy())
769 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
770 Start->getName() + "to.ptr");
772 Value *GEP = Builder.CreateInBoundsGEP(
773 Start->getType()->getPointerElementType(), NewBase,
774 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
776 if (!Val->getType()->isPointerTy()) {
777 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
778 Val->getName() + ".conv");
779 GEP = Cast;
781 Val->replaceAllUsesWith(GEP);
784 return NewInsts[Start];
787 /// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
788 /// the input Value as a constant indexed GEP. Returns a pair containing
789 /// the GEPs Pointer and Index.
790 static std::pair<Value *, Value *>
791 getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
792 Type *IndexType = IntegerType::get(V->getContext(),
793 DL.getIndexTypeSizeInBits(V->getType()));
795 Constant *Index = ConstantInt::getNullValue(IndexType);
796 while (true) {
797 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
798 // We accept only inbouds GEPs here to exclude the possibility of
799 // overflow.
800 if (!GEP->isInBounds())
801 break;
802 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
803 GEP->getType() == V->getType()) {
804 V = GEP->getOperand(0);
805 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
806 Index = ConstantExpr::getAdd(
807 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
808 continue;
810 break;
812 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
813 if (!CI->isNoopCast(DL))
814 break;
815 V = CI->getOperand(0);
816 continue;
818 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
819 if (!CI->isNoopCast(DL))
820 break;
821 V = CI->getOperand(0);
822 continue;
824 break;
826 return {V, Index};
829 /// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
830 /// We can look through PHIs, GEPs and casts in order to determine a common base
831 /// between GEPLHS and RHS.
832 static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
833 ICmpInst::Predicate Cond,
834 const DataLayout &DL) {
835 if (!GEPLHS->hasAllConstantIndices())
836 return nullptr;
838 // Make sure the pointers have the same type.
839 if (GEPLHS->getType() != RHS->getType())
840 return nullptr;
842 Value *PtrBase, *Index;
843 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
845 // The set of nodes that will take part in this transformation.
846 SetVector<Value *> Nodes;
848 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
849 return nullptr;
851 // We know we can re-write this as
852 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
853 // Since we've only looked through inbouds GEPs we know that we
854 // can't have overflow on either side. We can therefore re-write
855 // this as:
856 // OFFSET1 cmp OFFSET2
857 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
859 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
860 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
861 // offset. Since Index is the offset of LHS to the base pointer, we will now
862 // compare the offsets instead of comparing the pointers.
863 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
866 /// Fold comparisons between a GEP instruction and something else. At this point
867 /// we know that the GEP is on the LHS of the comparison.
868 Instruction *InstCombiner::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
869 ICmpInst::Predicate Cond,
870 Instruction &I) {
871 // Don't transform signed compares of GEPs into index compares. Even if the
872 // GEP is inbounds, the final add of the base pointer can have signed overflow
873 // and would change the result of the icmp.
874 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
875 // the maximum signed value for the pointer type.
876 if (ICmpInst::isSigned(Cond))
877 return nullptr;
879 // Look through bitcasts and addrspacecasts. We do not however want to remove
880 // 0 GEPs.
881 if (!isa<GetElementPtrInst>(RHS))
882 RHS = RHS->stripPointerCasts();
884 Value *PtrBase = GEPLHS->getOperand(0);
885 if (PtrBase == RHS && GEPLHS->isInBounds()) {
886 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
887 // This transformation (ignoring the base and scales) is valid because we
888 // know pointers can't overflow since the gep is inbounds. See if we can
889 // output an optimized form.
890 Value *Offset = evaluateGEPOffsetExpression(GEPLHS, *this, DL);
892 // If not, synthesize the offset the hard way.
893 if (!Offset)
894 Offset = EmitGEPOffset(GEPLHS);
895 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
896 Constant::getNullValue(Offset->getType()));
897 } else if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
898 isa<Constant>(RHS) && cast<Constant>(RHS)->isNullValue() &&
899 !NullPointerIsDefined(I.getFunction(),
900 RHS->getType()->getPointerAddressSpace())) {
901 // For most address spaces, an allocation can't be placed at null, but null
902 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
903 // the only valid inbounds address derived from null, is null itself.
904 // Thus, we have four cases to consider:
905 // 1) Base == nullptr, Offset == 0 -> inbounds, null
906 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
907 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
908 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
910 // (Note if we're indexing a type of size 0, that simply collapses into one
911 // of the buckets above.)
913 // In general, we're allowed to make values less poison (i.e. remove
914 // sources of full UB), so in this case, we just select between the two
915 // non-poison cases (1 and 4 above).
917 // For vectors, we apply the same reasoning on a per-lane basis.
918 auto *Base = GEPLHS->getPointerOperand();
919 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
920 int NumElts = GEPLHS->getType()->getVectorNumElements();
921 Base = Builder.CreateVectorSplat(NumElts, Base);
923 return new ICmpInst(Cond, Base,
924 ConstantExpr::getBitCast(cast<Constant>(RHS),
925 Base->getType()));
926 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
927 // If the base pointers are different, but the indices are the same, just
928 // compare the base pointer.
929 if (PtrBase != GEPRHS->getOperand(0)) {
930 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
931 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
932 GEPRHS->getOperand(0)->getType();
933 if (IndicesTheSame)
934 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
935 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
936 IndicesTheSame = false;
937 break;
940 // If all indices are the same, just compare the base pointers.
941 Type *BaseType = GEPLHS->getOperand(0)->getType();
942 if (IndicesTheSame && CmpInst::makeCmpResultType(BaseType) == I.getType())
943 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
945 // If we're comparing GEPs with two base pointers that only differ in type
946 // and both GEPs have only constant indices or just one use, then fold
947 // the compare with the adjusted indices.
948 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
949 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
950 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
951 PtrBase->stripPointerCasts() ==
952 GEPRHS->getOperand(0)->stripPointerCasts()) {
953 Value *LOffset = EmitGEPOffset(GEPLHS);
954 Value *ROffset = EmitGEPOffset(GEPRHS);
956 // If we looked through an addrspacecast between different sized address
957 // spaces, the LHS and RHS pointers are different sized
958 // integers. Truncate to the smaller one.
959 Type *LHSIndexTy = LOffset->getType();
960 Type *RHSIndexTy = ROffset->getType();
961 if (LHSIndexTy != RHSIndexTy) {
962 if (LHSIndexTy->getPrimitiveSizeInBits() <
963 RHSIndexTy->getPrimitiveSizeInBits()) {
964 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
965 } else
966 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
969 Value *Cmp = Builder.CreateICmp(ICmpInst::getSignedPredicate(Cond),
970 LOffset, ROffset);
971 return replaceInstUsesWith(I, Cmp);
974 // Otherwise, the base pointers are different and the indices are
975 // different. Try convert this to an indexed compare by looking through
976 // PHIs/casts.
977 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
980 // If one of the GEPs has all zero indices, recurse.
981 if (GEPLHS->hasAllZeroIndices())
982 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
983 ICmpInst::getSwappedPredicate(Cond), I);
985 // If the other GEP has all zero indices, recurse.
986 if (GEPRHS->hasAllZeroIndices())
987 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
989 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
990 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
991 // If the GEPs only differ by one index, compare it.
992 unsigned NumDifferences = 0; // Keep track of # differences.
993 unsigned DiffOperand = 0; // The operand that differs.
994 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
995 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
996 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
997 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
998 // Irreconcilable differences.
999 NumDifferences = 2;
1000 break;
1001 } else {
1002 if (NumDifferences++) break;
1003 DiffOperand = i;
1007 if (NumDifferences == 0) // SAME GEP?
1008 return replaceInstUsesWith(I, // No comparison is needed here.
1009 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
1011 else if (NumDifferences == 1 && GEPsInBounds) {
1012 Value *LHSV = GEPLHS->getOperand(DiffOperand);
1013 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1014 // Make sure we do a signed comparison here.
1015 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
1019 // Only lower this if the icmp is the only user of the GEP or if we expect
1020 // the result to fold to a constant!
1021 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
1022 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1023 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
1024 Value *L = EmitGEPOffset(GEPLHS);
1025 Value *R = EmitGEPOffset(GEPRHS);
1026 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1030 // Try convert this to an indexed compare by looking through PHIs/casts as a
1031 // last resort.
1032 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
1035 Instruction *InstCombiner::foldAllocaCmp(ICmpInst &ICI,
1036 const AllocaInst *Alloca,
1037 const Value *Other) {
1038 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1040 // It would be tempting to fold away comparisons between allocas and any
1041 // pointer not based on that alloca (e.g. an argument). However, even
1042 // though such pointers cannot alias, they can still compare equal.
1044 // But LLVM doesn't specify where allocas get their memory, so if the alloca
1045 // doesn't escape we can argue that it's impossible to guess its value, and we
1046 // can therefore act as if any such guesses are wrong.
1048 // The code below checks that the alloca doesn't escape, and that it's only
1049 // used in a comparison once (the current instruction). The
1050 // single-comparison-use condition ensures that we're trivially folding all
1051 // comparisons against the alloca consistently, and avoids the risk of
1052 // erroneously folding a comparison of the pointer with itself.
1054 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1056 SmallVector<const Use *, 32> Worklist;
1057 for (const Use &U : Alloca->uses()) {
1058 if (Worklist.size() >= MaxIter)
1059 return nullptr;
1060 Worklist.push_back(&U);
1063 unsigned NumCmps = 0;
1064 while (!Worklist.empty()) {
1065 assert(Worklist.size() <= MaxIter);
1066 const Use *U = Worklist.pop_back_val();
1067 const Value *V = U->getUser();
1068 --MaxIter;
1070 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1071 isa<SelectInst>(V)) {
1072 // Track the uses.
1073 } else if (isa<LoadInst>(V)) {
1074 // Loading from the pointer doesn't escape it.
1075 continue;
1076 } else if (const auto *SI = dyn_cast<StoreInst>(V)) {
1077 // Storing *to* the pointer is fine, but storing the pointer escapes it.
1078 if (SI->getValueOperand() == U->get())
1079 return nullptr;
1080 continue;
1081 } else if (isa<ICmpInst>(V)) {
1082 if (NumCmps++)
1083 return nullptr; // Found more than one cmp.
1084 continue;
1085 } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
1086 switch (Intrin->getIntrinsicID()) {
1087 // These intrinsics don't escape or compare the pointer. Memset is safe
1088 // because we don't allow ptrtoint. Memcpy and memmove are safe because
1089 // we don't allow stores, so src cannot point to V.
1090 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1091 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1092 continue;
1093 default:
1094 return nullptr;
1096 } else {
1097 return nullptr;
1099 for (const Use &U : V->uses()) {
1100 if (Worklist.size() >= MaxIter)
1101 return nullptr;
1102 Worklist.push_back(&U);
1106 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
1107 return replaceInstUsesWith(
1108 ICI,
1109 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1112 /// Fold "icmp pred (X+C), X".
1113 Instruction *InstCombiner::foldICmpAddOpConst(Value *X, const APInt &C,
1114 ICmpInst::Predicate Pred) {
1115 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
1116 // so the values can never be equal. Similarly for all other "or equals"
1117 // operators.
1118 assert(!!C && "C should not be zero!");
1120 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
1121 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
1122 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
1123 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
1124 Constant *R = ConstantInt::get(X->getType(),
1125 APInt::getMaxValue(C.getBitWidth()) - C);
1126 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1129 // (X+1) >u X --> X <u (0-1) --> X != 255
1130 // (X+2) >u X --> X <u (0-2) --> X <u 254
1131 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
1132 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
1133 return new ICmpInst(ICmpInst::ICMP_ULT, X,
1134 ConstantInt::get(X->getType(), -C));
1136 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
1138 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1139 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1140 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1141 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1142 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1143 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
1144 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1145 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1146 ConstantInt::get(X->getType(), SMax - C));
1148 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1149 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1150 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1151 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1152 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1153 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
1155 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
1156 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1157 ConstantInt::get(X->getType(), SMax - (C - 1)));
1160 /// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
1161 /// (icmp eq/ne A, Log2(AP2/AP1)) ->
1162 /// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
1163 Instruction *InstCombiner::foldICmpShrConstConst(ICmpInst &I, Value *A,
1164 const APInt &AP1,
1165 const APInt &AP2) {
1166 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1168 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1169 if (I.getPredicate() == I.ICMP_NE)
1170 Pred = CmpInst::getInversePredicate(Pred);
1171 return new ICmpInst(Pred, LHS, RHS);
1174 // Don't bother doing any work for cases which InstSimplify handles.
1175 if (AP2.isNullValue())
1176 return nullptr;
1178 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
1179 if (IsAShr) {
1180 if (AP2.isAllOnesValue())
1181 return nullptr;
1182 if (AP2.isNegative() != AP1.isNegative())
1183 return nullptr;
1184 if (AP2.sgt(AP1))
1185 return nullptr;
1188 if (!AP1)
1189 // 'A' must be large enough to shift out the highest set bit.
1190 return getICmp(I.ICMP_UGT, A,
1191 ConstantInt::get(A->getType(), AP2.logBase2()));
1193 if (AP1 == AP2)
1194 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1196 int Shift;
1197 if (IsAShr && AP1.isNegative())
1198 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
1199 else
1200 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
1202 if (Shift > 0) {
1203 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1204 // There are multiple solutions if we are comparing against -1 and the LHS
1205 // of the ashr is not a power of two.
1206 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1207 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1208 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1209 } else if (AP1 == AP2.lshr(Shift)) {
1210 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1214 // Shifting const2 will never be equal to const1.
1215 // FIXME: This should always be handled by InstSimplify?
1216 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1217 return replaceInstUsesWith(I, TorF);
1220 /// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1221 /// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1222 Instruction *InstCombiner::foldICmpShlConstConst(ICmpInst &I, Value *A,
1223 const APInt &AP1,
1224 const APInt &AP2) {
1225 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1227 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1228 if (I.getPredicate() == I.ICMP_NE)
1229 Pred = CmpInst::getInversePredicate(Pred);
1230 return new ICmpInst(Pred, LHS, RHS);
1233 // Don't bother doing any work for cases which InstSimplify handles.
1234 if (AP2.isNullValue())
1235 return nullptr;
1237 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1239 if (!AP1 && AP2TrailingZeros != 0)
1240 return getICmp(
1241 I.ICMP_UGE, A,
1242 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1244 if (AP1 == AP2)
1245 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1247 // Get the distance between the lowest bits that are set.
1248 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1250 if (Shift > 0 && AP2.shl(Shift) == AP1)
1251 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1253 // Shifting const2 will never be equal to const1.
1254 // FIXME: This should always be handled by InstSimplify?
1255 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1256 return replaceInstUsesWith(I, TorF);
1259 /// The caller has matched a pattern of the form:
1260 /// I = icmp ugt (add (add A, B), CI2), CI1
1261 /// If this is of the form:
1262 /// sum = a + b
1263 /// if (sum+128 >u 255)
1264 /// Then replace it with llvm.sadd.with.overflow.i8.
1266 static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1267 ConstantInt *CI2, ConstantInt *CI1,
1268 InstCombiner &IC) {
1269 // The transformation we're trying to do here is to transform this into an
1270 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1271 // with a narrower add, and discard the add-with-constant that is part of the
1272 // range check (if we can't eliminate it, this isn't profitable).
1274 // In order to eliminate the add-with-constant, the compare can be its only
1275 // use.
1276 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1277 if (!AddWithCst->hasOneUse())
1278 return nullptr;
1280 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1281 if (!CI2->getValue().isPowerOf2())
1282 return nullptr;
1283 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1284 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1285 return nullptr;
1287 // The width of the new add formed is 1 more than the bias.
1288 ++NewWidth;
1290 // Check to see that CI1 is an all-ones value with NewWidth bits.
1291 if (CI1->getBitWidth() == NewWidth ||
1292 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1293 return nullptr;
1295 // This is only really a signed overflow check if the inputs have been
1296 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1297 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1298 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1299 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
1300 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
1301 return nullptr;
1303 // In order to replace the original add with a narrower
1304 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1305 // and truncates that discard the high bits of the add. Verify that this is
1306 // the case.
1307 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1308 for (User *U : OrigAdd->users()) {
1309 if (U == AddWithCst)
1310 continue;
1312 // Only accept truncates for now. We would really like a nice recursive
1313 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1314 // chain to see which bits of a value are actually demanded. If the
1315 // original add had another add which was then immediately truncated, we
1316 // could still do the transformation.
1317 TruncInst *TI = dyn_cast<TruncInst>(U);
1318 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1319 return nullptr;
1322 // If the pattern matches, truncate the inputs to the narrower type and
1323 // use the sadd_with_overflow intrinsic to efficiently compute both the
1324 // result and the overflow bit.
1325 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1326 Function *F = Intrinsic::getDeclaration(
1327 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1329 InstCombiner::BuilderTy &Builder = IC.Builder;
1331 // Put the new code above the original add, in case there are any uses of the
1332 // add between the add and the compare.
1333 Builder.SetInsertPoint(OrigAdd);
1335 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1336 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1337 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1338 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1339 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1341 // The inner add was the result of the narrow add, zero extended to the
1342 // wider type. Replace it with the result computed by the intrinsic.
1343 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1345 // The original icmp gets replaced with the overflow value.
1346 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1349 /// If we have:
1350 /// icmp eq/ne (urem/srem %x, %y), 0
1351 /// iff %y is a power-of-two, we can replace this with a bit test:
1352 /// icmp eq/ne (and %x, (add %y, -1)), 0
1353 Instruction *InstCombiner::foldIRemByPowerOfTwoToBitTest(ICmpInst &I) {
1354 // This fold is only valid for equality predicates.
1355 if (!I.isEquality())
1356 return nullptr;
1357 ICmpInst::Predicate Pred;
1358 Value *X, *Y, *Zero;
1359 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1360 m_CombineAnd(m_Zero(), m_Value(Zero)))))
1361 return nullptr;
1362 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, 0, &I))
1363 return nullptr;
1364 // This may increase instruction count, we don't enforce that Y is a constant.
1365 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1366 Value *Masked = Builder.CreateAnd(X, Mask);
1367 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1370 // Handle icmp pred X, 0
1371 Instruction *InstCombiner::foldICmpWithZero(ICmpInst &Cmp) {
1372 CmpInst::Predicate Pred = Cmp.getPredicate();
1373 if (!match(Cmp.getOperand(1), m_Zero()))
1374 return nullptr;
1376 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1377 if (Pred == ICmpInst::ICMP_SGT) {
1378 Value *A, *B;
1379 SelectPatternResult SPR = matchSelectPattern(Cmp.getOperand(0), A, B);
1380 if (SPR.Flavor == SPF_SMIN) {
1381 if (isKnownPositive(A, DL, 0, &AC, &Cmp, &DT))
1382 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1383 if (isKnownPositive(B, DL, 0, &AC, &Cmp, &DT))
1384 return new ICmpInst(Pred, A, Cmp.getOperand(1));
1388 if (Instruction *New = foldIRemByPowerOfTwoToBitTest(Cmp))
1389 return New;
1391 // Given:
1392 // icmp eq/ne (urem %x, %y), 0
1393 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1394 // icmp eq/ne %x, 0
1395 Value *X, *Y;
1396 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1397 ICmpInst::isEquality(Pred)) {
1398 KnownBits XKnown = computeKnownBits(X, 0, &Cmp);
1399 KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);
1400 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1401 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1404 return nullptr;
1407 /// Fold icmp Pred X, C.
1408 /// TODO: This code structure does not make sense. The saturating add fold
1409 /// should be moved to some other helper and extended as noted below (it is also
1410 /// possible that code has been made unnecessary - do we canonicalize IR to
1411 /// overflow/saturating intrinsics or not?).
1412 Instruction *InstCombiner::foldICmpWithConstant(ICmpInst &Cmp) {
1413 // Match the following pattern, which is a common idiom when writing
1414 // overflow-safe integer arithmetic functions. The source performs an addition
1415 // in wider type and explicitly checks for overflow using comparisons against
1416 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1418 // TODO: This could probably be generalized to handle other overflow-safe
1419 // operations if we worked out the formulas to compute the appropriate magic
1420 // constants.
1422 // sum = a + b
1423 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1424 CmpInst::Predicate Pred = Cmp.getPredicate();
1425 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1426 Value *A, *B;
1427 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1428 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1429 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1430 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1431 return Res;
1433 return nullptr;
1436 /// Canonicalize icmp instructions based on dominating conditions.
1437 Instruction *InstCombiner::foldICmpWithDominatingICmp(ICmpInst &Cmp) {
1438 // This is a cheap/incomplete check for dominance - just match a single
1439 // predecessor with a conditional branch.
1440 BasicBlock *CmpBB = Cmp.getParent();
1441 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1442 if (!DomBB)
1443 return nullptr;
1445 Value *DomCond;
1446 BasicBlock *TrueBB, *FalseBB;
1447 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1448 return nullptr;
1450 assert((TrueBB == CmpBB || FalseBB == CmpBB) &&
1451 "Predecessor block does not point to successor?");
1453 // The branch should get simplified. Don't bother simplifying this condition.
1454 if (TrueBB == FalseBB)
1455 return nullptr;
1457 // Try to simplify this compare to T/F based on the dominating condition.
1458 Optional<bool> Imp = isImpliedCondition(DomCond, &Cmp, DL, TrueBB == CmpBB);
1459 if (Imp)
1460 return replaceInstUsesWith(Cmp, ConstantInt::get(Cmp.getType(), *Imp));
1462 CmpInst::Predicate Pred = Cmp.getPredicate();
1463 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1464 ICmpInst::Predicate DomPred;
1465 const APInt *C, *DomC;
1466 if (match(DomCond, m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))) &&
1467 match(Y, m_APInt(C))) {
1468 // We have 2 compares of a variable with constants. Calculate the constant
1469 // ranges of those compares to see if we can transform the 2nd compare:
1470 // DomBB:
1471 // DomCond = icmp DomPred X, DomC
1472 // br DomCond, CmpBB, FalseBB
1473 // CmpBB:
1474 // Cmp = icmp Pred X, C
1475 ConstantRange CR = ConstantRange::makeAllowedICmpRegion(Pred, *C);
1476 ConstantRange DominatingCR =
1477 (CmpBB == TrueBB) ? ConstantRange::makeExactICmpRegion(DomPred, *DomC)
1478 : ConstantRange::makeExactICmpRegion(
1479 CmpInst::getInversePredicate(DomPred), *DomC);
1480 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1481 ConstantRange Difference = DominatingCR.difference(CR);
1482 if (Intersection.isEmptySet())
1483 return replaceInstUsesWith(Cmp, Builder.getFalse());
1484 if (Difference.isEmptySet())
1485 return replaceInstUsesWith(Cmp, Builder.getTrue());
1487 // Canonicalizing a sign bit comparison that gets used in a branch,
1488 // pessimizes codegen by generating branch on zero instruction instead
1489 // of a test and branch. So we avoid canonicalizing in such situations
1490 // because test and branch instruction has better branch displacement
1491 // than compare and branch instruction.
1492 bool UnusedBit;
1493 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1494 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1495 return nullptr;
1497 if (const APInt *EqC = Intersection.getSingleElement())
1498 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1499 if (const APInt *NeC = Difference.getSingleElement())
1500 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1503 return nullptr;
1506 /// Fold icmp (trunc X, Y), C.
1507 Instruction *InstCombiner::foldICmpTruncConstant(ICmpInst &Cmp,
1508 TruncInst *Trunc,
1509 const APInt &C) {
1510 ICmpInst::Predicate Pred = Cmp.getPredicate();
1511 Value *X = Trunc->getOperand(0);
1512 if (C.isOneValue() && C.getBitWidth() > 1) {
1513 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1514 Value *V = nullptr;
1515 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1516 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1517 ConstantInt::get(V->getType(), 1));
1520 if (Cmp.isEquality() && Trunc->hasOneUse()) {
1521 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1522 // of the high bits truncated out of x are known.
1523 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1524 SrcBits = X->getType()->getScalarSizeInBits();
1525 KnownBits Known = computeKnownBits(X, 0, &Cmp);
1527 // If all the high bits are known, we can do this xform.
1528 if ((Known.Zero | Known.One).countLeadingOnes() >= SrcBits - DstBits) {
1529 // Pull in the high bits from known-ones set.
1530 APInt NewRHS = C.zext(SrcBits);
1531 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1532 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), NewRHS));
1536 return nullptr;
1539 /// Fold icmp (xor X, Y), C.
1540 Instruction *InstCombiner::foldICmpXorConstant(ICmpInst &Cmp,
1541 BinaryOperator *Xor,
1542 const APInt &C) {
1543 Value *X = Xor->getOperand(0);
1544 Value *Y = Xor->getOperand(1);
1545 const APInt *XorC;
1546 if (!match(Y, m_APInt(XorC)))
1547 return nullptr;
1549 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1550 // fold the xor.
1551 ICmpInst::Predicate Pred = Cmp.getPredicate();
1552 bool TrueIfSigned = false;
1553 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1555 // If the sign bit of the XorCst is not set, there is no change to
1556 // the operation, just stop using the Xor.
1557 if (!XorC->isNegative()) {
1558 Cmp.setOperand(0, X);
1559 Worklist.Add(Xor);
1560 return &Cmp;
1563 // Emit the opposite comparison.
1564 if (TrueIfSigned)
1565 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1566 ConstantInt::getAllOnesValue(X->getType()));
1567 else
1568 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1569 ConstantInt::getNullValue(X->getType()));
1572 if (Xor->hasOneUse()) {
1573 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1574 if (!Cmp.isEquality() && XorC->isSignMask()) {
1575 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1576 : Cmp.getSignedPredicate();
1577 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1580 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1581 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1582 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1583 : Cmp.getSignedPredicate();
1584 Pred = Cmp.getSwappedPredicate(Pred);
1585 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1589 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1590 if (Pred == ICmpInst::ICMP_UGT) {
1591 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1592 if (*XorC == ~C && (C + 1).isPowerOf2())
1593 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1594 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1595 if (*XorC == C && (C + 1).isPowerOf2())
1596 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1598 if (Pred == ICmpInst::ICMP_ULT) {
1599 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1600 if (*XorC == -C && C.isPowerOf2())
1601 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1602 ConstantInt::get(X->getType(), ~C));
1603 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1604 if (*XorC == C && (-C).isPowerOf2())
1605 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1606 ConstantInt::get(X->getType(), ~C));
1608 return nullptr;
1611 /// Fold icmp (and (sh X, Y), C2), C1.
1612 Instruction *InstCombiner::foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
1613 const APInt &C1, const APInt &C2) {
1614 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1615 if (!Shift || !Shift->isShift())
1616 return nullptr;
1618 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1619 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1620 // code produced by the clang front-end, for bitfield access.
1621 // This seemingly simple opportunity to fold away a shift turns out to be
1622 // rather complicated. See PR17827 for details.
1623 unsigned ShiftOpcode = Shift->getOpcode();
1624 bool IsShl = ShiftOpcode == Instruction::Shl;
1625 const APInt *C3;
1626 if (match(Shift->getOperand(1), m_APInt(C3))) {
1627 bool CanFold = false;
1628 if (ShiftOpcode == Instruction::Shl) {
1629 // For a left shift, we can fold if the comparison is not signed. We can
1630 // also fold a signed comparison if the mask value and comparison value
1631 // are not negative. These constraints may not be obvious, but we can
1632 // prove that they are correct using an SMT solver.
1633 if (!Cmp.isSigned() || (!C2.isNegative() && !C1.isNegative()))
1634 CanFold = true;
1635 } else {
1636 bool IsAshr = ShiftOpcode == Instruction::AShr;
1637 // For a logical right shift, we can fold if the comparison is not signed.
1638 // We can also fold a signed comparison if the shifted mask value and the
1639 // shifted comparison value are not negative. These constraints may not be
1640 // obvious, but we can prove that they are correct using an SMT solver.
1641 // For an arithmetic shift right we can do the same, if we ensure
1642 // the And doesn't use any bits being shifted in. Normally these would
1643 // be turned into lshr by SimplifyDemandedBits, but not if there is an
1644 // additional user.
1645 if (!IsAshr || (C2.shl(*C3).lshr(*C3) == C2)) {
1646 if (!Cmp.isSigned() ||
1647 (!C2.shl(*C3).isNegative() && !C1.shl(*C3).isNegative()))
1648 CanFold = true;
1652 if (CanFold) {
1653 APInt NewCst = IsShl ? C1.lshr(*C3) : C1.shl(*C3);
1654 APInt SameAsC1 = IsShl ? NewCst.shl(*C3) : NewCst.lshr(*C3);
1655 // Check to see if we are shifting out any of the bits being compared.
1656 if (SameAsC1 != C1) {
1657 // If we shifted bits out, the fold is not going to work out. As a
1658 // special case, check to see if this means that the result is always
1659 // true or false now.
1660 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1661 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1662 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1663 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1664 } else {
1665 Cmp.setOperand(1, ConstantInt::get(And->getType(), NewCst));
1666 APInt NewAndCst = IsShl ? C2.lshr(*C3) : C2.shl(*C3);
1667 And->setOperand(1, ConstantInt::get(And->getType(), NewAndCst));
1668 And->setOperand(0, Shift->getOperand(0));
1669 Worklist.Add(Shift); // Shift is dead.
1670 return &Cmp;
1675 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1676 // preferable because it allows the C2 << Y expression to be hoisted out of a
1677 // loop if Y is invariant and X is not.
1678 if (Shift->hasOneUse() && C1.isNullValue() && Cmp.isEquality() &&
1679 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1680 // Compute C2 << Y.
1681 Value *NewShift =
1682 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1683 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1685 // Compute X & (C2 << Y).
1686 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1687 Cmp.setOperand(0, NewAnd);
1688 return &Cmp;
1691 return nullptr;
1694 /// Fold icmp (and X, C2), C1.
1695 Instruction *InstCombiner::foldICmpAndConstConst(ICmpInst &Cmp,
1696 BinaryOperator *And,
1697 const APInt &C1) {
1698 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1700 // For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i1
1701 // TODO: We canonicalize to the longer form for scalars because we have
1702 // better analysis/folds for icmp, and codegen may be better with icmp.
1703 if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.isNullValue() &&
1704 match(And->getOperand(1), m_One()))
1705 return new TruncInst(And->getOperand(0), Cmp.getType());
1707 const APInt *C2;
1708 Value *X;
1709 if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1710 return nullptr;
1712 // Don't perform the following transforms if the AND has multiple uses
1713 if (!And->hasOneUse())
1714 return nullptr;
1716 if (Cmp.isEquality() && C1.isNullValue()) {
1717 // Restrict this fold to single-use 'and' (PR10267).
1718 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1719 if (C2->isSignMask()) {
1720 Constant *Zero = Constant::getNullValue(X->getType());
1721 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1722 return new ICmpInst(NewPred, X, Zero);
1725 // Restrict this fold only for single-use 'and' (PR10267).
1726 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1727 if ((~(*C2) + 1).isPowerOf2()) {
1728 Constant *NegBOC =
1729 ConstantExpr::getNeg(cast<Constant>(And->getOperand(1)));
1730 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1731 return new ICmpInst(NewPred, X, NegBOC);
1735 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1736 // the input width without changing the value produced, eliminate the cast:
1738 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1740 // We can do this transformation if the constants do not have their sign bits
1741 // set or if it is an equality comparison. Extending a relational comparison
1742 // when we're checking the sign bit would not work.
1743 Value *W;
1744 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1745 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1746 // TODO: Is this a good transform for vectors? Wider types may reduce
1747 // throughput. Should this transform be limited (even for scalars) by using
1748 // shouldChangeType()?
1749 if (!Cmp.getType()->isVectorTy()) {
1750 Type *WideType = W->getType();
1751 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1752 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1753 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1754 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1755 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1759 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1760 return I;
1762 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1763 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1765 // iff pred isn't signed
1766 if (!Cmp.isSigned() && C1.isNullValue() && And->getOperand(0)->hasOneUse() &&
1767 match(And->getOperand(1), m_One())) {
1768 Constant *One = cast<Constant>(And->getOperand(1));
1769 Value *Or = And->getOperand(0);
1770 Value *A, *B, *LShr;
1771 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1772 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1773 unsigned UsesRemoved = 0;
1774 if (And->hasOneUse())
1775 ++UsesRemoved;
1776 if (Or->hasOneUse())
1777 ++UsesRemoved;
1778 if (LShr->hasOneUse())
1779 ++UsesRemoved;
1781 // Compute A & ((1 << B) | 1)
1782 Value *NewOr = nullptr;
1783 if (auto *C = dyn_cast<Constant>(B)) {
1784 if (UsesRemoved >= 1)
1785 NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1786 } else {
1787 if (UsesRemoved >= 3)
1788 NewOr = Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1789 /*HasNUW=*/true),
1790 One, Or->getName());
1792 if (NewOr) {
1793 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1794 Cmp.setOperand(0, NewAnd);
1795 return &Cmp;
1800 return nullptr;
1803 /// Fold icmp (and X, Y), C.
1804 Instruction *InstCombiner::foldICmpAndConstant(ICmpInst &Cmp,
1805 BinaryOperator *And,
1806 const APInt &C) {
1807 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1808 return I;
1810 // TODO: These all require that Y is constant too, so refactor with the above.
1812 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1813 Value *X = And->getOperand(0);
1814 Value *Y = And->getOperand(1);
1815 if (auto *LI = dyn_cast<LoadInst>(X))
1816 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1817 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1818 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1819 !LI->isVolatile() && isa<ConstantInt>(Y)) {
1820 ConstantInt *C2 = cast<ConstantInt>(Y);
1821 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C2))
1822 return Res;
1825 if (!Cmp.isEquality())
1826 return nullptr;
1828 // X & -C == -C -> X > u ~C
1829 // X & -C != -C -> X <= u ~C
1830 // iff C is a power of 2
1831 if (Cmp.getOperand(1) == Y && (-C).isPowerOf2()) {
1832 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT
1833 : CmpInst::ICMP_ULE;
1834 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1837 // (X & C2) == 0 -> (trunc X) >= 0
1838 // (X & C2) != 0 -> (trunc X) < 0
1839 // iff C2 is a power of 2 and it masks the sign bit of a legal integer type.
1840 const APInt *C2;
1841 if (And->hasOneUse() && C.isNullValue() && match(Y, m_APInt(C2))) {
1842 int32_t ExactLogBase2 = C2->exactLogBase2();
1843 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1844 Type *NTy = IntegerType::get(Cmp.getContext(), ExactLogBase2 + 1);
1845 if (And->getType()->isVectorTy())
1846 NTy = VectorType::get(NTy, And->getType()->getVectorNumElements());
1847 Value *Trunc = Builder.CreateTrunc(X, NTy);
1848 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_SGE
1849 : CmpInst::ICMP_SLT;
1850 return new ICmpInst(NewPred, Trunc, Constant::getNullValue(NTy));
1854 return nullptr;
1857 /// Fold icmp (or X, Y), C.
1858 Instruction *InstCombiner::foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
1859 const APInt &C) {
1860 ICmpInst::Predicate Pred = Cmp.getPredicate();
1861 if (C.isOneValue()) {
1862 // icmp slt signum(V) 1 --> icmp slt V, 1
1863 Value *V = nullptr;
1864 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
1865 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1866 ConstantInt::get(V->getType(), 1));
1869 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
1870 if (Cmp.isEquality() && Cmp.getOperand(1) == OrOp1) {
1871 // X | C == C --> X <=u C
1872 // X | C != C --> X >u C
1873 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
1874 if ((C + 1).isPowerOf2()) {
1875 Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT;
1876 return new ICmpInst(Pred, OrOp0, OrOp1);
1878 // More general: are all bits outside of a mask constant set or not set?
1879 // X | C == C --> (X & ~C) == 0
1880 // X | C != C --> (X & ~C) != 0
1881 if (Or->hasOneUse()) {
1882 Value *A = Builder.CreateAnd(OrOp0, ~C);
1883 return new ICmpInst(Pred, A, ConstantInt::getNullValue(OrOp0->getType()));
1887 if (!Cmp.isEquality() || !C.isNullValue() || !Or->hasOneUse())
1888 return nullptr;
1890 Value *P, *Q;
1891 if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1892 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1893 // -> and (icmp eq P, null), (icmp eq Q, null).
1894 Value *CmpP =
1895 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
1896 Value *CmpQ =
1897 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
1898 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1899 return BinaryOperator::Create(BOpc, CmpP, CmpQ);
1902 // Are we using xors to bitwise check for a pair of (in)equalities? Convert to
1903 // a shorter form that has more potential to be folded even further.
1904 Value *X1, *X2, *X3, *X4;
1905 if (match(OrOp0, m_OneUse(m_Xor(m_Value(X1), m_Value(X2)))) &&
1906 match(OrOp1, m_OneUse(m_Xor(m_Value(X3), m_Value(X4))))) {
1907 // ((X1 ^ X2) || (X3 ^ X4)) == 0 --> (X1 == X2) && (X3 == X4)
1908 // ((X1 ^ X2) || (X3 ^ X4)) != 0 --> (X1 != X2) || (X3 != X4)
1909 Value *Cmp12 = Builder.CreateICmp(Pred, X1, X2);
1910 Value *Cmp34 = Builder.CreateICmp(Pred, X3, X4);
1911 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1912 return BinaryOperator::Create(BOpc, Cmp12, Cmp34);
1915 return nullptr;
1918 /// Fold icmp (mul X, Y), C.
1919 Instruction *InstCombiner::foldICmpMulConstant(ICmpInst &Cmp,
1920 BinaryOperator *Mul,
1921 const APInt &C) {
1922 const APInt *MulC;
1923 if (!match(Mul->getOperand(1), m_APInt(MulC)))
1924 return nullptr;
1926 // If this is a test of the sign bit and the multiply is sign-preserving with
1927 // a constant operand, use the multiply LHS operand instead.
1928 ICmpInst::Predicate Pred = Cmp.getPredicate();
1929 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
1930 if (MulC->isNegative())
1931 Pred = ICmpInst::getSwappedPredicate(Pred);
1932 return new ICmpInst(Pred, Mul->getOperand(0),
1933 Constant::getNullValue(Mul->getType()));
1936 return nullptr;
1939 /// Fold icmp (shl 1, Y), C.
1940 static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl,
1941 const APInt &C) {
1942 Value *Y;
1943 if (!match(Shl, m_Shl(m_One(), m_Value(Y))))
1944 return nullptr;
1946 Type *ShiftType = Shl->getType();
1947 unsigned TypeBits = C.getBitWidth();
1948 bool CIsPowerOf2 = C.isPowerOf2();
1949 ICmpInst::Predicate Pred = Cmp.getPredicate();
1950 if (Cmp.isUnsigned()) {
1951 // (1 << Y) pred C -> Y pred Log2(C)
1952 if (!CIsPowerOf2) {
1953 // (1 << Y) < 30 -> Y <= 4
1954 // (1 << Y) <= 30 -> Y <= 4
1955 // (1 << Y) >= 30 -> Y > 4
1956 // (1 << Y) > 30 -> Y > 4
1957 if (Pred == ICmpInst::ICMP_ULT)
1958 Pred = ICmpInst::ICMP_ULE;
1959 else if (Pred == ICmpInst::ICMP_UGE)
1960 Pred = ICmpInst::ICMP_UGT;
1963 // (1 << Y) >= 2147483648 -> Y >= 31 -> Y == 31
1964 // (1 << Y) < 2147483648 -> Y < 31 -> Y != 31
1965 unsigned CLog2 = C.logBase2();
1966 if (CLog2 == TypeBits - 1) {
1967 if (Pred == ICmpInst::ICMP_UGE)
1968 Pred = ICmpInst::ICMP_EQ;
1969 else if (Pred == ICmpInst::ICMP_ULT)
1970 Pred = ICmpInst::ICMP_NE;
1972 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
1973 } else if (Cmp.isSigned()) {
1974 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
1975 if (C.isAllOnesValue()) {
1976 // (1 << Y) <= -1 -> Y == 31
1977 if (Pred == ICmpInst::ICMP_SLE)
1978 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
1980 // (1 << Y) > -1 -> Y != 31
1981 if (Pred == ICmpInst::ICMP_SGT)
1982 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
1983 } else if (!C) {
1984 // (1 << Y) < 0 -> Y == 31
1985 // (1 << Y) <= 0 -> Y == 31
1986 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1987 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
1989 // (1 << Y) >= 0 -> Y != 31
1990 // (1 << Y) > 0 -> Y != 31
1991 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1992 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
1994 } else if (Cmp.isEquality() && CIsPowerOf2) {
1995 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, C.logBase2()));
1998 return nullptr;
2001 /// Fold icmp (shl X, Y), C.
2002 Instruction *InstCombiner::foldICmpShlConstant(ICmpInst &Cmp,
2003 BinaryOperator *Shl,
2004 const APInt &C) {
2005 const APInt *ShiftVal;
2006 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2007 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2009 const APInt *ShiftAmt;
2010 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2011 return foldICmpShlOne(Cmp, Shl, C);
2013 // Check that the shift amount is in range. If not, don't perform undefined
2014 // shifts. When the shift is visited, it will be simplified.
2015 unsigned TypeBits = C.getBitWidth();
2016 if (ShiftAmt->uge(TypeBits))
2017 return nullptr;
2019 ICmpInst::Predicate Pred = Cmp.getPredicate();
2020 Value *X = Shl->getOperand(0);
2021 Type *ShType = Shl->getType();
2023 // NSW guarantees that we are only shifting out sign bits from the high bits,
2024 // so we can ASHR the compare constant without needing a mask and eliminate
2025 // the shift.
2026 if (Shl->hasNoSignedWrap()) {
2027 if (Pred == ICmpInst::ICMP_SGT) {
2028 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2029 APInt ShiftedC = C.ashr(*ShiftAmt);
2030 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2032 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2033 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2034 APInt ShiftedC = C.ashr(*ShiftAmt);
2035 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2037 if (Pred == ICmpInst::ICMP_SLT) {
2038 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2039 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2040 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2041 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2042 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2043 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2044 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2046 // If this is a signed comparison to 0 and the shift is sign preserving,
2047 // use the shift LHS operand instead; isSignTest may change 'Pred', so only
2048 // do that if we're sure to not continue on in this function.
2049 if (isSignTest(Pred, C))
2050 return new ICmpInst(Pred, X, Constant::getNullValue(ShType));
2053 // NUW guarantees that we are only shifting out zero bits from the high bits,
2054 // so we can LSHR the compare constant without needing a mask and eliminate
2055 // the shift.
2056 if (Shl->hasNoUnsignedWrap()) {
2057 if (Pred == ICmpInst::ICMP_UGT) {
2058 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2059 APInt ShiftedC = C.lshr(*ShiftAmt);
2060 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2062 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2063 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2064 APInt ShiftedC = C.lshr(*ShiftAmt);
2065 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2067 if (Pred == ICmpInst::ICMP_ULT) {
2068 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2069 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2070 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2071 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2072 assert(C.ugt(0) && "ult 0 should have been eliminated");
2073 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2074 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2078 if (Cmp.isEquality() && Shl->hasOneUse()) {
2079 // Strength-reduce the shift into an 'and'.
2080 Constant *Mask = ConstantInt::get(
2081 ShType,
2082 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2083 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2084 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2085 return new ICmpInst(Pred, And, LShrC);
2088 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2089 bool TrueIfSigned = false;
2090 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2091 // (X << 31) <s 0 --> (X & 1) != 0
2092 Constant *Mask = ConstantInt::get(
2093 ShType,
2094 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2095 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2096 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2097 And, Constant::getNullValue(ShType));
2100 // Simplify 'shl' inequality test into 'and' equality test.
2101 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2102 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2103 if ((C + 1).isPowerOf2() &&
2104 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2105 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2106 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2107 : ICmpInst::ICMP_NE,
2108 And, Constant::getNullValue(ShType));
2110 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2111 if (C.isPowerOf2() &&
2112 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2113 Value *And =
2114 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2115 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2116 : ICmpInst::ICMP_NE,
2117 And, Constant::getNullValue(ShType));
2121 // Transform (icmp pred iM (shl iM %v, N), C)
2122 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2123 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2124 // This enables us to get rid of the shift in favor of a trunc that may be
2125 // free on the target. It has the additional benefit of comparing to a
2126 // smaller constant that may be more target-friendly.
2127 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2128 if (Shl->hasOneUse() && Amt != 0 && C.countTrailingZeros() >= Amt &&
2129 DL.isLegalInteger(TypeBits - Amt)) {
2130 Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt);
2131 if (ShType->isVectorTy())
2132 TruncTy = VectorType::get(TruncTy, ShType->getVectorNumElements());
2133 Constant *NewC =
2134 ConstantInt::get(TruncTy, C.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2135 return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC);
2138 return nullptr;
2141 /// Fold icmp ({al}shr X, Y), C.
2142 Instruction *InstCombiner::foldICmpShrConstant(ICmpInst &Cmp,
2143 BinaryOperator *Shr,
2144 const APInt &C) {
2145 // An exact shr only shifts out zero bits, so:
2146 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2147 Value *X = Shr->getOperand(0);
2148 CmpInst::Predicate Pred = Cmp.getPredicate();
2149 if (Cmp.isEquality() && Shr->isExact() && Shr->hasOneUse() &&
2150 C.isNullValue())
2151 return new ICmpInst(Pred, X, Cmp.getOperand(1));
2153 const APInt *ShiftVal;
2154 if (Cmp.isEquality() && match(Shr->getOperand(0), m_APInt(ShiftVal)))
2155 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftVal);
2157 const APInt *ShiftAmt;
2158 if (!match(Shr->getOperand(1), m_APInt(ShiftAmt)))
2159 return nullptr;
2161 // Check that the shift amount is in range. If not, don't perform undefined
2162 // shifts. When the shift is visited it will be simplified.
2163 unsigned TypeBits = C.getBitWidth();
2164 unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits);
2165 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2166 return nullptr;
2168 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2169 bool IsExact = Shr->isExact();
2170 Type *ShrTy = Shr->getType();
2171 // TODO: If we could guarantee that InstSimplify would handle all of the
2172 // constant-value-based preconditions in the folds below, then we could assert
2173 // those conditions rather than checking them. This is difficult because of
2174 // undef/poison (PR34838).
2175 if (IsAShr) {
2176 if (Pred == CmpInst::ICMP_SLT || (Pred == CmpInst::ICMP_SGT && IsExact)) {
2177 // icmp slt (ashr X, ShAmtC), C --> icmp slt X, (C << ShAmtC)
2178 // icmp sgt (ashr exact X, ShAmtC), C --> icmp sgt X, (C << ShAmtC)
2179 APInt ShiftedC = C.shl(ShAmtVal);
2180 if (ShiftedC.ashr(ShAmtVal) == C)
2181 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2183 if (Pred == CmpInst::ICMP_SGT) {
2184 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2185 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2186 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2187 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2188 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2190 } else {
2191 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2192 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2193 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2194 APInt ShiftedC = C.shl(ShAmtVal);
2195 if (ShiftedC.lshr(ShAmtVal) == C)
2196 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2198 if (Pred == CmpInst::ICMP_UGT) {
2199 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2200 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2201 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2202 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2206 if (!Cmp.isEquality())
2207 return nullptr;
2209 // Handle equality comparisons of shift-by-constant.
2211 // If the comparison constant changes with the shift, the comparison cannot
2212 // succeed (bits of the comparison constant cannot match the shifted value).
2213 // This should be known by InstSimplify and already be folded to true/false.
2214 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2215 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2216 "Expected icmp+shr simplify did not occur.");
2218 // If the bits shifted out are known zero, compare the unshifted value:
2219 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2220 if (Shr->isExact())
2221 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2223 if (Shr->hasOneUse()) {
2224 // Canonicalize the shift into an 'and':
2225 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2226 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2227 Constant *Mask = ConstantInt::get(ShrTy, Val);
2228 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2229 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2232 return nullptr;
2235 /// Fold icmp (udiv X, Y), C.
2236 Instruction *InstCombiner::foldICmpUDivConstant(ICmpInst &Cmp,
2237 BinaryOperator *UDiv,
2238 const APInt &C) {
2239 const APInt *C2;
2240 if (!match(UDiv->getOperand(0), m_APInt(C2)))
2241 return nullptr;
2243 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2245 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2246 Value *Y = UDiv->getOperand(1);
2247 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT) {
2248 assert(!C.isMaxValue() &&
2249 "icmp ugt X, UINT_MAX should have been simplified already.");
2250 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2251 ConstantInt::get(Y->getType(), C2->udiv(C + 1)));
2254 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2255 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT) {
2256 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2257 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2258 ConstantInt::get(Y->getType(), C2->udiv(C)));
2261 return nullptr;
2264 /// Fold icmp ({su}div X, Y), C.
2265 Instruction *InstCombiner::foldICmpDivConstant(ICmpInst &Cmp,
2266 BinaryOperator *Div,
2267 const APInt &C) {
2268 // Fold: icmp pred ([us]div X, C2), C -> range test
2269 // Fold this div into the comparison, producing a range check.
2270 // Determine, based on the divide type, what the range is being
2271 // checked. If there is an overflow on the low or high side, remember
2272 // it, otherwise compute the range [low, hi) bounding the new value.
2273 // See: InsertRangeTest above for the kinds of replacements possible.
2274 const APInt *C2;
2275 if (!match(Div->getOperand(1), m_APInt(C2)))
2276 return nullptr;
2278 // FIXME: If the operand types don't match the type of the divide
2279 // then don't attempt this transform. The code below doesn't have the
2280 // logic to deal with a signed divide and an unsigned compare (and
2281 // vice versa). This is because (x /s C2) <s C produces different
2282 // results than (x /s C2) <u C or (x /u C2) <s C or even
2283 // (x /u C2) <u C. Simply casting the operands and result won't
2284 // work. :( The if statement below tests that condition and bails
2285 // if it finds it.
2286 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2287 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
2288 return nullptr;
2290 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2291 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2292 // division-by-constant cases should be present, we can not assert that they
2293 // have happened before we reach this icmp instruction.
2294 if (C2->isNullValue() || C2->isOneValue() ||
2295 (DivIsSigned && C2->isAllOnesValue()))
2296 return nullptr;
2298 // Compute Prod = C * C2. We are essentially solving an equation of
2299 // form X / C2 = C. We solve for X by multiplying C2 and C.
2300 // By solving for X, we can turn this into a range check instead of computing
2301 // a divide.
2302 APInt Prod = C * *C2;
2304 // Determine if the product overflows by seeing if the product is not equal to
2305 // the divide. Make sure we do the same kind of divide as in the LHS
2306 // instruction that we're folding.
2307 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2309 ICmpInst::Predicate Pred = Cmp.getPredicate();
2311 // If the division is known to be exact, then there is no remainder from the
2312 // divide, so the covered range size is unit, otherwise it is the divisor.
2313 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2315 // Figure out the interval that is being checked. For example, a comparison
2316 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2317 // Compute this interval based on the constants involved and the signedness of
2318 // the compare/divide. This computes a half-open interval, keeping track of
2319 // whether either value in the interval overflows. After analysis each
2320 // overflow variable is set to 0 if it's corresponding bound variable is valid
2321 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2322 int LoOverflow = 0, HiOverflow = 0;
2323 APInt LoBound, HiBound;
2325 if (!DivIsSigned) { // udiv
2326 // e.g. X/5 op 3 --> [15, 20)
2327 LoBound = Prod;
2328 HiOverflow = LoOverflow = ProdOV;
2329 if (!HiOverflow) {
2330 // If this is not an exact divide, then many values in the range collapse
2331 // to the same result value.
2332 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2334 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2335 if (C.isNullValue()) { // (X / pos) op 0
2336 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2337 LoBound = -(RangeSize - 1);
2338 HiBound = RangeSize;
2339 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2340 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2341 HiOverflow = LoOverflow = ProdOV;
2342 if (!HiOverflow)
2343 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2344 } else { // (X / pos) op neg
2345 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2346 HiBound = Prod + 1;
2347 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2348 if (!LoOverflow) {
2349 APInt DivNeg = -RangeSize;
2350 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2353 } else if (C2->isNegative()) { // Divisor is < 0.
2354 if (Div->isExact())
2355 RangeSize.negate();
2356 if (C.isNullValue()) { // (X / neg) op 0
2357 // e.g. X/-5 op 0 --> [-4, 5)
2358 LoBound = RangeSize + 1;
2359 HiBound = -RangeSize;
2360 if (HiBound == *C2) { // -INTMIN = INTMIN
2361 HiOverflow = 1; // [INTMIN+1, overflow)
2362 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2364 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2365 // e.g. X/-5 op 3 --> [-19, -14)
2366 HiBound = Prod + 1;
2367 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2368 if (!LoOverflow)
2369 LoOverflow = addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
2370 } else { // (X / neg) op neg
2371 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2372 LoOverflow = HiOverflow = ProdOV;
2373 if (!HiOverflow)
2374 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2377 // Dividing by a negative swaps the condition. LT <-> GT
2378 Pred = ICmpInst::getSwappedPredicate(Pred);
2381 Value *X = Div->getOperand(0);
2382 switch (Pred) {
2383 default: llvm_unreachable("Unhandled icmp opcode!");
2384 case ICmpInst::ICMP_EQ:
2385 if (LoOverflow && HiOverflow)
2386 return replaceInstUsesWith(Cmp, Builder.getFalse());
2387 if (HiOverflow)
2388 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2389 ICmpInst::ICMP_UGE, X,
2390 ConstantInt::get(Div->getType(), LoBound));
2391 if (LoOverflow)
2392 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2393 ICmpInst::ICMP_ULT, X,
2394 ConstantInt::get(Div->getType(), HiBound));
2395 return replaceInstUsesWith(
2396 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
2397 case ICmpInst::ICMP_NE:
2398 if (LoOverflow && HiOverflow)
2399 return replaceInstUsesWith(Cmp, Builder.getTrue());
2400 if (HiOverflow)
2401 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2402 ICmpInst::ICMP_ULT, X,
2403 ConstantInt::get(Div->getType(), LoBound));
2404 if (LoOverflow)
2405 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2406 ICmpInst::ICMP_UGE, X,
2407 ConstantInt::get(Div->getType(), HiBound));
2408 return replaceInstUsesWith(Cmp,
2409 insertRangeTest(X, LoBound, HiBound,
2410 DivIsSigned, false));
2411 case ICmpInst::ICMP_ULT:
2412 case ICmpInst::ICMP_SLT:
2413 if (LoOverflow == +1) // Low bound is greater than input range.
2414 return replaceInstUsesWith(Cmp, Builder.getTrue());
2415 if (LoOverflow == -1) // Low bound is less than input range.
2416 return replaceInstUsesWith(Cmp, Builder.getFalse());
2417 return new ICmpInst(Pred, X, ConstantInt::get(Div->getType(), LoBound));
2418 case ICmpInst::ICMP_UGT:
2419 case ICmpInst::ICMP_SGT:
2420 if (HiOverflow == +1) // High bound greater than input range.
2421 return replaceInstUsesWith(Cmp, Builder.getFalse());
2422 if (HiOverflow == -1) // High bound less than input range.
2423 return replaceInstUsesWith(Cmp, Builder.getTrue());
2424 if (Pred == ICmpInst::ICMP_UGT)
2425 return new ICmpInst(ICmpInst::ICMP_UGE, X,
2426 ConstantInt::get(Div->getType(), HiBound));
2427 return new ICmpInst(ICmpInst::ICMP_SGE, X,
2428 ConstantInt::get(Div->getType(), HiBound));
2431 return nullptr;
2434 /// Fold icmp (sub X, Y), C.
2435 Instruction *InstCombiner::foldICmpSubConstant(ICmpInst &Cmp,
2436 BinaryOperator *Sub,
2437 const APInt &C) {
2438 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
2439 ICmpInst::Predicate Pred = Cmp.getPredicate();
2440 const APInt *C2;
2441 APInt SubResult;
2443 // icmp eq/ne (sub C, Y), C -> icmp eq/ne Y, 0
2444 if (match(X, m_APInt(C2)) && *C2 == C && Cmp.isEquality())
2445 return new ICmpInst(Cmp.getPredicate(), Y,
2446 ConstantInt::get(Y->getType(), 0));
2448 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
2449 if (match(X, m_APInt(C2)) &&
2450 ((Cmp.isUnsigned() && Sub->hasNoUnsignedWrap()) ||
2451 (Cmp.isSigned() && Sub->hasNoSignedWrap())) &&
2452 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
2453 return new ICmpInst(Cmp.getSwappedPredicate(), Y,
2454 ConstantInt::get(Y->getType(), SubResult));
2456 // The following transforms are only worth it if the only user of the subtract
2457 // is the icmp.
2458 if (!Sub->hasOneUse())
2459 return nullptr;
2461 if (Sub->hasNoSignedWrap()) {
2462 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
2463 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnesValue())
2464 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
2466 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
2467 if (Pred == ICmpInst::ICMP_SGT && C.isNullValue())
2468 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
2470 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
2471 if (Pred == ICmpInst::ICMP_SLT && C.isNullValue())
2472 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
2474 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
2475 if (Pred == ICmpInst::ICMP_SLT && C.isOneValue())
2476 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
2479 if (!match(X, m_APInt(C2)))
2480 return nullptr;
2482 // C2 - Y <u C -> (Y | (C - 1)) == C2
2483 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
2484 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
2485 (*C2 & (C - 1)) == (C - 1))
2486 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
2488 // C2 - Y >u C -> (Y | C) != C2
2489 // iff C2 & C == C and C + 1 is a power of 2
2490 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
2491 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
2493 return nullptr;
2496 /// Fold icmp (add X, Y), C.
2497 Instruction *InstCombiner::foldICmpAddConstant(ICmpInst &Cmp,
2498 BinaryOperator *Add,
2499 const APInt &C) {
2500 Value *Y = Add->getOperand(1);
2501 const APInt *C2;
2502 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
2503 return nullptr;
2505 // Fold icmp pred (add X, C2), C.
2506 Value *X = Add->getOperand(0);
2507 Type *Ty = Add->getType();
2508 CmpInst::Predicate Pred = Cmp.getPredicate();
2510 if (!Add->hasOneUse())
2511 return nullptr;
2513 // If the add does not wrap, we can always adjust the compare by subtracting
2514 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
2515 // are canonicalized to SGT/SLT/UGT/ULT.
2516 if ((Add->hasNoSignedWrap() &&
2517 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) ||
2518 (Add->hasNoUnsignedWrap() &&
2519 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) {
2520 bool Overflow;
2521 APInt NewC =
2522 Cmp.isSigned() ? C.ssub_ov(*C2, Overflow) : C.usub_ov(*C2, Overflow);
2523 // If there is overflow, the result must be true or false.
2524 // TODO: Can we assert there is no overflow because InstSimplify always
2525 // handles those cases?
2526 if (!Overflow)
2527 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
2528 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
2531 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
2532 const APInt &Upper = CR.getUpper();
2533 const APInt &Lower = CR.getLower();
2534 if (Cmp.isSigned()) {
2535 if (Lower.isSignMask())
2536 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
2537 if (Upper.isSignMask())
2538 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
2539 } else {
2540 if (Lower.isMinValue())
2541 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
2542 if (Upper.isMinValue())
2543 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
2546 // X+C <u C2 -> (X & -C2) == C
2547 // iff C & (C2-1) == 0
2548 // C2 is a power of 2
2549 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
2550 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
2551 ConstantExpr::getNeg(cast<Constant>(Y)));
2553 // X+C >u C2 -> (X & ~C2) != C
2554 // iff C & C2 == 0
2555 // C2+1 is a power of 2
2556 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
2557 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
2558 ConstantExpr::getNeg(cast<Constant>(Y)));
2560 return nullptr;
2563 bool InstCombiner::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS,
2564 Value *&RHS, ConstantInt *&Less,
2565 ConstantInt *&Equal,
2566 ConstantInt *&Greater) {
2567 // TODO: Generalize this to work with other comparison idioms or ensure
2568 // they get canonicalized into this form.
2570 // select i1 (a == b),
2571 // i32 Equal,
2572 // i32 (select i1 (a < b), i32 Less, i32 Greater)
2573 // where Equal, Less and Greater are placeholders for any three constants.
2574 ICmpInst::Predicate PredA;
2575 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
2576 !ICmpInst::isEquality(PredA))
2577 return false;
2578 Value *EqualVal = SI->getTrueValue();
2579 Value *UnequalVal = SI->getFalseValue();
2580 // We still can get non-canonical predicate here, so canonicalize.
2581 if (PredA == ICmpInst::ICMP_NE)
2582 std::swap(EqualVal, UnequalVal);
2583 if (!match(EqualVal, m_ConstantInt(Equal)))
2584 return false;
2585 ICmpInst::Predicate PredB;
2586 Value *LHS2, *RHS2;
2587 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
2588 m_ConstantInt(Less), m_ConstantInt(Greater))))
2589 return false;
2590 // We can get predicate mismatch here, so canonicalize if possible:
2591 // First, ensure that 'LHS' match.
2592 if (LHS2 != LHS) {
2593 // x sgt y <--> y slt x
2594 std::swap(LHS2, RHS2);
2595 PredB = ICmpInst::getSwappedPredicate(PredB);
2597 if (LHS2 != LHS)
2598 return false;
2599 // We also need to canonicalize 'RHS'.
2600 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
2601 // x sgt C-1 <--> x sge C <--> not(x slt C)
2602 auto FlippedStrictness =
2603 getFlippedStrictnessPredicateAndConstant(PredB, cast<Constant>(RHS2));
2604 if (!FlippedStrictness)
2605 return false;
2606 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE && "Sanity check");
2607 RHS2 = FlippedStrictness->second;
2608 // And kind-of perform the result swap.
2609 std::swap(Less, Greater);
2610 PredB = ICmpInst::ICMP_SLT;
2612 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
2615 Instruction *InstCombiner::foldICmpSelectConstant(ICmpInst &Cmp,
2616 SelectInst *Select,
2617 ConstantInt *C) {
2619 assert(C && "Cmp RHS should be a constant int!");
2620 // If we're testing a constant value against the result of a three way
2621 // comparison, the result can be expressed directly in terms of the
2622 // original values being compared. Note: We could possibly be more
2623 // aggressive here and remove the hasOneUse test. The original select is
2624 // really likely to simplify or sink when we remove a test of the result.
2625 Value *OrigLHS, *OrigRHS;
2626 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
2627 if (Cmp.hasOneUse() &&
2628 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
2629 C3GreaterThan)) {
2630 assert(C1LessThan && C2Equal && C3GreaterThan);
2632 bool TrueWhenLessThan =
2633 ConstantExpr::getCompare(Cmp.getPredicate(), C1LessThan, C)
2634 ->isAllOnesValue();
2635 bool TrueWhenEqual =
2636 ConstantExpr::getCompare(Cmp.getPredicate(), C2Equal, C)
2637 ->isAllOnesValue();
2638 bool TrueWhenGreaterThan =
2639 ConstantExpr::getCompare(Cmp.getPredicate(), C3GreaterThan, C)
2640 ->isAllOnesValue();
2642 // This generates the new instruction that will replace the original Cmp
2643 // Instruction. Instead of enumerating the various combinations when
2644 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
2645 // false, we rely on chaining of ORs and future passes of InstCombine to
2646 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
2648 // When none of the three constants satisfy the predicate for the RHS (C),
2649 // the entire original Cmp can be simplified to a false.
2650 Value *Cond = Builder.getFalse();
2651 if (TrueWhenLessThan)
2652 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT,
2653 OrigLHS, OrigRHS));
2654 if (TrueWhenEqual)
2655 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ,
2656 OrigLHS, OrigRHS));
2657 if (TrueWhenGreaterThan)
2658 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT,
2659 OrigLHS, OrigRHS));
2661 return replaceInstUsesWith(Cmp, Cond);
2663 return nullptr;
2666 static Instruction *foldICmpBitCast(ICmpInst &Cmp,
2667 InstCombiner::BuilderTy &Builder) {
2668 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
2669 if (!Bitcast)
2670 return nullptr;
2672 ICmpInst::Predicate Pred = Cmp.getPredicate();
2673 Value *Op1 = Cmp.getOperand(1);
2674 Value *BCSrcOp = Bitcast->getOperand(0);
2676 // Make sure the bitcast doesn't change the number of vector elements.
2677 if (Bitcast->getSrcTy()->getScalarSizeInBits() ==
2678 Bitcast->getDestTy()->getScalarSizeInBits()) {
2679 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
2680 Value *X;
2681 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
2682 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
2683 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
2684 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
2685 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
2686 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
2687 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
2688 match(Op1, m_Zero()))
2689 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2691 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
2692 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
2693 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
2695 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
2696 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
2697 return new ICmpInst(Pred, X,
2698 ConstantInt::getAllOnesValue(X->getType()));
2701 // Zero-equality checks are preserved through unsigned floating-point casts:
2702 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
2703 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
2704 if (match(BCSrcOp, m_UIToFP(m_Value(X))))
2705 if (Cmp.isEquality() && match(Op1, m_Zero()))
2706 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2709 // Test to see if the operands of the icmp are casted versions of other
2710 // values. If the ptr->ptr cast can be stripped off both arguments, do so.
2711 if (Bitcast->getType()->isPointerTy() &&
2712 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
2713 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2714 // so eliminate it as well.
2715 if (auto *BC2 = dyn_cast<BitCastInst>(Op1))
2716 Op1 = BC2->getOperand(0);
2718 Op1 = Builder.CreateBitCast(Op1, BCSrcOp->getType());
2719 return new ICmpInst(Pred, BCSrcOp, Op1);
2722 // Folding: icmp <pred> iN X, C
2723 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
2724 // and C is a splat of a K-bit pattern
2725 // and SC is a constant vector = <C', C', C', ..., C'>
2726 // Into:
2727 // %E = extractelement <M x iK> %vec, i32 C'
2728 // icmp <pred> iK %E, trunc(C)
2729 const APInt *C;
2730 if (!match(Cmp.getOperand(1), m_APInt(C)) ||
2731 !Bitcast->getType()->isIntegerTy() ||
2732 !Bitcast->getSrcTy()->isIntOrIntVectorTy())
2733 return nullptr;
2735 Value *Vec;
2736 Constant *Mask;
2737 if (match(BCSrcOp,
2738 m_ShuffleVector(m_Value(Vec), m_Undef(), m_Constant(Mask)))) {
2739 // Check whether every element of Mask is the same constant
2740 if (auto *Elem = dyn_cast_or_null<ConstantInt>(Mask->getSplatValue())) {
2741 auto *VecTy = cast<VectorType>(BCSrcOp->getType());
2742 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
2743 if (C->isSplat(EltTy->getBitWidth())) {
2744 // Fold the icmp based on the value of C
2745 // If C is M copies of an iK sized bit pattern,
2746 // then:
2747 // => %E = extractelement <N x iK> %vec, i32 Elem
2748 // icmp <pred> iK %SplatVal, <pattern>
2749 Value *Extract = Builder.CreateExtractElement(Vec, Elem);
2750 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
2751 return new ICmpInst(Pred, Extract, NewC);
2755 return nullptr;
2758 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C
2759 /// where X is some kind of instruction.
2760 Instruction *InstCombiner::foldICmpInstWithConstant(ICmpInst &Cmp) {
2761 const APInt *C;
2762 if (!match(Cmp.getOperand(1), m_APInt(C)))
2763 return nullptr;
2765 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0))) {
2766 switch (BO->getOpcode()) {
2767 case Instruction::Xor:
2768 if (Instruction *I = foldICmpXorConstant(Cmp, BO, *C))
2769 return I;
2770 break;
2771 case Instruction::And:
2772 if (Instruction *I = foldICmpAndConstant(Cmp, BO, *C))
2773 return I;
2774 break;
2775 case Instruction::Or:
2776 if (Instruction *I = foldICmpOrConstant(Cmp, BO, *C))
2777 return I;
2778 break;
2779 case Instruction::Mul:
2780 if (Instruction *I = foldICmpMulConstant(Cmp, BO, *C))
2781 return I;
2782 break;
2783 case Instruction::Shl:
2784 if (Instruction *I = foldICmpShlConstant(Cmp, BO, *C))
2785 return I;
2786 break;
2787 case Instruction::LShr:
2788 case Instruction::AShr:
2789 if (Instruction *I = foldICmpShrConstant(Cmp, BO, *C))
2790 return I;
2791 break;
2792 case Instruction::UDiv:
2793 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, *C))
2794 return I;
2795 LLVM_FALLTHROUGH;
2796 case Instruction::SDiv:
2797 if (Instruction *I = foldICmpDivConstant(Cmp, BO, *C))
2798 return I;
2799 break;
2800 case Instruction::Sub:
2801 if (Instruction *I = foldICmpSubConstant(Cmp, BO, *C))
2802 return I;
2803 break;
2804 case Instruction::Add:
2805 if (Instruction *I = foldICmpAddConstant(Cmp, BO, *C))
2806 return I;
2807 break;
2808 default:
2809 break;
2811 // TODO: These folds could be refactored to be part of the above calls.
2812 if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, *C))
2813 return I;
2816 // Match against CmpInst LHS being instructions other than binary operators.
2818 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0))) {
2819 // For now, we only support constant integers while folding the
2820 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
2821 // similar to the cases handled by binary ops above.
2822 if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
2823 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
2824 return I;
2827 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0))) {
2828 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
2829 return I;
2832 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
2833 if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, II, *C))
2834 return I;
2836 return nullptr;
2839 /// Fold an icmp equality instruction with binary operator LHS and constant RHS:
2840 /// icmp eq/ne BO, C.
2841 Instruction *InstCombiner::foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
2842 BinaryOperator *BO,
2843 const APInt &C) {
2844 // TODO: Some of these folds could work with arbitrary constants, but this
2845 // function is limited to scalar and vector splat constants.
2846 if (!Cmp.isEquality())
2847 return nullptr;
2849 ICmpInst::Predicate Pred = Cmp.getPredicate();
2850 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
2851 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
2852 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
2854 switch (BO->getOpcode()) {
2855 case Instruction::SRem:
2856 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2857 if (C.isNullValue() && BO->hasOneUse()) {
2858 const APInt *BOC;
2859 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
2860 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
2861 return new ICmpInst(Pred, NewRem,
2862 Constant::getNullValue(BO->getType()));
2865 break;
2866 case Instruction::Add: {
2867 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2868 const APInt *BOC;
2869 if (match(BOp1, m_APInt(BOC))) {
2870 if (BO->hasOneUse()) {
2871 Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1));
2872 return new ICmpInst(Pred, BOp0, SubC);
2874 } else if (C.isNullValue()) {
2875 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2876 // efficiently invertible, or if the add has just this one use.
2877 if (Value *NegVal = dyn_castNegVal(BOp1))
2878 return new ICmpInst(Pred, BOp0, NegVal);
2879 if (Value *NegVal = dyn_castNegVal(BOp0))
2880 return new ICmpInst(Pred, NegVal, BOp1);
2881 if (BO->hasOneUse()) {
2882 Value *Neg = Builder.CreateNeg(BOp1);
2883 Neg->takeName(BO);
2884 return new ICmpInst(Pred, BOp0, Neg);
2887 break;
2889 case Instruction::Xor:
2890 if (BO->hasOneUse()) {
2891 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
2892 // For the xor case, we can xor two constants together, eliminating
2893 // the explicit xor.
2894 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
2895 } else if (C.isNullValue()) {
2896 // Replace ((xor A, B) != 0) with (A != B)
2897 return new ICmpInst(Pred, BOp0, BOp1);
2900 break;
2901 case Instruction::Sub:
2902 if (BO->hasOneUse()) {
2903 const APInt *BOC;
2904 if (match(BOp0, m_APInt(BOC))) {
2905 // Replace ((sub BOC, B) != C) with (B != BOC-C).
2906 Constant *SubC = ConstantExpr::getSub(cast<Constant>(BOp0), RHS);
2907 return new ICmpInst(Pred, BOp1, SubC);
2908 } else if (C.isNullValue()) {
2909 // Replace ((sub A, B) != 0) with (A != B).
2910 return new ICmpInst(Pred, BOp0, BOp1);
2913 break;
2914 case Instruction::Or: {
2915 const APInt *BOC;
2916 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
2917 // Comparing if all bits outside of a constant mask are set?
2918 // Replace (X | C) == -1 with (X & ~C) == ~C.
2919 // This removes the -1 constant.
2920 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
2921 Value *And = Builder.CreateAnd(BOp0, NotBOC);
2922 return new ICmpInst(Pred, And, NotBOC);
2924 break;
2926 case Instruction::And: {
2927 const APInt *BOC;
2928 if (match(BOp1, m_APInt(BOC))) {
2929 // If we have ((X & C) == C), turn it into ((X & C) != 0).
2930 if (C == *BOC && C.isPowerOf2())
2931 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
2932 BO, Constant::getNullValue(RHS->getType()));
2934 break;
2936 case Instruction::Mul:
2937 if (C.isNullValue() && BO->hasNoSignedWrap()) {
2938 const APInt *BOC;
2939 if (match(BOp1, m_APInt(BOC)) && !BOC->isNullValue()) {
2940 // The trivial case (mul X, 0) is handled by InstSimplify.
2941 // General case : (mul X, C) != 0 iff X != 0
2942 // (mul X, C) == 0 iff X == 0
2943 return new ICmpInst(Pred, BOp0, Constant::getNullValue(RHS->getType()));
2946 break;
2947 case Instruction::UDiv:
2948 if (C.isNullValue()) {
2949 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
2950 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
2951 return new ICmpInst(NewPred, BOp1, BOp0);
2953 break;
2954 default:
2955 break;
2957 return nullptr;
2960 /// Fold an equality icmp with LLVM intrinsic and constant operand.
2961 Instruction *InstCombiner::foldICmpEqIntrinsicWithConstant(ICmpInst &Cmp,
2962 IntrinsicInst *II,
2963 const APInt &C) {
2964 Type *Ty = II->getType();
2965 unsigned BitWidth = C.getBitWidth();
2966 switch (II->getIntrinsicID()) {
2967 case Intrinsic::bswap:
2968 Worklist.Add(II);
2969 Cmp.setOperand(0, II->getArgOperand(0));
2970 Cmp.setOperand(1, ConstantInt::get(Ty, C.byteSwap()));
2971 return &Cmp;
2973 case Intrinsic::ctlz:
2974 case Intrinsic::cttz: {
2975 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
2976 if (C == BitWidth) {
2977 Worklist.Add(II);
2978 Cmp.setOperand(0, II->getArgOperand(0));
2979 Cmp.setOperand(1, ConstantInt::getNullValue(Ty));
2980 return &Cmp;
2983 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
2984 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
2985 // Limit to one use to ensure we don't increase instruction count.
2986 unsigned Num = C.getLimitedValue(BitWidth);
2987 if (Num != BitWidth && II->hasOneUse()) {
2988 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
2989 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
2990 : APInt::getHighBitsSet(BitWidth, Num + 1);
2991 APInt Mask2 = IsTrailing
2992 ? APInt::getOneBitSet(BitWidth, Num)
2993 : APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
2994 Cmp.setOperand(0, Builder.CreateAnd(II->getArgOperand(0), Mask1));
2995 Cmp.setOperand(1, ConstantInt::get(Ty, Mask2));
2996 Worklist.Add(II);
2997 return &Cmp;
2999 break;
3002 case Intrinsic::ctpop: {
3003 // popcount(A) == 0 -> A == 0 and likewise for !=
3004 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3005 bool IsZero = C.isNullValue();
3006 if (IsZero || C == BitWidth) {
3007 Worklist.Add(II);
3008 Cmp.setOperand(0, II->getArgOperand(0));
3009 auto *NewOp =
3010 IsZero ? Constant::getNullValue(Ty) : Constant::getAllOnesValue(Ty);
3011 Cmp.setOperand(1, NewOp);
3012 return &Cmp;
3014 break;
3016 default:
3017 break;
3020 return nullptr;
3023 /// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
3024 Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
3025 IntrinsicInst *II,
3026 const APInt &C) {
3027 if (Cmp.isEquality())
3028 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
3030 Type *Ty = II->getType();
3031 unsigned BitWidth = C.getBitWidth();
3032 switch (II->getIntrinsicID()) {
3033 case Intrinsic::ctlz: {
3034 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
3035 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3036 unsigned Num = C.getLimitedValue();
3037 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
3038 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
3039 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3042 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
3043 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT &&
3044 C.uge(1) && C.ule(BitWidth)) {
3045 unsigned Num = C.getLimitedValue();
3046 APInt Limit = APInt::getLowBitsSet(BitWidth, BitWidth - Num);
3047 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
3048 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3050 break;
3052 case Intrinsic::cttz: {
3053 // Limit to one use to ensure we don't increase instruction count.
3054 if (!II->hasOneUse())
3055 return nullptr;
3057 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
3058 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3059 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
3060 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
3061 Builder.CreateAnd(II->getArgOperand(0), Mask),
3062 ConstantInt::getNullValue(Ty));
3065 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
3066 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT &&
3067 C.uge(1) && C.ule(BitWidth)) {
3068 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
3069 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
3070 Builder.CreateAnd(II->getArgOperand(0), Mask),
3071 ConstantInt::getNullValue(Ty));
3073 break;
3075 default:
3076 break;
3079 return nullptr;
3082 /// Handle icmp with constant (but not simple integer constant) RHS.
3083 Instruction *InstCombiner::foldICmpInstWithConstantNotInt(ICmpInst &I) {
3084 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3085 Constant *RHSC = dyn_cast<Constant>(Op1);
3086 Instruction *LHSI = dyn_cast<Instruction>(Op0);
3087 if (!RHSC || !LHSI)
3088 return nullptr;
3090 switch (LHSI->getOpcode()) {
3091 case Instruction::GetElementPtr:
3092 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3093 if (RHSC->isNullValue() &&
3094 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3095 return new ICmpInst(
3096 I.getPredicate(), LHSI->getOperand(0),
3097 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3098 break;
3099 case Instruction::PHI:
3100 // Only fold icmp into the PHI if the phi and icmp are in the same
3101 // block. If in the same block, we're encouraging jump threading. If
3102 // not, we are just pessimizing the code by making an i1 phi.
3103 if (LHSI->getParent() == I.getParent())
3104 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
3105 return NV;
3106 break;
3107 case Instruction::Select: {
3108 // If either operand of the select is a constant, we can fold the
3109 // comparison into the select arms, which will cause one to be
3110 // constant folded and the select turned into a bitwise or.
3111 Value *Op1 = nullptr, *Op2 = nullptr;
3112 ConstantInt *CI = nullptr;
3113 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3114 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
3115 CI = dyn_cast<ConstantInt>(Op1);
3117 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3118 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
3119 CI = dyn_cast<ConstantInt>(Op2);
3122 // We only want to perform this transformation if it will not lead to
3123 // additional code. This is true if either both sides of the select
3124 // fold to a constant (in which case the icmp is replaced with a select
3125 // which will usually simplify) or this is the only user of the
3126 // select (in which case we are trading a select+icmp for a simpler
3127 // select+icmp) or all uses of the select can be replaced based on
3128 // dominance information ("Global cases").
3129 bool Transform = false;
3130 if (Op1 && Op2)
3131 Transform = true;
3132 else if (Op1 || Op2) {
3133 // Local case
3134 if (LHSI->hasOneUse())
3135 Transform = true;
3136 // Global cases
3137 else if (CI && !CI->isZero())
3138 // When Op1 is constant try replacing select with second operand.
3139 // Otherwise Op2 is constant and try replacing select with first
3140 // operand.
3141 Transform =
3142 replacedSelectWithOperand(cast<SelectInst>(LHSI), &I, Op1 ? 2 : 1);
3144 if (Transform) {
3145 if (!Op1)
3146 Op1 = Builder.CreateICmp(I.getPredicate(), LHSI->getOperand(1), RHSC,
3147 I.getName());
3148 if (!Op2)
3149 Op2 = Builder.CreateICmp(I.getPredicate(), LHSI->getOperand(2), RHSC,
3150 I.getName());
3151 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3153 break;
3155 case Instruction::IntToPtr:
3156 // icmp pred inttoptr(X), null -> icmp pred X, 0
3157 if (RHSC->isNullValue() &&
3158 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
3159 return new ICmpInst(
3160 I.getPredicate(), LHSI->getOperand(0),
3161 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3162 break;
3164 case Instruction::Load:
3165 // Try to optimize things like "A[i] > 4" to index computations.
3166 if (GetElementPtrInst *GEP =
3167 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3168 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3169 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3170 !cast<LoadInst>(LHSI)->isVolatile())
3171 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
3172 return Res;
3174 break;
3177 return nullptr;
3180 /// Some comparisons can be simplified.
3181 /// In this case, we are looking for comparisons that look like
3182 /// a check for a lossy truncation.
3183 /// Folds:
3184 /// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
3185 /// Where Mask is some pattern that produces all-ones in low bits:
3186 /// (-1 >> y)
3187 /// ((-1 << y) >> y) <- non-canonical, has extra uses
3188 /// ~(-1 << y)
3189 /// ((1 << y) + (-1)) <- non-canonical, has extra uses
3190 /// The Mask can be a constant, too.
3191 /// For some predicates, the operands are commutative.
3192 /// For others, x can only be on a specific side.
3193 static Value *foldICmpWithLowBitMaskedVal(ICmpInst &I,
3194 InstCombiner::BuilderTy &Builder) {
3195 ICmpInst::Predicate SrcPred;
3196 Value *X, *M, *Y;
3197 auto m_VariableMask = m_CombineOr(
3198 m_CombineOr(m_Not(m_Shl(m_AllOnes(), m_Value())),
3199 m_Add(m_Shl(m_One(), m_Value()), m_AllOnes())),
3200 m_CombineOr(m_LShr(m_AllOnes(), m_Value()),
3201 m_LShr(m_Shl(m_AllOnes(), m_Value(Y)), m_Deferred(Y))));
3202 auto m_Mask = m_CombineOr(m_VariableMask, m_LowBitMask());
3203 if (!match(&I, m_c_ICmp(SrcPred,
3204 m_c_And(m_CombineAnd(m_Mask, m_Value(M)), m_Value(X)),
3205 m_Deferred(X))))
3206 return nullptr;
3208 ICmpInst::Predicate DstPred;
3209 switch (SrcPred) {
3210 case ICmpInst::Predicate::ICMP_EQ:
3211 // x & (-1 >> y) == x -> x u<= (-1 >> y)
3212 DstPred = ICmpInst::Predicate::ICMP_ULE;
3213 break;
3214 case ICmpInst::Predicate::ICMP_NE:
3215 // x & (-1 >> y) != x -> x u> (-1 >> y)
3216 DstPred = ICmpInst::Predicate::ICMP_UGT;
3217 break;
3218 case ICmpInst::Predicate::ICMP_UGT:
3219 // x u> x & (-1 >> y) -> x u> (-1 >> y)
3220 assert(X == I.getOperand(0) && "instsimplify took care of commut. variant");
3221 DstPred = ICmpInst::Predicate::ICMP_UGT;
3222 break;
3223 case ICmpInst::Predicate::ICMP_UGE:
3224 // x & (-1 >> y) u>= x -> x u<= (-1 >> y)
3225 assert(X == I.getOperand(1) && "instsimplify took care of commut. variant");
3226 DstPred = ICmpInst::Predicate::ICMP_ULE;
3227 break;
3228 case ICmpInst::Predicate::ICMP_ULT:
3229 // x & (-1 >> y) u< x -> x u> (-1 >> y)
3230 assert(X == I.getOperand(1) && "instsimplify took care of commut. variant");
3231 DstPred = ICmpInst::Predicate::ICMP_UGT;
3232 break;
3233 case ICmpInst::Predicate::ICMP_ULE:
3234 // x u<= x & (-1 >> y) -> x u<= (-1 >> y)
3235 assert(X == I.getOperand(0) && "instsimplify took care of commut. variant");
3236 DstPred = ICmpInst::Predicate::ICMP_ULE;
3237 break;
3238 case ICmpInst::Predicate::ICMP_SGT:
3239 // x s> x & (-1 >> y) -> x s> (-1 >> y)
3240 if (X != I.getOperand(0)) // X must be on LHS of comparison!
3241 return nullptr; // Ignore the other case.
3242 if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3243 return nullptr;
3244 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3245 return nullptr;
3246 DstPred = ICmpInst::Predicate::ICMP_SGT;
3247 break;
3248 case ICmpInst::Predicate::ICMP_SGE:
3249 // x & (-1 >> y) s>= x -> x s<= (-1 >> y)
3250 if (X != I.getOperand(1)) // X must be on RHS of comparison!
3251 return nullptr; // Ignore the other case.
3252 if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3253 return nullptr;
3254 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3255 return nullptr;
3256 DstPred = ICmpInst::Predicate::ICMP_SLE;
3257 break;
3258 case ICmpInst::Predicate::ICMP_SLT:
3259 // x & (-1 >> y) s< x -> x s> (-1 >> y)
3260 if (X != I.getOperand(1)) // X must be on RHS of comparison!
3261 return nullptr; // Ignore the other case.
3262 if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3263 return nullptr;
3264 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3265 return nullptr;
3266 DstPred = ICmpInst::Predicate::ICMP_SGT;
3267 break;
3268 case ICmpInst::Predicate::ICMP_SLE:
3269 // x s<= x & (-1 >> y) -> x s<= (-1 >> y)
3270 if (X != I.getOperand(0)) // X must be on LHS of comparison!
3271 return nullptr; // Ignore the other case.
3272 if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3273 return nullptr;
3274 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3275 return nullptr;
3276 DstPred = ICmpInst::Predicate::ICMP_SLE;
3277 break;
3278 default:
3279 llvm_unreachable("All possible folds are handled.");
3282 return Builder.CreateICmp(DstPred, X, M);
3285 /// Some comparisons can be simplified.
3286 /// In this case, we are looking for comparisons that look like
3287 /// a check for a lossy signed truncation.
3288 /// Folds: (MaskedBits is a constant.)
3289 /// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
3290 /// Into:
3291 /// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
3292 /// Where KeptBits = bitwidth(%x) - MaskedBits
3293 static Value *
3294 foldICmpWithTruncSignExtendedVal(ICmpInst &I,
3295 InstCombiner::BuilderTy &Builder) {
3296 ICmpInst::Predicate SrcPred;
3297 Value *X;
3298 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
3299 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
3300 if (!match(&I, m_c_ICmp(SrcPred,
3301 m_OneUse(m_AShr(m_Shl(m_Value(X), m_APInt(C0)),
3302 m_APInt(C1))),
3303 m_Deferred(X))))
3304 return nullptr;
3306 // Potential handling of non-splats: for each element:
3307 // * if both are undef, replace with constant 0.
3308 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
3309 // * if both are not undef, and are different, bailout.
3310 // * else, only one is undef, then pick the non-undef one.
3312 // The shift amount must be equal.
3313 if (*C0 != *C1)
3314 return nullptr;
3315 const APInt &MaskedBits = *C0;
3316 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
3318 ICmpInst::Predicate DstPred;
3319 switch (SrcPred) {
3320 case ICmpInst::Predicate::ICMP_EQ:
3321 // ((%x << MaskedBits) a>> MaskedBits) == %x
3322 // =>
3323 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
3324 DstPred = ICmpInst::Predicate::ICMP_ULT;
3325 break;
3326 case ICmpInst::Predicate::ICMP_NE:
3327 // ((%x << MaskedBits) a>> MaskedBits) != %x
3328 // =>
3329 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
3330 DstPred = ICmpInst::Predicate::ICMP_UGE;
3331 break;
3332 // FIXME: are more folds possible?
3333 default:
3334 return nullptr;
3337 auto *XType = X->getType();
3338 const unsigned XBitWidth = XType->getScalarSizeInBits();
3339 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
3340 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
3342 // KeptBits = bitwidth(%x) - MaskedBits
3343 const APInt KeptBits = BitWidth - MaskedBits;
3344 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
3345 // ICmpCst = (1 << KeptBits)
3346 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
3347 assert(ICmpCst.isPowerOf2());
3348 // AddCst = (1 << (KeptBits-1))
3349 const APInt AddCst = ICmpCst.lshr(1);
3350 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
3352 // T0 = add %x, AddCst
3353 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
3354 // T1 = T0 DstPred ICmpCst
3355 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
3357 return T1;
3360 // Given pattern:
3361 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
3362 // we should move shifts to the same hand of 'and', i.e. rewrite as
3363 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
3364 // We are only interested in opposite logical shifts here.
3365 // One of the shifts can be truncated. For now, it can only be 'shl'.
3366 // If we can, we want to end up creating 'lshr' shift.
3367 static Value *
3368 foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ,
3369 InstCombiner::BuilderTy &Builder) {
3370 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
3371 !I.getOperand(0)->hasOneUse())
3372 return nullptr;
3374 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
3376 // Look for an 'and' of two logical shifts, one of which may be truncated.
3377 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
3378 Instruction *XShift, *MaybeTruncation, *YShift;
3379 if (!match(
3380 I.getOperand(0),
3381 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
3382 m_CombineAnd(m_TruncOrSelf(m_CombineAnd(
3383 m_AnyLogicalShift, m_Instruction(YShift))),
3384 m_Instruction(MaybeTruncation)))))
3385 return nullptr;
3387 // We potentially looked past 'trunc', but only when matching YShift,
3388 // therefore YShift must have the widest type.
3389 Instruction *WidestShift = YShift;
3390 // Therefore XShift must have the shallowest type.
3391 // Or they both have identical types if there was no truncation.
3392 Instruction *NarrowestShift = XShift;
3394 Type *WidestTy = WidestShift->getType();
3395 assert(NarrowestShift->getType() == I.getOperand(0)->getType() &&
3396 "We did not look past any shifts while matching XShift though.");
3397 bool HadTrunc = WidestTy != I.getOperand(0)->getType();
3399 if (HadTrunc) {
3400 // We did indeed have a truncation. For now, let's only proceed if the 'shl'
3401 // was truncated, since that does not require any extra legality checks.
3402 // FIXME: trunc-of-lshr.
3403 if (!match(YShift, m_Shl(m_Value(), m_Value())))
3404 return nullptr;
3407 // If YShift is a 'lshr', swap the shifts around.
3408 if (match(YShift, m_LShr(m_Value(), m_Value())))
3409 std::swap(XShift, YShift);
3411 // The shifts must be in opposite directions.
3412 auto XShiftOpcode = XShift->getOpcode();
3413 if (XShiftOpcode == YShift->getOpcode())
3414 return nullptr; // Do not care about same-direction shifts here.
3416 Value *X, *XShAmt, *Y, *YShAmt;
3417 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
3418 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
3420 // If one of the values being shifted is a constant, then we will end with
3421 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
3422 // however, we will need to ensure that we won't increase instruction count.
3423 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
3424 // At least one of the hands of the 'and' should be one-use shift.
3425 if (!match(I.getOperand(0),
3426 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
3427 return nullptr;
3428 if (HadTrunc) {
3429 // Due to the 'trunc', we will need to widen X. For that either the old
3430 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
3431 if (!MaybeTruncation->hasOneUse() &&
3432 !NarrowestShift->getOperand(1)->hasOneUse())
3433 return nullptr;
3437 // We have two shift amounts from two different shifts. The types of those
3438 // shift amounts may not match. If that's the case let's bailout now.
3439 if (XShAmt->getType() != YShAmt->getType())
3440 return nullptr;
3442 // Can we fold (XShAmt+YShAmt) ?
3443 auto *NewShAmt = dyn_cast_or_null<Constant>(
3444 SimplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
3445 /*isNUW=*/false, SQ.getWithInstruction(&I)));
3446 if (!NewShAmt)
3447 return nullptr;
3448 // Is the new shift amount smaller than the bit width?
3449 // FIXME: could also rely on ConstantRange.
3450 if (!match(NewShAmt, m_SpecificInt_ICMP(
3451 ICmpInst::Predicate::ICMP_ULT,
3452 APInt(NewShAmt->getType()->getScalarSizeInBits(),
3453 WidestTy->getScalarSizeInBits()))))
3454 return nullptr;
3455 // All good, we can do this fold.
3456 NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, WidestTy);
3457 X = Builder.CreateZExt(X, WidestTy);
3458 // The shift is the same that was for X.
3459 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
3460 ? Builder.CreateLShr(X, NewShAmt)
3461 : Builder.CreateShl(X, NewShAmt);
3462 Value *T1 = Builder.CreateAnd(T0, Y);
3463 return Builder.CreateICmp(I.getPredicate(), T1,
3464 Constant::getNullValue(WidestTy));
3467 /// Try to fold icmp (binop), X or icmp X, (binop).
3468 /// TODO: A large part of this logic is duplicated in InstSimplify's
3469 /// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
3470 /// duplication.
3471 Instruction *InstCombiner::foldICmpBinOp(ICmpInst &I) {
3472 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3474 // Special logic for binary operators.
3475 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3476 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3477 if (!BO0 && !BO1)
3478 return nullptr;
3480 const CmpInst::Predicate Pred = I.getPredicate();
3481 Value *X;
3483 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
3484 // (Op1 + X) <u Op1 --> ~Op1 <u X
3485 // Op0 >u (Op0 + X) --> X >u ~Op0
3486 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
3487 Pred == ICmpInst::ICMP_ULT)
3488 return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
3489 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
3490 Pred == ICmpInst::ICMP_UGT)
3491 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
3493 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3494 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3495 NoOp0WrapProblem =
3496 ICmpInst::isEquality(Pred) ||
3497 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3498 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3499 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3500 NoOp1WrapProblem =
3501 ICmpInst::isEquality(Pred) ||
3502 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3503 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3505 // Analyze the case when either Op0 or Op1 is an add instruction.
3506 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
3507 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
3508 if (BO0 && BO0->getOpcode() == Instruction::Add) {
3509 A = BO0->getOperand(0);
3510 B = BO0->getOperand(1);
3512 if (BO1 && BO1->getOpcode() == Instruction::Add) {
3513 C = BO1->getOperand(0);
3514 D = BO1->getOperand(1);
3517 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3518 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3519 return new ICmpInst(Pred, A == Op1 ? B : A,
3520 Constant::getNullValue(Op1->getType()));
3522 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3523 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3524 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3525 C == Op0 ? D : C);
3527 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
3528 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
3529 NoOp1WrapProblem &&
3530 // Try not to increase register pressure.
3531 BO0->hasOneUse() && BO1->hasOneUse()) {
3532 // Determine Y and Z in the form icmp (X+Y), (X+Z).
3533 Value *Y, *Z;
3534 if (A == C) {
3535 // C + B == C + D -> B == D
3536 Y = B;
3537 Z = D;
3538 } else if (A == D) {
3539 // D + B == C + D -> B == C
3540 Y = B;
3541 Z = C;
3542 } else if (B == C) {
3543 // A + C == C + D -> A == D
3544 Y = A;
3545 Z = D;
3546 } else {
3547 assert(B == D);
3548 // A + D == C + D -> A == C
3549 Y = A;
3550 Z = C;
3552 return new ICmpInst(Pred, Y, Z);
3555 // icmp slt (X + -1), Y -> icmp sle X, Y
3556 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3557 match(B, m_AllOnes()))
3558 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3560 // icmp sge (X + -1), Y -> icmp sgt X, Y
3561 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3562 match(B, m_AllOnes()))
3563 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3565 // icmp sle (X + 1), Y -> icmp slt X, Y
3566 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One()))
3567 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3569 // icmp sgt (X + 1), Y -> icmp sge X, Y
3570 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One()))
3571 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3573 // icmp sgt X, (Y + -1) -> icmp sge X, Y
3574 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3575 match(D, m_AllOnes()))
3576 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3578 // icmp sle X, (Y + -1) -> icmp slt X, Y
3579 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3580 match(D, m_AllOnes()))
3581 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3583 // icmp sge X, (Y + 1) -> icmp sgt X, Y
3584 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One()))
3585 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3587 // icmp slt X, (Y + 1) -> icmp sle X, Y
3588 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One()))
3589 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3591 // TODO: The subtraction-related identities shown below also hold, but
3592 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
3593 // wouldn't happen even if they were implemented.
3595 // icmp ult (X - 1), Y -> icmp ule X, Y
3596 // icmp uge (X - 1), Y -> icmp ugt X, Y
3597 // icmp ugt X, (Y - 1) -> icmp uge X, Y
3598 // icmp ule X, (Y - 1) -> icmp ult X, Y
3600 // icmp ule (X + 1), Y -> icmp ult X, Y
3601 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One()))
3602 return new ICmpInst(CmpInst::ICMP_ULT, A, Op1);
3604 // icmp ugt (X + 1), Y -> icmp uge X, Y
3605 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One()))
3606 return new ICmpInst(CmpInst::ICMP_UGE, A, Op1);
3608 // icmp uge X, (Y + 1) -> icmp ugt X, Y
3609 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One()))
3610 return new ICmpInst(CmpInst::ICMP_UGT, Op0, C);
3612 // icmp ult X, (Y + 1) -> icmp ule X, Y
3613 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One()))
3614 return new ICmpInst(CmpInst::ICMP_ULE, Op0, C);
3616 // if C1 has greater magnitude than C2:
3617 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3618 // s.t. C3 = C1 - C2
3620 // if C2 has greater magnitude than C1:
3621 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3622 // s.t. C3 = C2 - C1
3623 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3624 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3625 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3626 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3627 const APInt &AP1 = C1->getValue();
3628 const APInt &AP2 = C2->getValue();
3629 if (AP1.isNegative() == AP2.isNegative()) {
3630 APInt AP1Abs = C1->getValue().abs();
3631 APInt AP2Abs = C2->getValue().abs();
3632 if (AP1Abs.uge(AP2Abs)) {
3633 ConstantInt *C3 = Builder.getInt(AP1 - AP2);
3634 Value *NewAdd = Builder.CreateNSWAdd(A, C3);
3635 return new ICmpInst(Pred, NewAdd, C);
3636 } else {
3637 ConstantInt *C3 = Builder.getInt(AP2 - AP1);
3638 Value *NewAdd = Builder.CreateNSWAdd(C, C3);
3639 return new ICmpInst(Pred, A, NewAdd);
3644 // Analyze the case when either Op0 or Op1 is a sub instruction.
3645 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
3646 A = nullptr;
3647 B = nullptr;
3648 C = nullptr;
3649 D = nullptr;
3650 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
3651 A = BO0->getOperand(0);
3652 B = BO0->getOperand(1);
3654 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3655 C = BO1->getOperand(0);
3656 D = BO1->getOperand(1);
3659 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3660 if (A == Op1 && NoOp0WrapProblem)
3661 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3662 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
3663 if (C == Op0 && NoOp1WrapProblem)
3664 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3666 // (A - B) >u A --> A <u B
3667 if (A == Op1 && Pred == ICmpInst::ICMP_UGT)
3668 return new ICmpInst(ICmpInst::ICMP_ULT, A, B);
3669 // C <u (C - D) --> C <u D
3670 if (C == Op0 && Pred == ICmpInst::ICMP_ULT)
3671 return new ICmpInst(ICmpInst::ICMP_ULT, C, D);
3673 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
3674 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
3675 // Try not to increase register pressure.
3676 BO0->hasOneUse() && BO1->hasOneUse())
3677 return new ICmpInst(Pred, A, C);
3678 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
3679 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3680 // Try not to increase register pressure.
3681 BO0->hasOneUse() && BO1->hasOneUse())
3682 return new ICmpInst(Pred, D, B);
3684 // icmp (0-X) < cst --> x > -cst
3685 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3686 Value *X;
3687 if (match(BO0, m_Neg(m_Value(X))))
3688 if (Constant *RHSC = dyn_cast<Constant>(Op1))
3689 if (RHSC->isNotMinSignedValue())
3690 return new ICmpInst(I.getSwappedPredicate(), X,
3691 ConstantExpr::getNeg(RHSC));
3694 BinaryOperator *SRem = nullptr;
3695 // icmp (srem X, Y), Y
3696 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
3697 SRem = BO0;
3698 // icmp Y, (srem X, Y)
3699 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3700 Op0 == BO1->getOperand(1))
3701 SRem = BO1;
3702 if (SRem) {
3703 // We don't check hasOneUse to avoid increasing register pressure because
3704 // the value we use is the same value this instruction was already using.
3705 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
3706 default:
3707 break;
3708 case ICmpInst::ICMP_EQ:
3709 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3710 case ICmpInst::ICMP_NE:
3711 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3712 case ICmpInst::ICMP_SGT:
3713 case ICmpInst::ICMP_SGE:
3714 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
3715 Constant::getAllOnesValue(SRem->getType()));
3716 case ICmpInst::ICMP_SLT:
3717 case ICmpInst::ICMP_SLE:
3718 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
3719 Constant::getNullValue(SRem->getType()));
3723 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() &&
3724 BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) {
3725 switch (BO0->getOpcode()) {
3726 default:
3727 break;
3728 case Instruction::Add:
3729 case Instruction::Sub:
3730 case Instruction::Xor: {
3731 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
3732 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3734 const APInt *C;
3735 if (match(BO0->getOperand(1), m_APInt(C))) {
3736 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
3737 if (C->isSignMask()) {
3738 ICmpInst::Predicate NewPred =
3739 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate();
3740 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
3743 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
3744 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
3745 ICmpInst::Predicate NewPred =
3746 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate();
3747 NewPred = I.getSwappedPredicate(NewPred);
3748 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
3751 break;
3753 case Instruction::Mul: {
3754 if (!I.isEquality())
3755 break;
3757 const APInt *C;
3758 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isNullValue() &&
3759 !C->isOneValue()) {
3760 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
3761 // Mask = -1 >> count-trailing-zeros(C).
3762 if (unsigned TZs = C->countTrailingZeros()) {
3763 Constant *Mask = ConstantInt::get(
3764 BO0->getType(),
3765 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
3766 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
3767 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
3768 return new ICmpInst(Pred, And1, And2);
3770 // If there are no trailing zeros in the multiplier, just eliminate
3771 // the multiplies (no masking is needed):
3772 // icmp eq/ne (X * C), (Y * C) --> icmp eq/ne X, Y
3773 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3775 break;
3777 case Instruction::UDiv:
3778 case Instruction::LShr:
3779 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
3780 break;
3781 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3783 case Instruction::SDiv:
3784 if (!I.isEquality() || !BO0->isExact() || !BO1->isExact())
3785 break;
3786 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3788 case Instruction::AShr:
3789 if (!BO0->isExact() || !BO1->isExact())
3790 break;
3791 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3793 case Instruction::Shl: {
3794 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
3795 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
3796 if (!NUW && !NSW)
3797 break;
3798 if (!NSW && I.isSigned())
3799 break;
3800 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3805 if (BO0) {
3806 // Transform A & (L - 1) `ult` L --> L != 0
3807 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
3808 auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
3810 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
3811 auto *Zero = Constant::getNullValue(BO0->getType());
3812 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
3816 if (Value *V = foldICmpWithLowBitMaskedVal(I, Builder))
3817 return replaceInstUsesWith(I, V);
3819 if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder))
3820 return replaceInstUsesWith(I, V);
3822 if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder))
3823 return replaceInstUsesWith(I, V);
3825 return nullptr;
3828 /// Fold icmp Pred min|max(X, Y), X.
3829 static Instruction *foldICmpWithMinMax(ICmpInst &Cmp) {
3830 ICmpInst::Predicate Pred = Cmp.getPredicate();
3831 Value *Op0 = Cmp.getOperand(0);
3832 Value *X = Cmp.getOperand(1);
3834 // Canonicalize minimum or maximum operand to LHS of the icmp.
3835 if (match(X, m_c_SMin(m_Specific(Op0), m_Value())) ||
3836 match(X, m_c_SMax(m_Specific(Op0), m_Value())) ||
3837 match(X, m_c_UMin(m_Specific(Op0), m_Value())) ||
3838 match(X, m_c_UMax(m_Specific(Op0), m_Value()))) {
3839 std::swap(Op0, X);
3840 Pred = Cmp.getSwappedPredicate();
3843 Value *Y;
3844 if (match(Op0, m_c_SMin(m_Specific(X), m_Value(Y)))) {
3845 // smin(X, Y) == X --> X s<= Y
3846 // smin(X, Y) s>= X --> X s<= Y
3847 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SGE)
3848 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3850 // smin(X, Y) != X --> X s> Y
3851 // smin(X, Y) s< X --> X s> Y
3852 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SLT)
3853 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3855 // These cases should be handled in InstSimplify:
3856 // smin(X, Y) s<= X --> true
3857 // smin(X, Y) s> X --> false
3858 return nullptr;
3861 if (match(Op0, m_c_SMax(m_Specific(X), m_Value(Y)))) {
3862 // smax(X, Y) == X --> X s>= Y
3863 // smax(X, Y) s<= X --> X s>= Y
3864 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SLE)
3865 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3867 // smax(X, Y) != X --> X s< Y
3868 // smax(X, Y) s> X --> X s< Y
3869 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SGT)
3870 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3872 // These cases should be handled in InstSimplify:
3873 // smax(X, Y) s>= X --> true
3874 // smax(X, Y) s< X --> false
3875 return nullptr;
3878 if (match(Op0, m_c_UMin(m_Specific(X), m_Value(Y)))) {
3879 // umin(X, Y) == X --> X u<= Y
3880 // umin(X, Y) u>= X --> X u<= Y
3881 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_UGE)
3882 return new ICmpInst(ICmpInst::ICMP_ULE, X, Y);
3884 // umin(X, Y) != X --> X u> Y
3885 // umin(X, Y) u< X --> X u> Y
3886 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT)
3887 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
3889 // These cases should be handled in InstSimplify:
3890 // umin(X, Y) u<= X --> true
3891 // umin(X, Y) u> X --> false
3892 return nullptr;
3895 if (match(Op0, m_c_UMax(m_Specific(X), m_Value(Y)))) {
3896 // umax(X, Y) == X --> X u>= Y
3897 // umax(X, Y) u<= X --> X u>= Y
3898 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_ULE)
3899 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y);
3901 // umax(X, Y) != X --> X u< Y
3902 // umax(X, Y) u> X --> X u< Y
3903 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_UGT)
3904 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
3906 // These cases should be handled in InstSimplify:
3907 // umax(X, Y) u>= X --> true
3908 // umax(X, Y) u< X --> false
3909 return nullptr;
3912 return nullptr;
3915 Instruction *InstCombiner::foldICmpEquality(ICmpInst &I) {
3916 if (!I.isEquality())
3917 return nullptr;
3919 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3920 const CmpInst::Predicate Pred = I.getPredicate();
3921 Value *A, *B, *C, *D;
3922 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3923 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
3924 Value *OtherVal = A == Op1 ? B : A;
3925 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
3928 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
3929 // A^c1 == C^c2 --> A == C^(c1^c2)
3930 ConstantInt *C1, *C2;
3931 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
3932 Op1->hasOneUse()) {
3933 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
3934 Value *Xor = Builder.CreateXor(C, NC);
3935 return new ICmpInst(Pred, A, Xor);
3938 // A^B == A^D -> B == D
3939 if (A == C)
3940 return new ICmpInst(Pred, B, D);
3941 if (A == D)
3942 return new ICmpInst(Pred, B, C);
3943 if (B == C)
3944 return new ICmpInst(Pred, A, D);
3945 if (B == D)
3946 return new ICmpInst(Pred, A, C);
3950 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
3951 // A == (A^B) -> B == 0
3952 Value *OtherVal = A == Op0 ? B : A;
3953 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
3956 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
3957 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
3958 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
3959 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
3961 if (A == C) {
3962 X = B;
3963 Y = D;
3964 Z = A;
3965 } else if (A == D) {
3966 X = B;
3967 Y = C;
3968 Z = A;
3969 } else if (B == C) {
3970 X = A;
3971 Y = D;
3972 Z = B;
3973 } else if (B == D) {
3974 X = A;
3975 Y = C;
3976 Z = B;
3979 if (X) { // Build (X^Y) & Z
3980 Op1 = Builder.CreateXor(X, Y);
3981 Op1 = Builder.CreateAnd(Op1, Z);
3982 I.setOperand(0, Op1);
3983 I.setOperand(1, Constant::getNullValue(Op1->getType()));
3984 return &I;
3988 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
3989 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
3990 ConstantInt *Cst1;
3991 if ((Op0->hasOneUse() && match(Op0, m_ZExt(m_Value(A))) &&
3992 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
3993 (Op1->hasOneUse() && match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
3994 match(Op1, m_ZExt(m_Value(A))))) {
3995 APInt Pow2 = Cst1->getValue() + 1;
3996 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
3997 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
3998 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
4001 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
4002 // For lshr and ashr pairs.
4003 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4004 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
4005 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4006 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
4007 unsigned TypeBits = Cst1->getBitWidth();
4008 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4009 if (ShAmt < TypeBits && ShAmt != 0) {
4010 ICmpInst::Predicate NewPred =
4011 Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
4012 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
4013 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
4014 return new ICmpInst(NewPred, Xor, Builder.getInt(CmpVal));
4018 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
4019 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
4020 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
4021 unsigned TypeBits = Cst1->getBitWidth();
4022 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4023 if (ShAmt < TypeBits && ShAmt != 0) {
4024 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
4025 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
4026 Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal),
4027 I.getName() + ".mask");
4028 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
4032 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
4033 // "icmp (and X, mask), cst"
4034 uint64_t ShAmt = 0;
4035 if (Op0->hasOneUse() &&
4036 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
4037 match(Op1, m_ConstantInt(Cst1)) &&
4038 // Only do this when A has multiple uses. This is most important to do
4039 // when it exposes other optimizations.
4040 !A->hasOneUse()) {
4041 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
4043 if (ShAmt < ASize) {
4044 APInt MaskV =
4045 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
4046 MaskV <<= ShAmt;
4048 APInt CmpV = Cst1->getValue().zext(ASize);
4049 CmpV <<= ShAmt;
4051 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
4052 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
4056 // If both operands are byte-swapped or bit-reversed, just compare the
4057 // original values.
4058 // TODO: Move this to a function similar to foldICmpIntrinsicWithConstant()
4059 // and handle more intrinsics.
4060 if ((match(Op0, m_BSwap(m_Value(A))) && match(Op1, m_BSwap(m_Value(B)))) ||
4061 (match(Op0, m_BitReverse(m_Value(A))) &&
4062 match(Op1, m_BitReverse(m_Value(B)))))
4063 return new ICmpInst(Pred, A, B);
4065 // Canonicalize checking for a power-of-2-or-zero value:
4066 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
4067 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
4068 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
4069 m_Deferred(A)))) ||
4070 !match(Op1, m_ZeroInt()))
4071 A = nullptr;
4073 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
4074 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
4075 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
4076 A = Op1;
4077 else if (match(Op1,
4078 m_OneUse(m_c_And(m_Neg(m_Specific(Op0)), m_Specific(Op0)))))
4079 A = Op0;
4081 if (A) {
4082 Type *Ty = A->getType();
4083 CallInst *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
4084 return Pred == ICmpInst::ICMP_EQ
4085 ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop, ConstantInt::get(Ty, 2))
4086 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop, ConstantInt::get(Ty, 1));
4089 return nullptr;
4092 static Instruction *foldICmpWithZextOrSext(ICmpInst &ICmp,
4093 InstCombiner::BuilderTy &Builder) {
4094 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
4095 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
4096 Value *X;
4097 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
4098 return nullptr;
4100 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
4101 bool IsSignedCmp = ICmp.isSigned();
4102 if (auto *CastOp1 = dyn_cast<CastInst>(ICmp.getOperand(1))) {
4103 // If the signedness of the two casts doesn't agree (i.e. one is a sext
4104 // and the other is a zext), then we can't handle this.
4105 // TODO: This is too strict. We can handle some predicates (equality?).
4106 if (CastOp0->getOpcode() != CastOp1->getOpcode())
4107 return nullptr;
4109 // Not an extension from the same type?
4110 Value *Y = CastOp1->getOperand(0);
4111 Type *XTy = X->getType(), *YTy = Y->getType();
4112 if (XTy != YTy) {
4113 // One of the casts must have one use because we are creating a new cast.
4114 if (!CastOp0->hasOneUse() && !CastOp1->hasOneUse())
4115 return nullptr;
4116 // Extend the narrower operand to the type of the wider operand.
4117 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
4118 X = Builder.CreateCast(CastOp0->getOpcode(), X, YTy);
4119 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
4120 Y = Builder.CreateCast(CastOp0->getOpcode(), Y, XTy);
4121 else
4122 return nullptr;
4125 // (zext X) == (zext Y) --> X == Y
4126 // (sext X) == (sext Y) --> X == Y
4127 if (ICmp.isEquality())
4128 return new ICmpInst(ICmp.getPredicate(), X, Y);
4130 // A signed comparison of sign extended values simplifies into a
4131 // signed comparison.
4132 if (IsSignedCmp && IsSignedExt)
4133 return new ICmpInst(ICmp.getPredicate(), X, Y);
4135 // The other three cases all fold into an unsigned comparison.
4136 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
4139 // Below here, we are only folding a compare with constant.
4140 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
4141 if (!C)
4142 return nullptr;
4144 // Compute the constant that would happen if we truncated to SrcTy then
4145 // re-extended to DestTy.
4146 Type *SrcTy = CastOp0->getSrcTy();
4147 Type *DestTy = CastOp0->getDestTy();
4148 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
4149 Constant *Res2 = ConstantExpr::getCast(CastOp0->getOpcode(), Res1, DestTy);
4151 // If the re-extended constant didn't change...
4152 if (Res2 == C) {
4153 if (ICmp.isEquality())
4154 return new ICmpInst(ICmp.getPredicate(), X, Res1);
4156 // A signed comparison of sign extended values simplifies into a
4157 // signed comparison.
4158 if (IsSignedExt && IsSignedCmp)
4159 return new ICmpInst(ICmp.getPredicate(), X, Res1);
4161 // The other three cases all fold into an unsigned comparison.
4162 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res1);
4165 // The re-extended constant changed, partly changed (in the case of a vector),
4166 // or could not be determined to be equal (in the case of a constant
4167 // expression), so the constant cannot be represented in the shorter type.
4168 // All the cases that fold to true or false will have already been handled
4169 // by SimplifyICmpInst, so only deal with the tricky case.
4170 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
4171 return nullptr;
4173 // Is source op positive?
4174 // icmp ult (sext X), C --> icmp sgt X, -1
4175 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
4176 return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(SrcTy));
4178 // Is source op negative?
4179 // icmp ugt (sext X), C --> icmp slt X, 0
4180 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
4181 return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(SrcTy));
4184 /// Handle icmp (cast x), (cast or constant).
4185 Instruction *InstCombiner::foldICmpWithCastOp(ICmpInst &ICmp) {
4186 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
4187 if (!CastOp0)
4188 return nullptr;
4189 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
4190 return nullptr;
4192 Value *Op0Src = CastOp0->getOperand(0);
4193 Type *SrcTy = CastOp0->getSrcTy();
4194 Type *DestTy = CastOp0->getDestTy();
4196 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
4197 // integer type is the same size as the pointer type.
4198 auto CompatibleSizes = [&](Type *SrcTy, Type *DestTy) {
4199 if (isa<VectorType>(SrcTy)) {
4200 SrcTy = cast<VectorType>(SrcTy)->getElementType();
4201 DestTy = cast<VectorType>(DestTy)->getElementType();
4203 return DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth();
4205 if (CastOp0->getOpcode() == Instruction::PtrToInt &&
4206 CompatibleSizes(SrcTy, DestTy)) {
4207 Value *NewOp1 = nullptr;
4208 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
4209 Value *PtrSrc = PtrToIntOp1->getOperand(0);
4210 if (PtrSrc->getType()->getPointerAddressSpace() ==
4211 Op0Src->getType()->getPointerAddressSpace()) {
4212 NewOp1 = PtrToIntOp1->getOperand(0);
4213 // If the pointer types don't match, insert a bitcast.
4214 if (Op0Src->getType() != NewOp1->getType())
4215 NewOp1 = Builder.CreateBitCast(NewOp1, Op0Src->getType());
4217 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
4218 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
4221 if (NewOp1)
4222 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
4225 return foldICmpWithZextOrSext(ICmp, Builder);
4228 static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS) {
4229 switch (BinaryOp) {
4230 default:
4231 llvm_unreachable("Unsupported binary op");
4232 case Instruction::Add:
4233 case Instruction::Sub:
4234 return match(RHS, m_Zero());
4235 case Instruction::Mul:
4236 return match(RHS, m_One());
4240 OverflowResult InstCombiner::computeOverflow(
4241 Instruction::BinaryOps BinaryOp, bool IsSigned,
4242 Value *LHS, Value *RHS, Instruction *CxtI) const {
4243 switch (BinaryOp) {
4244 default:
4245 llvm_unreachable("Unsupported binary op");
4246 case Instruction::Add:
4247 if (IsSigned)
4248 return computeOverflowForSignedAdd(LHS, RHS, CxtI);
4249 else
4250 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
4251 case Instruction::Sub:
4252 if (IsSigned)
4253 return computeOverflowForSignedSub(LHS, RHS, CxtI);
4254 else
4255 return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
4256 case Instruction::Mul:
4257 if (IsSigned)
4258 return computeOverflowForSignedMul(LHS, RHS, CxtI);
4259 else
4260 return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
4264 bool InstCombiner::OptimizeOverflowCheck(
4265 Instruction::BinaryOps BinaryOp, bool IsSigned, Value *LHS, Value *RHS,
4266 Instruction &OrigI, Value *&Result, Constant *&Overflow) {
4267 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
4268 std::swap(LHS, RHS);
4270 // If the overflow check was an add followed by a compare, the insertion point
4271 // may be pointing to the compare. We want to insert the new instructions
4272 // before the add in case there are uses of the add between the add and the
4273 // compare.
4274 Builder.SetInsertPoint(&OrigI);
4276 if (isNeutralValue(BinaryOp, RHS)) {
4277 Result = LHS;
4278 Overflow = Builder.getFalse();
4279 return true;
4282 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
4283 case OverflowResult::MayOverflow:
4284 return false;
4285 case OverflowResult::AlwaysOverflowsLow:
4286 case OverflowResult::AlwaysOverflowsHigh:
4287 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
4288 Result->takeName(&OrigI);
4289 Overflow = Builder.getTrue();
4290 return true;
4291 case OverflowResult::NeverOverflows:
4292 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
4293 Result->takeName(&OrigI);
4294 Overflow = Builder.getFalse();
4295 if (auto *Inst = dyn_cast<Instruction>(Result)) {
4296 if (IsSigned)
4297 Inst->setHasNoSignedWrap();
4298 else
4299 Inst->setHasNoUnsignedWrap();
4301 return true;
4304 llvm_unreachable("Unexpected overflow result");
4307 /// Recognize and process idiom involving test for multiplication
4308 /// overflow.
4310 /// The caller has matched a pattern of the form:
4311 /// I = cmp u (mul(zext A, zext B), V
4312 /// The function checks if this is a test for overflow and if so replaces
4313 /// multiplication with call to 'mul.with.overflow' intrinsic.
4315 /// \param I Compare instruction.
4316 /// \param MulVal Result of 'mult' instruction. It is one of the arguments of
4317 /// the compare instruction. Must be of integer type.
4318 /// \param OtherVal The other argument of compare instruction.
4319 /// \returns Instruction which must replace the compare instruction, NULL if no
4320 /// replacement required.
4321 static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,
4322 Value *OtherVal, InstCombiner &IC) {
4323 // Don't bother doing this transformation for pointers, don't do it for
4324 // vectors.
4325 if (!isa<IntegerType>(MulVal->getType()))
4326 return nullptr;
4328 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
4329 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
4330 auto *MulInstr = dyn_cast<Instruction>(MulVal);
4331 if (!MulInstr)
4332 return nullptr;
4333 assert(MulInstr->getOpcode() == Instruction::Mul);
4335 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
4336 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
4337 assert(LHS->getOpcode() == Instruction::ZExt);
4338 assert(RHS->getOpcode() == Instruction::ZExt);
4339 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
4341 // Calculate type and width of the result produced by mul.with.overflow.
4342 Type *TyA = A->getType(), *TyB = B->getType();
4343 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
4344 WidthB = TyB->getPrimitiveSizeInBits();
4345 unsigned MulWidth;
4346 Type *MulType;
4347 if (WidthB > WidthA) {
4348 MulWidth = WidthB;
4349 MulType = TyB;
4350 } else {
4351 MulWidth = WidthA;
4352 MulType = TyA;
4355 // In order to replace the original mul with a narrower mul.with.overflow,
4356 // all uses must ignore upper bits of the product. The number of used low
4357 // bits must be not greater than the width of mul.with.overflow.
4358 if (MulVal->hasNUsesOrMore(2))
4359 for (User *U : MulVal->users()) {
4360 if (U == &I)
4361 continue;
4362 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
4363 // Check if truncation ignores bits above MulWidth.
4364 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
4365 if (TruncWidth > MulWidth)
4366 return nullptr;
4367 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
4368 // Check if AND ignores bits above MulWidth.
4369 if (BO->getOpcode() != Instruction::And)
4370 return nullptr;
4371 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4372 const APInt &CVal = CI->getValue();
4373 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
4374 return nullptr;
4375 } else {
4376 // In this case we could have the operand of the binary operation
4377 // being defined in another block, and performing the replacement
4378 // could break the dominance relation.
4379 return nullptr;
4381 } else {
4382 // Other uses prohibit this transformation.
4383 return nullptr;
4387 // Recognize patterns
4388 switch (I.getPredicate()) {
4389 case ICmpInst::ICMP_EQ:
4390 case ICmpInst::ICMP_NE:
4391 // Recognize pattern:
4392 // mulval = mul(zext A, zext B)
4393 // cmp eq/neq mulval, zext trunc mulval
4394 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
4395 if (Zext->hasOneUse()) {
4396 Value *ZextArg = Zext->getOperand(0);
4397 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
4398 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
4399 break; //Recognized
4402 // Recognize pattern:
4403 // mulval = mul(zext A, zext B)
4404 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
4405 ConstantInt *CI;
4406 Value *ValToMask;
4407 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
4408 if (ValToMask != MulVal)
4409 return nullptr;
4410 const APInt &CVal = CI->getValue() + 1;
4411 if (CVal.isPowerOf2()) {
4412 unsigned MaskWidth = CVal.logBase2();
4413 if (MaskWidth == MulWidth)
4414 break; // Recognized
4417 return nullptr;
4419 case ICmpInst::ICMP_UGT:
4420 // Recognize pattern:
4421 // mulval = mul(zext A, zext B)
4422 // cmp ugt mulval, max
4423 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4424 APInt MaxVal = APInt::getMaxValue(MulWidth);
4425 MaxVal = MaxVal.zext(CI->getBitWidth());
4426 if (MaxVal.eq(CI->getValue()))
4427 break; // Recognized
4429 return nullptr;
4431 case ICmpInst::ICMP_UGE:
4432 // Recognize pattern:
4433 // mulval = mul(zext A, zext B)
4434 // cmp uge mulval, max+1
4435 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4436 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
4437 if (MaxVal.eq(CI->getValue()))
4438 break; // Recognized
4440 return nullptr;
4442 case ICmpInst::ICMP_ULE:
4443 // Recognize pattern:
4444 // mulval = mul(zext A, zext B)
4445 // cmp ule mulval, max
4446 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4447 APInt MaxVal = APInt::getMaxValue(MulWidth);
4448 MaxVal = MaxVal.zext(CI->getBitWidth());
4449 if (MaxVal.eq(CI->getValue()))
4450 break; // Recognized
4452 return nullptr;
4454 case ICmpInst::ICMP_ULT:
4455 // Recognize pattern:
4456 // mulval = mul(zext A, zext B)
4457 // cmp ule mulval, max + 1
4458 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4459 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
4460 if (MaxVal.eq(CI->getValue()))
4461 break; // Recognized
4463 return nullptr;
4465 default:
4466 return nullptr;
4469 InstCombiner::BuilderTy &Builder = IC.Builder;
4470 Builder.SetInsertPoint(MulInstr);
4472 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
4473 Value *MulA = A, *MulB = B;
4474 if (WidthA < MulWidth)
4475 MulA = Builder.CreateZExt(A, MulType);
4476 if (WidthB < MulWidth)
4477 MulB = Builder.CreateZExt(B, MulType);
4478 Function *F = Intrinsic::getDeclaration(
4479 I.getModule(), Intrinsic::umul_with_overflow, MulType);
4480 CallInst *Call = Builder.CreateCall(F, {MulA, MulB}, "umul");
4481 IC.Worklist.Add(MulInstr);
4483 // If there are uses of mul result other than the comparison, we know that
4484 // they are truncation or binary AND. Change them to use result of
4485 // mul.with.overflow and adjust properly mask/size.
4486 if (MulVal->hasNUsesOrMore(2)) {
4487 Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value");
4488 for (auto UI = MulVal->user_begin(), UE = MulVal->user_end(); UI != UE;) {
4489 User *U = *UI++;
4490 if (U == &I || U == OtherVal)
4491 continue;
4492 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
4493 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
4494 IC.replaceInstUsesWith(*TI, Mul);
4495 else
4496 TI->setOperand(0, Mul);
4497 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
4498 assert(BO->getOpcode() == Instruction::And);
4499 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
4500 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
4501 APInt ShortMask = CI->getValue().trunc(MulWidth);
4502 Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask);
4503 Instruction *Zext =
4504 cast<Instruction>(Builder.CreateZExt(ShortAnd, BO->getType()));
4505 IC.Worklist.Add(Zext);
4506 IC.replaceInstUsesWith(*BO, Zext);
4507 } else {
4508 llvm_unreachable("Unexpected Binary operation");
4510 IC.Worklist.Add(cast<Instruction>(U));
4513 if (isa<Instruction>(OtherVal))
4514 IC.Worklist.Add(cast<Instruction>(OtherVal));
4516 // The original icmp gets replaced with the overflow value, maybe inverted
4517 // depending on predicate.
4518 bool Inverse = false;
4519 switch (I.getPredicate()) {
4520 case ICmpInst::ICMP_NE:
4521 break;
4522 case ICmpInst::ICMP_EQ:
4523 Inverse = true;
4524 break;
4525 case ICmpInst::ICMP_UGT:
4526 case ICmpInst::ICMP_UGE:
4527 if (I.getOperand(0) == MulVal)
4528 break;
4529 Inverse = true;
4530 break;
4531 case ICmpInst::ICMP_ULT:
4532 case ICmpInst::ICMP_ULE:
4533 if (I.getOperand(1) == MulVal)
4534 break;
4535 Inverse = true;
4536 break;
4537 default:
4538 llvm_unreachable("Unexpected predicate");
4540 if (Inverse) {
4541 Value *Res = Builder.CreateExtractValue(Call, 1);
4542 return BinaryOperator::CreateNot(Res);
4545 return ExtractValueInst::Create(Call, 1);
4548 /// When performing a comparison against a constant, it is possible that not all
4549 /// the bits in the LHS are demanded. This helper method computes the mask that
4550 /// IS demanded.
4551 static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) {
4552 const APInt *RHS;
4553 if (!match(I.getOperand(1), m_APInt(RHS)))
4554 return APInt::getAllOnesValue(BitWidth);
4556 // If this is a normal comparison, it demands all bits. If it is a sign bit
4557 // comparison, it only demands the sign bit.
4558 bool UnusedBit;
4559 if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
4560 return APInt::getSignMask(BitWidth);
4562 switch (I.getPredicate()) {
4563 // For a UGT comparison, we don't care about any bits that
4564 // correspond to the trailing ones of the comparand. The value of these
4565 // bits doesn't impact the outcome of the comparison, because any value
4566 // greater than the RHS must differ in a bit higher than these due to carry.
4567 case ICmpInst::ICMP_UGT:
4568 return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingOnes());
4570 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
4571 // Any value less than the RHS must differ in a higher bit because of carries.
4572 case ICmpInst::ICMP_ULT:
4573 return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingZeros());
4575 default:
4576 return APInt::getAllOnesValue(BitWidth);
4580 /// Check if the order of \p Op0 and \p Op1 as operands in an ICmpInst
4581 /// should be swapped.
4582 /// The decision is based on how many times these two operands are reused
4583 /// as subtract operands and their positions in those instructions.
4584 /// The rationale is that several architectures use the same instruction for
4585 /// both subtract and cmp. Thus, it is better if the order of those operands
4586 /// match.
4587 /// \return true if Op0 and Op1 should be swapped.
4588 static bool swapMayExposeCSEOpportunities(const Value *Op0, const Value *Op1) {
4589 // Filter out pointer values as those cannot appear directly in subtract.
4590 // FIXME: we may want to go through inttoptrs or bitcasts.
4591 if (Op0->getType()->isPointerTy())
4592 return false;
4593 // If a subtract already has the same operands as a compare, swapping would be
4594 // bad. If a subtract has the same operands as a compare but in reverse order,
4595 // then swapping is good.
4596 int GoodToSwap = 0;
4597 for (const User *U : Op0->users()) {
4598 if (match(U, m_Sub(m_Specific(Op1), m_Specific(Op0))))
4599 GoodToSwap++;
4600 else if (match(U, m_Sub(m_Specific(Op0), m_Specific(Op1))))
4601 GoodToSwap--;
4603 return GoodToSwap > 0;
4606 /// Check that one use is in the same block as the definition and all
4607 /// other uses are in blocks dominated by a given block.
4609 /// \param DI Definition
4610 /// \param UI Use
4611 /// \param DB Block that must dominate all uses of \p DI outside
4612 /// the parent block
4613 /// \return true when \p UI is the only use of \p DI in the parent block
4614 /// and all other uses of \p DI are in blocks dominated by \p DB.
4616 bool InstCombiner::dominatesAllUses(const Instruction *DI,
4617 const Instruction *UI,
4618 const BasicBlock *DB) const {
4619 assert(DI && UI && "Instruction not defined\n");
4620 // Ignore incomplete definitions.
4621 if (!DI->getParent())
4622 return false;
4623 // DI and UI must be in the same block.
4624 if (DI->getParent() != UI->getParent())
4625 return false;
4626 // Protect from self-referencing blocks.
4627 if (DI->getParent() == DB)
4628 return false;
4629 for (const User *U : DI->users()) {
4630 auto *Usr = cast<Instruction>(U);
4631 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
4632 return false;
4634 return true;
4637 /// Return true when the instruction sequence within a block is select-cmp-br.
4638 static bool isChainSelectCmpBranch(const SelectInst *SI) {
4639 const BasicBlock *BB = SI->getParent();
4640 if (!BB)
4641 return false;
4642 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
4643 if (!BI || BI->getNumSuccessors() != 2)
4644 return false;
4645 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
4646 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
4647 return false;
4648 return true;
4651 /// True when a select result is replaced by one of its operands
4652 /// in select-icmp sequence. This will eventually result in the elimination
4653 /// of the select.
4655 /// \param SI Select instruction
4656 /// \param Icmp Compare instruction
4657 /// \param SIOpd Operand that replaces the select
4659 /// Notes:
4660 /// - The replacement is global and requires dominator information
4661 /// - The caller is responsible for the actual replacement
4663 /// Example:
4665 /// entry:
4666 /// %4 = select i1 %3, %C* %0, %C* null
4667 /// %5 = icmp eq %C* %4, null
4668 /// br i1 %5, label %9, label %7
4669 /// ...
4670 /// ; <label>:7 ; preds = %entry
4671 /// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
4672 /// ...
4674 /// can be transformed to
4676 /// %5 = icmp eq %C* %0, null
4677 /// %6 = select i1 %3, i1 %5, i1 true
4678 /// br i1 %6, label %9, label %7
4679 /// ...
4680 /// ; <label>:7 ; preds = %entry
4681 /// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
4683 /// Similar when the first operand of the select is a constant or/and
4684 /// the compare is for not equal rather than equal.
4686 /// NOTE: The function is only called when the select and compare constants
4687 /// are equal, the optimization can work only for EQ predicates. This is not a
4688 /// major restriction since a NE compare should be 'normalized' to an equal
4689 /// compare, which usually happens in the combiner and test case
4690 /// select-cmp-br.ll checks for it.
4691 bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
4692 const ICmpInst *Icmp,
4693 const unsigned SIOpd) {
4694 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
4695 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
4696 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
4697 // The check for the single predecessor is not the best that can be
4698 // done. But it protects efficiently against cases like when SI's
4699 // home block has two successors, Succ and Succ1, and Succ1 predecessor
4700 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
4701 // replaced can be reached on either path. So the uniqueness check
4702 // guarantees that the path all uses of SI (outside SI's parent) are on
4703 // is disjoint from all other paths out of SI. But that information
4704 // is more expensive to compute, and the trade-off here is in favor
4705 // of compile-time. It should also be noticed that we check for a single
4706 // predecessor and not only uniqueness. This to handle the situation when
4707 // Succ and Succ1 points to the same basic block.
4708 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
4709 NumSel++;
4710 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
4711 return true;
4714 return false;
4717 /// Try to fold the comparison based on range information we can get by checking
4718 /// whether bits are known to be zero or one in the inputs.
4719 Instruction *InstCombiner::foldICmpUsingKnownBits(ICmpInst &I) {
4720 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4721 Type *Ty = Op0->getType();
4722 ICmpInst::Predicate Pred = I.getPredicate();
4724 // Get scalar or pointer size.
4725 unsigned BitWidth = Ty->isIntOrIntVectorTy()
4726 ? Ty->getScalarSizeInBits()
4727 : DL.getIndexTypeSizeInBits(Ty->getScalarType());
4729 if (!BitWidth)
4730 return nullptr;
4732 KnownBits Op0Known(BitWidth);
4733 KnownBits Op1Known(BitWidth);
4735 if (SimplifyDemandedBits(&I, 0,
4736 getDemandedBitsLHSMask(I, BitWidth),
4737 Op0Known, 0))
4738 return &I;
4740 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnesValue(BitWidth),
4741 Op1Known, 0))
4742 return &I;
4744 // Given the known and unknown bits, compute a range that the LHS could be
4745 // in. Compute the Min, Max and RHS values based on the known bits. For the
4746 // EQ and NE we use unsigned values.
4747 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
4748 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
4749 if (I.isSigned()) {
4750 computeSignedMinMaxValuesFromKnownBits(Op0Known, Op0Min, Op0Max);
4751 computeSignedMinMaxValuesFromKnownBits(Op1Known, Op1Min, Op1Max);
4752 } else {
4753 computeUnsignedMinMaxValuesFromKnownBits(Op0Known, Op0Min, Op0Max);
4754 computeUnsignedMinMaxValuesFromKnownBits(Op1Known, Op1Min, Op1Max);
4757 // If Min and Max are known to be the same, then SimplifyDemandedBits figured
4758 // out that the LHS or RHS is a constant. Constant fold this now, so that
4759 // code below can assume that Min != Max.
4760 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
4761 return new ICmpInst(Pred, ConstantExpr::getIntegerValue(Ty, Op0Min), Op1);
4762 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
4763 return new ICmpInst(Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Min));
4765 // Based on the range information we know about the LHS, see if we can
4766 // simplify this comparison. For example, (x&4) < 8 is always true.
4767 switch (Pred) {
4768 default:
4769 llvm_unreachable("Unknown icmp opcode!");
4770 case ICmpInst::ICMP_EQ:
4771 case ICmpInst::ICMP_NE: {
4772 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) {
4773 return Pred == CmpInst::ICMP_EQ
4774 ? replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()))
4775 : replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4778 // If all bits are known zero except for one, then we know at most one bit
4779 // is set. If the comparison is against zero, then this is a check to see if
4780 // *that* bit is set.
4781 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
4782 if (Op1Known.isZero()) {
4783 // If the LHS is an AND with the same constant, look through it.
4784 Value *LHS = nullptr;
4785 const APInt *LHSC;
4786 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
4787 *LHSC != Op0KnownZeroInverted)
4788 LHS = Op0;
4790 Value *X;
4791 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
4792 APInt ValToCheck = Op0KnownZeroInverted;
4793 Type *XTy = X->getType();
4794 if (ValToCheck.isPowerOf2()) {
4795 // ((1 << X) & 8) == 0 -> X != 3
4796 // ((1 << X) & 8) != 0 -> X == 3
4797 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros());
4798 auto NewPred = ICmpInst::getInversePredicate(Pred);
4799 return new ICmpInst(NewPred, X, CmpC);
4800 } else if ((++ValToCheck).isPowerOf2()) {
4801 // ((1 << X) & 7) == 0 -> X >= 3
4802 // ((1 << X) & 7) != 0 -> X < 3
4803 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros());
4804 auto NewPred =
4805 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
4806 return new ICmpInst(NewPred, X, CmpC);
4810 // Check if the LHS is 8 >>u x and the result is a power of 2 like 1.
4811 const APInt *CI;
4812 if (Op0KnownZeroInverted.isOneValue() &&
4813 match(LHS, m_LShr(m_Power2(CI), m_Value(X)))) {
4814 // ((8 >>u X) & 1) == 0 -> X != 3
4815 // ((8 >>u X) & 1) != 0 -> X == 3
4816 unsigned CmpVal = CI->countTrailingZeros();
4817 auto NewPred = ICmpInst::getInversePredicate(Pred);
4818 return new ICmpInst(NewPred, X, ConstantInt::get(X->getType(), CmpVal));
4821 break;
4823 case ICmpInst::ICMP_ULT: {
4824 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
4825 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4826 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
4827 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4828 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
4829 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4831 const APInt *CmpC;
4832 if (match(Op1, m_APInt(CmpC))) {
4833 // A <u C -> A == C-1 if min(A)+1 == C
4834 if (*CmpC == Op0Min + 1)
4835 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4836 ConstantInt::get(Op1->getType(), *CmpC - 1));
4837 // X <u C --> X == 0, if the number of zero bits in the bottom of X
4838 // exceeds the log2 of C.
4839 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
4840 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4841 Constant::getNullValue(Op1->getType()));
4843 break;
4845 case ICmpInst::ICMP_UGT: {
4846 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
4847 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4848 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
4849 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4850 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
4851 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4853 const APInt *CmpC;
4854 if (match(Op1, m_APInt(CmpC))) {
4855 // A >u C -> A == C+1 if max(a)-1 == C
4856 if (*CmpC == Op0Max - 1)
4857 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4858 ConstantInt::get(Op1->getType(), *CmpC + 1));
4859 // X >u C --> X != 0, if the number of zero bits in the bottom of X
4860 // exceeds the log2 of C.
4861 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
4862 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
4863 Constant::getNullValue(Op1->getType()));
4865 break;
4867 case ICmpInst::ICMP_SLT: {
4868 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
4869 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4870 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
4871 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4872 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
4873 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4874 const APInt *CmpC;
4875 if (match(Op1, m_APInt(CmpC))) {
4876 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
4877 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4878 ConstantInt::get(Op1->getType(), *CmpC - 1));
4880 break;
4882 case ICmpInst::ICMP_SGT: {
4883 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
4884 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4885 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
4886 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4887 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
4888 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4889 const APInt *CmpC;
4890 if (match(Op1, m_APInt(CmpC))) {
4891 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
4892 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4893 ConstantInt::get(Op1->getType(), *CmpC + 1));
4895 break;
4897 case ICmpInst::ICMP_SGE:
4898 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
4899 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
4900 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4901 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
4902 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4903 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
4904 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4905 break;
4906 case ICmpInst::ICMP_SLE:
4907 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
4908 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
4909 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4910 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
4911 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4912 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
4913 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4914 break;
4915 case ICmpInst::ICMP_UGE:
4916 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
4917 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
4918 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4919 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
4920 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4921 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
4922 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4923 break;
4924 case ICmpInst::ICMP_ULE:
4925 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
4926 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
4927 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4928 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
4929 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4930 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
4931 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4932 break;
4935 // Turn a signed comparison into an unsigned one if both operands are known to
4936 // have the same sign.
4937 if (I.isSigned() &&
4938 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
4939 (Op0Known.One.isNegative() && Op1Known.One.isNegative())))
4940 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
4942 return nullptr;
4945 llvm::Optional<std::pair<CmpInst::Predicate, Constant *>>
4946 llvm::getFlippedStrictnessPredicateAndConstant(CmpInst::Predicate Pred,
4947 Constant *C) {
4948 assert(ICmpInst::isRelational(Pred) && ICmpInst::isIntPredicate(Pred) &&
4949 "Only for relational integer predicates.");
4951 Type *Type = C->getType();
4952 bool IsSigned = ICmpInst::isSigned(Pred);
4954 CmpInst::Predicate UnsignedPred = ICmpInst::getUnsignedPredicate(Pred);
4955 bool WillIncrement =
4956 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
4958 // Check if the constant operand can be safely incremented/decremented
4959 // without overflowing/underflowing.
4960 auto ConstantIsOk = [WillIncrement, IsSigned](ConstantInt *C) {
4961 return WillIncrement ? !C->isMaxValue(IsSigned) : !C->isMinValue(IsSigned);
4964 // For scalars, SimplifyICmpInst should have already handled
4965 // the edge cases for us, so we just assert on them.
4966 // For vectors, we must handle the edge cases.
4967 if (auto *CI = dyn_cast<ConstantInt>(C)) {
4968 // A <= MAX -> TRUE ; A >= MIN -> TRUE
4969 assert(ConstantIsOk(CI));
4970 } else if (Type->isVectorTy()) {
4971 // TODO? If the edge cases for vectors were guaranteed to be handled as they
4972 // are for scalar, we could remove the min/max checks. However, to do that,
4973 // we would have to use insertelement/shufflevector to replace edge values.
4974 unsigned NumElts = Type->getVectorNumElements();
4975 for (unsigned i = 0; i != NumElts; ++i) {
4976 Constant *Elt = C->getAggregateElement(i);
4977 if (!Elt)
4978 return llvm::None;
4980 if (isa<UndefValue>(Elt))
4981 continue;
4983 // Bail out if we can't determine if this constant is min/max or if we
4984 // know that this constant is min/max.
4985 auto *CI = dyn_cast<ConstantInt>(Elt);
4986 if (!CI || !ConstantIsOk(CI))
4987 return llvm::None;
4989 } else {
4990 // ConstantExpr?
4991 return llvm::None;
4994 CmpInst::Predicate NewPred = CmpInst::getFlippedStrictnessPredicate(Pred);
4996 // Increment or decrement the constant.
4997 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
4998 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
5000 return std::make_pair(NewPred, NewC);
5003 /// If we have an icmp le or icmp ge instruction with a constant operand, turn
5004 /// it into the appropriate icmp lt or icmp gt instruction. This transform
5005 /// allows them to be folded in visitICmpInst.
5006 static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
5007 ICmpInst::Predicate Pred = I.getPredicate();
5008 if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
5009 isCanonicalPredicate(Pred))
5010 return nullptr;
5012 Value *Op0 = I.getOperand(0);
5013 Value *Op1 = I.getOperand(1);
5014 auto *Op1C = dyn_cast<Constant>(Op1);
5015 if (!Op1C)
5016 return nullptr;
5018 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
5019 if (!FlippedStrictness)
5020 return nullptr;
5022 return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
5025 /// Integer compare with boolean values can always be turned into bitwise ops.
5026 static Instruction *canonicalizeICmpBool(ICmpInst &I,
5027 InstCombiner::BuilderTy &Builder) {
5028 Value *A = I.getOperand(0), *B = I.getOperand(1);
5029 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
5031 // A boolean compared to true/false can be simplified to Op0/true/false in
5032 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
5033 // Cases not handled by InstSimplify are always 'not' of Op0.
5034 if (match(B, m_Zero())) {
5035 switch (I.getPredicate()) {
5036 case CmpInst::ICMP_EQ: // A == 0 -> !A
5037 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
5038 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
5039 return BinaryOperator::CreateNot(A);
5040 default:
5041 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
5043 } else if (match(B, m_One())) {
5044 switch (I.getPredicate()) {
5045 case CmpInst::ICMP_NE: // A != 1 -> !A
5046 case CmpInst::ICMP_ULT: // A <u 1 -> !A
5047 case CmpInst::ICMP_SGT: // A >s -1 -> !A
5048 return BinaryOperator::CreateNot(A);
5049 default:
5050 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
5054 switch (I.getPredicate()) {
5055 default:
5056 llvm_unreachable("Invalid icmp instruction!");
5057 case ICmpInst::ICMP_EQ:
5058 // icmp eq i1 A, B -> ~(A ^ B)
5059 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
5061 case ICmpInst::ICMP_NE:
5062 // icmp ne i1 A, B -> A ^ B
5063 return BinaryOperator::CreateXor(A, B);
5065 case ICmpInst::ICMP_UGT:
5066 // icmp ugt -> icmp ult
5067 std::swap(A, B);
5068 LLVM_FALLTHROUGH;
5069 case ICmpInst::ICMP_ULT:
5070 // icmp ult i1 A, B -> ~A & B
5071 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
5073 case ICmpInst::ICMP_SGT:
5074 // icmp sgt -> icmp slt
5075 std::swap(A, B);
5076 LLVM_FALLTHROUGH;
5077 case ICmpInst::ICMP_SLT:
5078 // icmp slt i1 A, B -> A & ~B
5079 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
5081 case ICmpInst::ICMP_UGE:
5082 // icmp uge -> icmp ule
5083 std::swap(A, B);
5084 LLVM_FALLTHROUGH;
5085 case ICmpInst::ICMP_ULE:
5086 // icmp ule i1 A, B -> ~A | B
5087 return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
5089 case ICmpInst::ICMP_SGE:
5090 // icmp sge -> icmp sle
5091 std::swap(A, B);
5092 LLVM_FALLTHROUGH;
5093 case ICmpInst::ICMP_SLE:
5094 // icmp sle i1 A, B -> A | ~B
5095 return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
5099 // Transform pattern like:
5100 // (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
5101 // (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
5102 // Into:
5103 // (X l>> Y) != 0
5104 // (X l>> Y) == 0
5105 static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp,
5106 InstCombiner::BuilderTy &Builder) {
5107 ICmpInst::Predicate Pred, NewPred;
5108 Value *X, *Y;
5109 if (match(&Cmp,
5110 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
5111 // We want X to be the icmp's second operand, so swap predicate if it isn't.
5112 if (Cmp.getOperand(0) == X)
5113 Pred = Cmp.getSwappedPredicate();
5115 switch (Pred) {
5116 case ICmpInst::ICMP_ULE:
5117 NewPred = ICmpInst::ICMP_NE;
5118 break;
5119 case ICmpInst::ICMP_UGT:
5120 NewPred = ICmpInst::ICMP_EQ;
5121 break;
5122 default:
5123 return nullptr;
5125 } else if (match(&Cmp, m_c_ICmp(Pred,
5126 m_OneUse(m_CombineOr(
5127 m_Not(m_Shl(m_AllOnes(), m_Value(Y))),
5128 m_Add(m_Shl(m_One(), m_Value(Y)),
5129 m_AllOnes()))),
5130 m_Value(X)))) {
5131 // The variant with 'add' is not canonical, (the variant with 'not' is)
5132 // we only get it because it has extra uses, and can't be canonicalized,
5134 // We want X to be the icmp's second operand, so swap predicate if it isn't.
5135 if (Cmp.getOperand(0) == X)
5136 Pred = Cmp.getSwappedPredicate();
5138 switch (Pred) {
5139 case ICmpInst::ICMP_ULT:
5140 NewPred = ICmpInst::ICMP_NE;
5141 break;
5142 case ICmpInst::ICMP_UGE:
5143 NewPred = ICmpInst::ICMP_EQ;
5144 break;
5145 default:
5146 return nullptr;
5148 } else
5149 return nullptr;
5151 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
5152 Constant *Zero = Constant::getNullValue(NewX->getType());
5153 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
5156 static Instruction *foldVectorCmp(CmpInst &Cmp,
5157 InstCombiner::BuilderTy &Builder) {
5158 // If both arguments of the cmp are shuffles that use the same mask and
5159 // shuffle within a single vector, move the shuffle after the cmp.
5160 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
5161 Value *V1, *V2;
5162 Constant *M;
5163 if (match(LHS, m_ShuffleVector(m_Value(V1), m_Undef(), m_Constant(M))) &&
5164 match(RHS, m_ShuffleVector(m_Value(V2), m_Undef(), m_Specific(M))) &&
5165 V1->getType() == V2->getType() &&
5166 (LHS->hasOneUse() || RHS->hasOneUse())) {
5167 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
5168 CmpInst::Predicate P = Cmp.getPredicate();
5169 Value *NewCmp = isa<ICmpInst>(Cmp) ? Builder.CreateICmp(P, V1, V2)
5170 : Builder.CreateFCmp(P, V1, V2);
5171 return new ShuffleVectorInst(NewCmp, UndefValue::get(NewCmp->getType()), M);
5173 return nullptr;
5176 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5177 bool Changed = false;
5178 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5179 unsigned Op0Cplxity = getComplexity(Op0);
5180 unsigned Op1Cplxity = getComplexity(Op1);
5182 /// Orders the operands of the compare so that they are listed from most
5183 /// complex to least complex. This puts constants before unary operators,
5184 /// before binary operators.
5185 if (Op0Cplxity < Op1Cplxity ||
5186 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
5187 I.swapOperands();
5188 std::swap(Op0, Op1);
5189 Changed = true;
5192 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1,
5193 SQ.getWithInstruction(&I)))
5194 return replaceInstUsesWith(I, V);
5196 // Comparing -val or val with non-zero is the same as just comparing val
5197 // ie, abs(val) != 0 -> val != 0
5198 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
5199 Value *Cond, *SelectTrue, *SelectFalse;
5200 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
5201 m_Value(SelectFalse)))) {
5202 if (Value *V = dyn_castNegVal(SelectTrue)) {
5203 if (V == SelectFalse)
5204 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
5206 else if (Value *V = dyn_castNegVal(SelectFalse)) {
5207 if (V == SelectTrue)
5208 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
5213 if (Op0->getType()->isIntOrIntVectorTy(1))
5214 if (Instruction *Res = canonicalizeICmpBool(I, Builder))
5215 return Res;
5217 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
5218 return NewICmp;
5220 if (Instruction *Res = foldICmpWithConstant(I))
5221 return Res;
5223 if (Instruction *Res = foldICmpWithDominatingICmp(I))
5224 return Res;
5226 if (Instruction *Res = foldICmpUsingKnownBits(I))
5227 return Res;
5229 // Test if the ICmpInst instruction is used exclusively by a select as
5230 // part of a minimum or maximum operation. If so, refrain from doing
5231 // any other folding. This helps out other analyses which understand
5232 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5233 // and CodeGen. And in this case, at least one of the comparison
5234 // operands has at least one user besides the compare (the select),
5235 // which would often largely negate the benefit of folding anyway.
5237 // Do the same for the other patterns recognized by matchSelectPattern.
5238 if (I.hasOneUse())
5239 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
5240 Value *A, *B;
5241 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
5242 if (SPR.Flavor != SPF_UNKNOWN)
5243 return nullptr;
5246 // Do this after checking for min/max to prevent infinite looping.
5247 if (Instruction *Res = foldICmpWithZero(I))
5248 return Res;
5250 // FIXME: We only do this after checking for min/max to prevent infinite
5251 // looping caused by a reverse canonicalization of these patterns for min/max.
5252 // FIXME: The organization of folds is a mess. These would naturally go into
5253 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
5254 // down here after the min/max restriction.
5255 ICmpInst::Predicate Pred = I.getPredicate();
5256 const APInt *C;
5257 if (match(Op1, m_APInt(C))) {
5258 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
5259 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
5260 Constant *Zero = Constant::getNullValue(Op0->getType());
5261 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
5264 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
5265 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
5266 Constant *AllOnes = Constant::getAllOnesValue(Op0->getType());
5267 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
5271 if (Instruction *Res = foldICmpInstWithConstant(I))
5272 return Res;
5274 if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
5275 return Res;
5277 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5278 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
5279 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
5280 return NI;
5281 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
5282 if (Instruction *NI = foldGEPICmp(GEP, Op0,
5283 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5284 return NI;
5286 // Try to optimize equality comparisons against alloca-based pointers.
5287 if (Op0->getType()->isPointerTy() && I.isEquality()) {
5288 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
5289 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
5290 if (Instruction *New = foldAllocaCmp(I, Alloca, Op1))
5291 return New;
5292 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
5293 if (Instruction *New = foldAllocaCmp(I, Alloca, Op0))
5294 return New;
5297 if (Instruction *Res = foldICmpBitCast(I, Builder))
5298 return Res;
5300 if (Instruction *R = foldICmpWithCastOp(I))
5301 return R;
5303 if (Instruction *Res = foldICmpBinOp(I))
5304 return Res;
5306 if (Instruction *Res = foldICmpWithMinMax(I))
5307 return Res;
5310 Value *A, *B;
5311 // Transform (A & ~B) == 0 --> (A & B) != 0
5312 // and (A & ~B) != 0 --> (A & B) == 0
5313 // if A is a power of 2.
5314 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
5315 match(Op1, m_Zero()) &&
5316 isKnownToBeAPowerOfTwo(A, false, 0, &I) && I.isEquality())
5317 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(A, B),
5318 Op1);
5320 // ~X < ~Y --> Y < X
5321 // ~X < C --> X > ~C
5322 if (match(Op0, m_Not(m_Value(A)))) {
5323 if (match(Op1, m_Not(m_Value(B))))
5324 return new ICmpInst(I.getPredicate(), B, A);
5326 const APInt *C;
5327 if (match(Op1, m_APInt(C)))
5328 return new ICmpInst(I.getSwappedPredicate(), A,
5329 ConstantInt::get(Op1->getType(), ~(*C)));
5332 Instruction *AddI = nullptr;
5333 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
5334 m_Instruction(AddI))) &&
5335 isa<IntegerType>(A->getType())) {
5336 Value *Result;
5337 Constant *Overflow;
5338 if (OptimizeOverflowCheck(Instruction::Add, /*Signed*/false, A, B,
5339 *AddI, Result, Overflow)) {
5340 replaceInstUsesWith(*AddI, Result);
5341 return replaceInstUsesWith(I, Overflow);
5345 // (zext a) * (zext b) --> llvm.umul.with.overflow.
5346 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
5347 if (Instruction *R = processUMulZExtIdiom(I, Op0, Op1, *this))
5348 return R;
5350 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
5351 if (Instruction *R = processUMulZExtIdiom(I, Op1, Op0, *this))
5352 return R;
5356 if (Instruction *Res = foldICmpEquality(I))
5357 return Res;
5359 // The 'cmpxchg' instruction returns an aggregate containing the old value and
5360 // an i1 which indicates whether or not we successfully did the swap.
5362 // Replace comparisons between the old value and the expected value with the
5363 // indicator that 'cmpxchg' returns.
5365 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
5366 // spuriously fail. In those cases, the old value may equal the expected
5367 // value but it is possible for the swap to not occur.
5368 if (I.getPredicate() == ICmpInst::ICMP_EQ)
5369 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
5370 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
5371 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
5372 !ACXI->isWeak())
5373 return ExtractValueInst::Create(ACXI, 1);
5376 Value *X;
5377 const APInt *C;
5378 // icmp X+Cst, X
5379 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
5380 return foldICmpAddOpConst(X, *C, I.getPredicate());
5382 // icmp X, X+Cst
5383 if (match(Op1, m_Add(m_Value(X), m_APInt(C))) && Op0 == X)
5384 return foldICmpAddOpConst(X, *C, I.getSwappedPredicate());
5387 if (Instruction *Res = foldICmpWithHighBitMask(I, Builder))
5388 return Res;
5390 if (I.getType()->isVectorTy())
5391 if (Instruction *Res = foldVectorCmp(I, Builder))
5392 return Res;
5394 return Changed ? &I : nullptr;
5397 /// Fold fcmp ([us]itofp x, cst) if possible.
5398 Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
5399 Constant *RHSC) {
5400 if (!isa<ConstantFP>(RHSC)) return nullptr;
5401 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5403 // Get the width of the mantissa. We don't want to hack on conversions that
5404 // might lose information from the integer, e.g. "i64 -> float"
5405 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5406 if (MantissaWidth == -1) return nullptr; // Unknown.
5408 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5410 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5412 if (I.isEquality()) {
5413 FCmpInst::Predicate P = I.getPredicate();
5414 bool IsExact = false;
5415 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
5416 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
5418 // If the floating point constant isn't an integer value, we know if we will
5419 // ever compare equal / not equal to it.
5420 if (!IsExact) {
5421 // TODO: Can never be -0.0 and other non-representable values
5422 APFloat RHSRoundInt(RHS);
5423 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
5424 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
5425 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
5426 return replaceInstUsesWith(I, Builder.getFalse());
5428 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
5429 return replaceInstUsesWith(I, Builder.getTrue());
5433 // TODO: If the constant is exactly representable, is it always OK to do
5434 // equality compares as integer?
5437 // Check to see that the input is converted from an integer type that is small
5438 // enough that preserves all bits. TODO: check here for "known" sign bits.
5439 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5440 unsigned InputSize = IntTy->getScalarSizeInBits();
5442 // Following test does NOT adjust InputSize downwards for signed inputs,
5443 // because the most negative value still requires all the mantissa bits
5444 // to distinguish it from one less than that value.
5445 if ((int)InputSize > MantissaWidth) {
5446 // Conversion would lose accuracy. Check if loss can impact comparison.
5447 int Exp = ilogb(RHS);
5448 if (Exp == APFloat::IEK_Inf) {
5449 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
5450 if (MaxExponent < (int)InputSize - !LHSUnsigned)
5451 // Conversion could create infinity.
5452 return nullptr;
5453 } else {
5454 // Note that if RHS is zero or NaN, then Exp is negative
5455 // and first condition is trivially false.
5456 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
5457 // Conversion could affect comparison.
5458 return nullptr;
5462 // Otherwise, we can potentially simplify the comparison. We know that it
5463 // will always come through as an integer value and we know the constant is
5464 // not a NAN (it would have been previously simplified).
5465 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5467 ICmpInst::Predicate Pred;
5468 switch (I.getPredicate()) {
5469 default: llvm_unreachable("Unexpected predicate!");
5470 case FCmpInst::FCMP_UEQ:
5471 case FCmpInst::FCMP_OEQ:
5472 Pred = ICmpInst::ICMP_EQ;
5473 break;
5474 case FCmpInst::FCMP_UGT:
5475 case FCmpInst::FCMP_OGT:
5476 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5477 break;
5478 case FCmpInst::FCMP_UGE:
5479 case FCmpInst::FCMP_OGE:
5480 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5481 break;
5482 case FCmpInst::FCMP_ULT:
5483 case FCmpInst::FCMP_OLT:
5484 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5485 break;
5486 case FCmpInst::FCMP_ULE:
5487 case FCmpInst::FCMP_OLE:
5488 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5489 break;
5490 case FCmpInst::FCMP_UNE:
5491 case FCmpInst::FCMP_ONE:
5492 Pred = ICmpInst::ICMP_NE;
5493 break;
5494 case FCmpInst::FCMP_ORD:
5495 return replaceInstUsesWith(I, Builder.getTrue());
5496 case FCmpInst::FCMP_UNO:
5497 return replaceInstUsesWith(I, Builder.getFalse());
5500 // Now we know that the APFloat is a normal number, zero or inf.
5502 // See if the FP constant is too large for the integer. For example,
5503 // comparing an i8 to 300.0.
5504 unsigned IntWidth = IntTy->getScalarSizeInBits();
5506 if (!LHSUnsigned) {
5507 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5508 // and large values.
5509 APFloat SMax(RHS.getSemantics());
5510 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5511 APFloat::rmNearestTiesToEven);
5512 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5513 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5514 Pred == ICmpInst::ICMP_SLE)
5515 return replaceInstUsesWith(I, Builder.getTrue());
5516 return replaceInstUsesWith(I, Builder.getFalse());
5518 } else {
5519 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5520 // +INF and large values.
5521 APFloat UMax(RHS.getSemantics());
5522 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5523 APFloat::rmNearestTiesToEven);
5524 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5525 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5526 Pred == ICmpInst::ICMP_ULE)
5527 return replaceInstUsesWith(I, Builder.getTrue());
5528 return replaceInstUsesWith(I, Builder.getFalse());
5532 if (!LHSUnsigned) {
5533 // See if the RHS value is < SignedMin.
5534 APFloat SMin(RHS.getSemantics());
5535 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5536 APFloat::rmNearestTiesToEven);
5537 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5538 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5539 Pred == ICmpInst::ICMP_SGE)
5540 return replaceInstUsesWith(I, Builder.getTrue());
5541 return replaceInstUsesWith(I, Builder.getFalse());
5543 } else {
5544 // See if the RHS value is < UnsignedMin.
5545 APFloat SMin(RHS.getSemantics());
5546 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
5547 APFloat::rmNearestTiesToEven);
5548 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
5549 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
5550 Pred == ICmpInst::ICMP_UGE)
5551 return replaceInstUsesWith(I, Builder.getTrue());
5552 return replaceInstUsesWith(I, Builder.getFalse());
5556 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5557 // [0, UMAX], but it may still be fractional. See if it is fractional by
5558 // casting the FP value to the integer value and back, checking for equality.
5559 // Don't do this for zero, because -0.0 is not fractional.
5560 Constant *RHSInt = LHSUnsigned
5561 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5562 : ConstantExpr::getFPToSI(RHSC, IntTy);
5563 if (!RHS.isZero()) {
5564 bool Equal = LHSUnsigned
5565 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5566 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5567 if (!Equal) {
5568 // If we had a comparison against a fractional value, we have to adjust
5569 // the compare predicate and sometimes the value. RHSC is rounded towards
5570 // zero at this point.
5571 switch (Pred) {
5572 default: llvm_unreachable("Unexpected integer comparison!");
5573 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5574 return replaceInstUsesWith(I, Builder.getTrue());
5575 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5576 return replaceInstUsesWith(I, Builder.getFalse());
5577 case ICmpInst::ICMP_ULE:
5578 // (float)int <= 4.4 --> int <= 4
5579 // (float)int <= -4.4 --> false
5580 if (RHS.isNegative())
5581 return replaceInstUsesWith(I, Builder.getFalse());
5582 break;
5583 case ICmpInst::ICMP_SLE:
5584 // (float)int <= 4.4 --> int <= 4
5585 // (float)int <= -4.4 --> int < -4
5586 if (RHS.isNegative())
5587 Pred = ICmpInst::ICMP_SLT;
5588 break;
5589 case ICmpInst::ICMP_ULT:
5590 // (float)int < -4.4 --> false
5591 // (float)int < 4.4 --> int <= 4
5592 if (RHS.isNegative())
5593 return replaceInstUsesWith(I, Builder.getFalse());
5594 Pred = ICmpInst::ICMP_ULE;
5595 break;
5596 case ICmpInst::ICMP_SLT:
5597 // (float)int < -4.4 --> int < -4
5598 // (float)int < 4.4 --> int <= 4
5599 if (!RHS.isNegative())
5600 Pred = ICmpInst::ICMP_SLE;
5601 break;
5602 case ICmpInst::ICMP_UGT:
5603 // (float)int > 4.4 --> int > 4
5604 // (float)int > -4.4 --> true
5605 if (RHS.isNegative())
5606 return replaceInstUsesWith(I, Builder.getTrue());
5607 break;
5608 case ICmpInst::ICMP_SGT:
5609 // (float)int > 4.4 --> int > 4
5610 // (float)int > -4.4 --> int >= -4
5611 if (RHS.isNegative())
5612 Pred = ICmpInst::ICMP_SGE;
5613 break;
5614 case ICmpInst::ICMP_UGE:
5615 // (float)int >= -4.4 --> true
5616 // (float)int >= 4.4 --> int > 4
5617 if (RHS.isNegative())
5618 return replaceInstUsesWith(I, Builder.getTrue());
5619 Pred = ICmpInst::ICMP_UGT;
5620 break;
5621 case ICmpInst::ICMP_SGE:
5622 // (float)int >= -4.4 --> int >= -4
5623 // (float)int >= 4.4 --> int > 4
5624 if (!RHS.isNegative())
5625 Pred = ICmpInst::ICMP_SGT;
5626 break;
5631 // Lower this FP comparison into an appropriate integer version of the
5632 // comparison.
5633 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5636 /// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
5637 static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI,
5638 Constant *RHSC) {
5639 // When C is not 0.0 and infinities are not allowed:
5640 // (C / X) < 0.0 is a sign-bit test of X
5641 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
5642 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
5644 // Proof:
5645 // Multiply (C / X) < 0.0 by X * X / C.
5646 // - X is non zero, if it is the flag 'ninf' is violated.
5647 // - C defines the sign of X * X * C. Thus it also defines whether to swap
5648 // the predicate. C is also non zero by definition.
5650 // Thus X * X / C is non zero and the transformation is valid. [qed]
5652 FCmpInst::Predicate Pred = I.getPredicate();
5654 // Check that predicates are valid.
5655 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
5656 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
5657 return nullptr;
5659 // Check that RHS operand is zero.
5660 if (!match(RHSC, m_AnyZeroFP()))
5661 return nullptr;
5663 // Check fastmath flags ('ninf').
5664 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
5665 return nullptr;
5667 // Check the properties of the dividend. It must not be zero to avoid a
5668 // division by zero (see Proof).
5669 const APFloat *C;
5670 if (!match(LHSI->getOperand(0), m_APFloat(C)))
5671 return nullptr;
5673 if (C->isZero())
5674 return nullptr;
5676 // Get swapped predicate if necessary.
5677 if (C->isNegative())
5678 Pred = I.getSwappedPredicate();
5680 return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
5683 /// Optimize fabs(X) compared with zero.
5684 static Instruction *foldFabsWithFcmpZero(FCmpInst &I) {
5685 Value *X;
5686 if (!match(I.getOperand(0), m_Intrinsic<Intrinsic::fabs>(m_Value(X))) ||
5687 !match(I.getOperand(1), m_PosZeroFP()))
5688 return nullptr;
5690 auto replacePredAndOp0 = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
5691 I->setPredicate(P);
5692 I->setOperand(0, X);
5693 return I;
5696 switch (I.getPredicate()) {
5697 case FCmpInst::FCMP_UGE:
5698 case FCmpInst::FCMP_OLT:
5699 // fabs(X) >= 0.0 --> true
5700 // fabs(X) < 0.0 --> false
5701 llvm_unreachable("fcmp should have simplified");
5703 case FCmpInst::FCMP_OGT:
5704 // fabs(X) > 0.0 --> X != 0.0
5705 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
5707 case FCmpInst::FCMP_UGT:
5708 // fabs(X) u> 0.0 --> X u!= 0.0
5709 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
5711 case FCmpInst::FCMP_OLE:
5712 // fabs(X) <= 0.0 --> X == 0.0
5713 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
5715 case FCmpInst::FCMP_ULE:
5716 // fabs(X) u<= 0.0 --> X u== 0.0
5717 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
5719 case FCmpInst::FCMP_OGE:
5720 // fabs(X) >= 0.0 --> !isnan(X)
5721 assert(!I.hasNoNaNs() && "fcmp should have simplified");
5722 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
5724 case FCmpInst::FCMP_ULT:
5725 // fabs(X) u< 0.0 --> isnan(X)
5726 assert(!I.hasNoNaNs() && "fcmp should have simplified");
5727 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
5729 case FCmpInst::FCMP_OEQ:
5730 case FCmpInst::FCMP_UEQ:
5731 case FCmpInst::FCMP_ONE:
5732 case FCmpInst::FCMP_UNE:
5733 case FCmpInst::FCMP_ORD:
5734 case FCmpInst::FCMP_UNO:
5735 // Look through the fabs() because it doesn't change anything but the sign.
5736 // fabs(X) == 0.0 --> X == 0.0,
5737 // fabs(X) != 0.0 --> X != 0.0
5738 // isnan(fabs(X)) --> isnan(X)
5739 // !isnan(fabs(X) --> !isnan(X)
5740 return replacePredAndOp0(&I, I.getPredicate(), X);
5742 default:
5743 return nullptr;
5747 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5748 bool Changed = false;
5750 /// Orders the operands of the compare so that they are listed from most
5751 /// complex to least complex. This puts constants before unary operators,
5752 /// before binary operators.
5753 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
5754 I.swapOperands();
5755 Changed = true;
5758 const CmpInst::Predicate Pred = I.getPredicate();
5759 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5760 if (Value *V = SimplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
5761 SQ.getWithInstruction(&I)))
5762 return replaceInstUsesWith(I, V);
5764 // Simplify 'fcmp pred X, X'
5765 Type *OpType = Op0->getType();
5766 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
5767 if (Op0 == Op1) {
5768 switch (Pred) {
5769 default: break;
5770 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5771 case FCmpInst::FCMP_ULT: // True if unordered or less than
5772 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5773 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5774 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5775 I.setPredicate(FCmpInst::FCMP_UNO);
5776 I.setOperand(1, Constant::getNullValue(OpType));
5777 return &I;
5779 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5780 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5781 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5782 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5783 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5784 I.setPredicate(FCmpInst::FCMP_ORD);
5785 I.setOperand(1, Constant::getNullValue(OpType));
5786 return &I;
5790 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
5791 // then canonicalize the operand to 0.0.
5792 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
5793 if (!match(Op0, m_PosZeroFP()) && isKnownNeverNaN(Op0, &TLI)) {
5794 I.setOperand(0, ConstantFP::getNullValue(OpType));
5795 return &I;
5797 if (!match(Op1, m_PosZeroFP()) && isKnownNeverNaN(Op1, &TLI)) {
5798 I.setOperand(1, ConstantFP::getNullValue(OpType));
5799 return &I;
5803 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
5804 Value *X, *Y;
5805 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
5806 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
5808 // Test if the FCmpInst instruction is used exclusively by a select as
5809 // part of a minimum or maximum operation. If so, refrain from doing
5810 // any other folding. This helps out other analyses which understand
5811 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5812 // and CodeGen. And in this case, at least one of the comparison
5813 // operands has at least one user besides the compare (the select),
5814 // which would often largely negate the benefit of folding anyway.
5815 if (I.hasOneUse())
5816 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
5817 Value *A, *B;
5818 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
5819 if (SPR.Flavor != SPF_UNKNOWN)
5820 return nullptr;
5823 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
5824 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
5825 if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP())) {
5826 I.setOperand(1, ConstantFP::getNullValue(OpType));
5827 return &I;
5830 // Handle fcmp with instruction LHS and constant RHS.
5831 Instruction *LHSI;
5832 Constant *RHSC;
5833 if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
5834 switch (LHSI->getOpcode()) {
5835 case Instruction::PHI:
5836 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5837 // block. If in the same block, we're encouraging jump threading. If
5838 // not, we are just pessimizing the code by making an i1 phi.
5839 if (LHSI->getParent() == I.getParent())
5840 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
5841 return NV;
5842 break;
5843 case Instruction::SIToFP:
5844 case Instruction::UIToFP:
5845 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
5846 return NV;
5847 break;
5848 case Instruction::FDiv:
5849 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
5850 return NV;
5851 break;
5852 case Instruction::Load:
5853 if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
5854 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
5855 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
5856 !cast<LoadInst>(LHSI)->isVolatile())
5857 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
5858 return Res;
5859 break;
5863 if (Instruction *R = foldFabsWithFcmpZero(I))
5864 return R;
5866 if (match(Op0, m_FNeg(m_Value(X)))) {
5867 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
5868 Constant *C;
5869 if (match(Op1, m_Constant(C))) {
5870 Constant *NegC = ConstantExpr::getFNeg(C);
5871 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
5875 if (match(Op0, m_FPExt(m_Value(X)))) {
5876 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
5877 if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
5878 return new FCmpInst(Pred, X, Y, "", &I);
5880 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
5881 const APFloat *C;
5882 if (match(Op1, m_APFloat(C))) {
5883 const fltSemantics &FPSem =
5884 X->getType()->getScalarType()->getFltSemantics();
5885 bool Lossy;
5886 APFloat TruncC = *C;
5887 TruncC.convert(FPSem, APFloat::rmNearestTiesToEven, &Lossy);
5889 // Avoid lossy conversions and denormals.
5890 // Zero is a special case that's OK to convert.
5891 APFloat Fabs = TruncC;
5892 Fabs.clearSign();
5893 if (!Lossy &&
5894 ((Fabs.compare(APFloat::getSmallestNormalized(FPSem)) !=
5895 APFloat::cmpLessThan) || Fabs.isZero())) {
5896 Constant *NewC = ConstantFP::get(X->getType(), TruncC);
5897 return new FCmpInst(Pred, X, NewC, "", &I);
5902 if (I.getType()->isVectorTy())
5903 if (Instruction *Res = foldVectorCmp(I, Builder))
5904 return Res;
5906 return Changed ? &I : nullptr;