1 //===- InstCombineCompares.cpp --------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visitICmp and visitFCmp functions.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Analysis/MemoryBuiltins.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/Support/ConstantRange.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/PatternMatch.h"
23 #include "llvm/Target/TargetLibraryInfo.h"
25 using namespace PatternMatch;
27 static ConstantInt *getOne(Constant *C) {
28 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
31 /// AddOne - Add one to a ConstantInt
32 static Constant *AddOne(Constant *C) {
33 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
35 /// SubOne - Subtract one from a ConstantInt
36 static Constant *SubOne(Constant *C) {
37 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
40 static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
41 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
44 static bool HasAddOverflow(ConstantInt *Result,
45 ConstantInt *In1, ConstantInt *In2,
48 return Result->getValue().ult(In1->getValue());
50 if (In2->isNegative())
51 return Result->getValue().sgt(In1->getValue());
52 return Result->getValue().slt(In1->getValue());
55 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
56 /// overflowed for this type.
57 static bool AddWithOverflow(Constant *&Result, Constant *In1,
58 Constant *In2, bool IsSigned = false) {
59 Result = ConstantExpr::getAdd(In1, In2);
61 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
62 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
63 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
64 if (HasAddOverflow(ExtractElement(Result, Idx),
65 ExtractElement(In1, Idx),
66 ExtractElement(In2, Idx),
73 return HasAddOverflow(cast<ConstantInt>(Result),
74 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
78 static bool HasSubOverflow(ConstantInt *Result,
79 ConstantInt *In1, ConstantInt *In2,
82 return Result->getValue().ugt(In1->getValue());
84 if (In2->isNegative())
85 return Result->getValue().slt(In1->getValue());
87 return Result->getValue().sgt(In1->getValue());
90 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
91 /// overflowed for this type.
92 static bool SubWithOverflow(Constant *&Result, Constant *In1,
93 Constant *In2, bool IsSigned = false) {
94 Result = ConstantExpr::getSub(In1, In2);
96 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
97 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
98 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
99 if (HasSubOverflow(ExtractElement(Result, Idx),
100 ExtractElement(In1, Idx),
101 ExtractElement(In2, Idx),
108 return HasSubOverflow(cast<ConstantInt>(Result),
109 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
113 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
114 /// comparison only checks the sign bit. If it only checks the sign bit, set
115 /// TrueIfSigned if the result of the comparison is true when the input value is
117 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
118 bool &TrueIfSigned) {
120 case ICmpInst::ICMP_SLT: // True if LHS s< 0
122 return RHS->isZero();
123 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
125 return RHS->isAllOnesValue();
126 case ICmpInst::ICMP_SGT: // True if LHS s> -1
127 TrueIfSigned = false;
128 return RHS->isAllOnesValue();
129 case ICmpInst::ICMP_UGT:
130 // True if LHS u> RHS and RHS == high-bit-mask - 1
132 return RHS->isMaxValue(true);
133 case ICmpInst::ICMP_UGE:
134 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
136 return RHS->getValue().isSignBit();
142 /// Returns true if the exploded icmp can be expressed as a signed comparison
143 /// to zero and updates the predicate accordingly.
144 /// The signedness of the comparison is preserved.
145 static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
146 if (!ICmpInst::isSigned(pred))
150 return ICmpInst::isRelational(pred);
153 if (pred == ICmpInst::ICMP_SLT) {
154 pred = ICmpInst::ICMP_SLE;
157 } else if (RHS->isAllOnesValue()) {
158 if (pred == ICmpInst::ICMP_SGT) {
159 pred = ICmpInst::ICMP_SGE;
167 // isHighOnes - Return true if the constant is of the form 1+0+.
168 // This is the same as lowones(~X).
169 static bool isHighOnes(const ConstantInt *CI) {
170 return (~CI->getValue() + 1).isPowerOf2();
173 /// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
174 /// set of known zero and one bits, compute the maximum and minimum values that
175 /// could have the specified known zero and known one bits, returning them in
177 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
178 const APInt& KnownOne,
179 APInt& Min, APInt& Max) {
180 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
181 KnownZero.getBitWidth() == Min.getBitWidth() &&
182 KnownZero.getBitWidth() == Max.getBitWidth() &&
183 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
184 APInt UnknownBits = ~(KnownZero|KnownOne);
186 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
187 // bit if it is unknown.
189 Max = KnownOne|UnknownBits;
191 if (UnknownBits.isNegative()) { // Sign bit is unknown
192 Min.setBit(Min.getBitWidth()-1);
193 Max.clearBit(Max.getBitWidth()-1);
197 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
198 // a set of known zero and one bits, compute the maximum and minimum values that
199 // could have the specified known zero and known one bits, returning them in
201 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
202 const APInt &KnownOne,
203 APInt &Min, APInt &Max) {
204 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
205 KnownZero.getBitWidth() == Min.getBitWidth() &&
206 KnownZero.getBitWidth() == Max.getBitWidth() &&
207 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
208 APInt UnknownBits = ~(KnownZero|KnownOne);
210 // The minimum value is when the unknown bits are all zeros.
212 // The maximum value is when the unknown bits are all ones.
213 Max = KnownOne|UnknownBits;
218 /// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
219 /// cmp pred (load (gep GV, ...)), cmpcst
220 /// where GV is a global variable with a constant initializer. Try to simplify
221 /// this into some simple computation that does not need the load. For example
222 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
224 /// If AndCst is non-null, then the loaded value is masked with that constant
225 /// before doing the comparison. This handles cases like "A[i]&4 == 0".
226 Instruction *InstCombiner::
227 FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
228 CmpInst &ICI, ConstantInt *AndCst) {
229 // We need TD information to know the pointer size unless this is inbounds.
230 if (!GEP->isInBounds() && TD == 0)
233 Constant *Init = GV->getInitializer();
234 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
237 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
238 if (ArrayElementCount > 1024) return 0; // Don't blow up on huge arrays.
240 // There are many forms of this optimization we can handle, for now, just do
241 // the simple index into a single-dimensional array.
243 // Require: GEP GV, 0, i {{, constant indices}}
244 if (GEP->getNumOperands() < 3 ||
245 !isa<ConstantInt>(GEP->getOperand(1)) ||
246 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
247 isa<Constant>(GEP->getOperand(2)))
250 // Check that indices after the variable are constants and in-range for the
251 // type they index. Collect the indices. This is typically for arrays of
253 SmallVector<unsigned, 4> LaterIndices;
255 Type *EltTy = Init->getType()->getArrayElementType();
256 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
257 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
258 if (Idx == 0) return 0; // Variable index.
260 uint64_t IdxVal = Idx->getZExtValue();
261 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
263 if (StructType *STy = dyn_cast<StructType>(EltTy))
264 EltTy = STy->getElementType(IdxVal);
265 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
266 if (IdxVal >= ATy->getNumElements()) return 0;
267 EltTy = ATy->getElementType();
269 return 0; // Unknown type.
272 LaterIndices.push_back(IdxVal);
275 enum { Overdefined = -3, Undefined = -2 };
277 // Variables for our state machines.
279 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
280 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
281 // and 87 is the second (and last) index. FirstTrueElement is -2 when
282 // undefined, otherwise set to the first true element. SecondTrueElement is
283 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
284 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
286 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
287 // form "i != 47 & i != 87". Same state transitions as for true elements.
288 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
290 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
291 /// define a state machine that triggers for ranges of values that the index
292 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
293 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
294 /// index in the range (inclusive). We use -2 for undefined here because we
295 /// use relative comparisons and don't want 0-1 to match -1.
296 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
298 // MagicBitvector - This is a magic bitvector where we set a bit if the
299 // comparison is true for element 'i'. If there are 64 elements or less in
300 // the array, this will fully represent all the comparison results.
301 uint64_t MagicBitvector = 0;
304 // Scan the array and see if one of our patterns matches.
305 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
306 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
307 Constant *Elt = Init->getAggregateElement(i);
308 if (Elt == 0) return 0;
310 // If this is indexing an array of structures, get the structure element.
311 if (!LaterIndices.empty())
312 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
314 // If the element is masked, handle it.
315 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
317 // Find out if the comparison would be true or false for the i'th element.
318 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
319 CompareRHS, TD, TLI);
320 // If the result is undef for this element, ignore it.
321 if (isa<UndefValue>(C)) {
322 // Extend range state machines to cover this element in case there is an
323 // undef in the middle of the range.
324 if (TrueRangeEnd == (int)i-1)
326 if (FalseRangeEnd == (int)i-1)
331 // If we can't compute the result for any of the elements, we have to give
332 // up evaluating the entire conditional.
333 if (!isa<ConstantInt>(C)) return 0;
335 // Otherwise, we know if the comparison is true or false for this element,
336 // update our state machines.
337 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
339 // State machine for single/double/range index comparison.
341 // Update the TrueElement state machine.
342 if (FirstTrueElement == Undefined)
343 FirstTrueElement = TrueRangeEnd = i; // First true element.
345 // Update double-compare state machine.
346 if (SecondTrueElement == Undefined)
347 SecondTrueElement = i;
349 SecondTrueElement = Overdefined;
351 // Update range state machine.
352 if (TrueRangeEnd == (int)i-1)
355 TrueRangeEnd = Overdefined;
358 // Update the FalseElement state machine.
359 if (FirstFalseElement == Undefined)
360 FirstFalseElement = FalseRangeEnd = i; // First false element.
362 // Update double-compare state machine.
363 if (SecondFalseElement == Undefined)
364 SecondFalseElement = i;
366 SecondFalseElement = Overdefined;
368 // Update range state machine.
369 if (FalseRangeEnd == (int)i-1)
372 FalseRangeEnd = Overdefined;
377 // If this element is in range, update our magic bitvector.
378 if (i < 64 && IsTrueForElt)
379 MagicBitvector |= 1ULL << i;
381 // If all of our states become overdefined, bail out early. Since the
382 // predicate is expensive, only check it every 8 elements. This is only
383 // really useful for really huge arrays.
384 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
385 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
386 FalseRangeEnd == Overdefined)
390 // Now that we've scanned the entire array, emit our new comparison(s). We
391 // order the state machines in complexity of the generated code.
392 Value *Idx = GEP->getOperand(2);
394 // If the index is larger than the pointer size of the target, truncate the
395 // index down like the GEP would do implicitly. We don't have to do this for
396 // an inbounds GEP because the index can't be out of range.
397 if (!GEP->isInBounds()) {
398 Type *IntPtrTy = TD->getIntPtrType(GEP->getType());
399 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
400 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
401 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
404 // If the comparison is only true for one or two elements, emit direct
406 if (SecondTrueElement != Overdefined) {
407 // None true -> false.
408 if (FirstTrueElement == Undefined)
409 return ReplaceInstUsesWith(ICI, Builder->getFalse());
411 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
413 // True for one element -> 'i == 47'.
414 if (SecondTrueElement == Undefined)
415 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
417 // True for two elements -> 'i == 47 | i == 72'.
418 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
419 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
420 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
421 return BinaryOperator::CreateOr(C1, C2);
424 // If the comparison is only false for one or two elements, emit direct
426 if (SecondFalseElement != Overdefined) {
427 // None false -> true.
428 if (FirstFalseElement == Undefined)
429 return ReplaceInstUsesWith(ICI, Builder->getTrue());
431 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
433 // False for one element -> 'i != 47'.
434 if (SecondFalseElement == Undefined)
435 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
437 // False for two elements -> 'i != 47 & i != 72'.
438 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
439 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
440 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
441 return BinaryOperator::CreateAnd(C1, C2);
444 // If the comparison can be replaced with a range comparison for the elements
445 // where it is true, emit the range check.
446 if (TrueRangeEnd != Overdefined) {
447 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
449 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
450 if (FirstTrueElement) {
451 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
452 Idx = Builder->CreateAdd(Idx, Offs);
455 Value *End = ConstantInt::get(Idx->getType(),
456 TrueRangeEnd-FirstTrueElement+1);
457 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
460 // False range check.
461 if (FalseRangeEnd != Overdefined) {
462 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
463 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
464 if (FirstFalseElement) {
465 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
466 Idx = Builder->CreateAdd(Idx, Offs);
469 Value *End = ConstantInt::get(Idx->getType(),
470 FalseRangeEnd-FirstFalseElement);
471 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
475 // If a magic bitvector captures the entire comparison state
476 // of this load, replace it with computation that does:
477 // ((magic_cst >> i) & 1) != 0
481 // Look for an appropriate type:
482 // - The type of Idx if the magic fits
483 // - The smallest fitting legal type if we have a DataLayout
485 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
488 Ty = TD->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
489 else if (ArrayElementCount <= 32)
490 Ty = Type::getInt32Ty(Init->getContext());
493 Value *V = Builder->CreateIntCast(Idx, Ty, false);
494 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
495 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
496 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
504 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
505 /// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
506 /// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
507 /// be complex, and scales are involved. The above expression would also be
508 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
509 /// This later form is less amenable to optimization though, and we are allowed
510 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
512 /// If we can't emit an optimized form for this expression, this returns null.
514 static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
515 DataLayout &TD = *IC.getDataLayout();
516 gep_type_iterator GTI = gep_type_begin(GEP);
518 // Check to see if this gep only has a single variable index. If so, and if
519 // any constant indices are a multiple of its scale, then we can compute this
520 // in terms of the scale of the variable index. For example, if the GEP
521 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
522 // because the expression will cross zero at the same point.
523 unsigned i, e = GEP->getNumOperands();
525 for (i = 1; i != e; ++i, ++GTI) {
526 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
527 // Compute the aggregate offset of constant indices.
528 if (CI->isZero()) continue;
530 // Handle a struct index, which adds its field offset to the pointer.
531 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
532 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
534 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
535 Offset += Size*CI->getSExtValue();
538 // Found our variable index.
543 // If there are no variable indices, we must have a constant offset, just
544 // evaluate it the general way.
545 if (i == e) return 0;
547 Value *VariableIdx = GEP->getOperand(i);
548 // Determine the scale factor of the variable element. For example, this is
549 // 4 if the variable index is into an array of i32.
550 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
552 // Verify that there are no other variable indices. If so, emit the hard way.
553 for (++i, ++GTI; i != e; ++i, ++GTI) {
554 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
557 // Compute the aggregate offset of constant indices.
558 if (CI->isZero()) continue;
560 // Handle a struct index, which adds its field offset to the pointer.
561 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
562 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
564 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
565 Offset += Size*CI->getSExtValue();
571 // Okay, we know we have a single variable index, which must be a
572 // pointer/array/vector index. If there is no offset, life is simple, return
574 Type *IntPtrTy = TD.getIntPtrType(GEP->getOperand(0)->getType());
575 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
577 // Cast to intptrty in case a truncation occurs. If an extension is needed,
578 // we don't need to bother extending: the extension won't affect where the
579 // computation crosses zero.
580 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
581 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
586 // Otherwise, there is an index. The computation we will do will be modulo
587 // the pointer size, so get it.
588 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
590 Offset &= PtrSizeMask;
591 VariableScale &= PtrSizeMask;
593 // To do this transformation, any constant index must be a multiple of the
594 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
595 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
596 // multiple of the variable scale.
597 int64_t NewOffs = Offset / (int64_t)VariableScale;
598 if (Offset != NewOffs*(int64_t)VariableScale)
601 // Okay, we can do this evaluation. Start by converting the index to intptr.
602 if (VariableIdx->getType() != IntPtrTy)
603 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
605 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
606 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
609 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
610 /// else. At this point we know that the GEP is on the LHS of the comparison.
611 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
612 ICmpInst::Predicate Cond,
614 // Don't transform signed compares of GEPs into index compares. Even if the
615 // GEP is inbounds, the final add of the base pointer can have signed overflow
616 // and would change the result of the icmp.
617 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
618 // the maximum signed value for the pointer type.
619 if (ICmpInst::isSigned(Cond))
622 // Look through bitcasts.
623 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
624 RHS = BCI->getOperand(0);
626 Value *PtrBase = GEPLHS->getOperand(0);
627 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
628 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
629 // This transformation (ignoring the base and scales) is valid because we
630 // know pointers can't overflow since the gep is inbounds. See if we can
631 // output an optimized form.
632 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
634 // If not, synthesize the offset the hard way.
636 Offset = EmitGEPOffset(GEPLHS);
637 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
638 Constant::getNullValue(Offset->getType()));
639 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
640 // If the base pointers are different, but the indices are the same, just
641 // compare the base pointer.
642 if (PtrBase != GEPRHS->getOperand(0)) {
643 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
644 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
645 GEPRHS->getOperand(0)->getType();
647 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
648 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
649 IndicesTheSame = false;
653 // If all indices are the same, just compare the base pointers.
655 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
657 // If we're comparing GEPs with two base pointers that only differ in type
658 // and both GEPs have only constant indices or just one use, then fold
659 // the compare with the adjusted indices.
660 if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
661 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
662 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
663 PtrBase->stripPointerCasts() ==
664 GEPRHS->getOperand(0)->stripPointerCasts()) {
665 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
666 EmitGEPOffset(GEPLHS),
667 EmitGEPOffset(GEPRHS));
668 return ReplaceInstUsesWith(I, Cmp);
671 // Otherwise, the base pointers are different and the indices are
672 // different, bail out.
676 // If one of the GEPs has all zero indices, recurse.
677 bool AllZeros = true;
678 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
679 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
680 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
685 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
686 ICmpInst::getSwappedPredicate(Cond), I);
688 // If the other GEP has all zero indices, recurse.
690 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
691 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
692 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
697 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
699 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
700 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
701 // If the GEPs only differ by one index, compare it.
702 unsigned NumDifferences = 0; // Keep track of # differences.
703 unsigned DiffOperand = 0; // The operand that differs.
704 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
705 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
706 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
707 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
708 // Irreconcilable differences.
712 if (NumDifferences++) break;
717 if (NumDifferences == 0) // SAME GEP?
718 return ReplaceInstUsesWith(I, // No comparison is needed here.
719 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
721 else if (NumDifferences == 1 && GEPsInBounds) {
722 Value *LHSV = GEPLHS->getOperand(DiffOperand);
723 Value *RHSV = GEPRHS->getOperand(DiffOperand);
724 // Make sure we do a signed comparison here.
725 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
729 // Only lower this if the icmp is the only user of the GEP or if we expect
730 // the result to fold to a constant!
733 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
734 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
735 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
736 Value *L = EmitGEPOffset(GEPLHS);
737 Value *R = EmitGEPOffset(GEPRHS);
738 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
744 /// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
745 Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
746 Value *X, ConstantInt *CI,
747 ICmpInst::Predicate Pred) {
748 // If we have X+0, exit early (simplifying logic below) and let it get folded
749 // elsewhere. icmp X+0, X -> icmp X, X
751 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
752 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
755 // (X+4) == X -> false.
756 if (Pred == ICmpInst::ICMP_EQ)
757 return ReplaceInstUsesWith(ICI, Builder->getFalse());
759 // (X+4) != X -> true.
760 if (Pred == ICmpInst::ICMP_NE)
761 return ReplaceInstUsesWith(ICI, Builder->getTrue());
763 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
764 // so the values can never be equal. Similarly for all other "or equals"
767 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
768 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
769 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
770 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
772 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
773 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
776 // (X+1) >u X --> X <u (0-1) --> X != 255
777 // (X+2) >u X --> X <u (0-2) --> X <u 254
778 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
779 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
780 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
782 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
783 ConstantInt *SMax = ConstantInt::get(X->getContext(),
784 APInt::getSignedMaxValue(BitWidth));
786 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
787 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
788 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
789 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
790 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
791 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
792 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
793 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
795 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
796 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
797 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
798 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
799 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
800 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
802 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
803 Constant *C = Builder->getInt(CI->getValue()-1);
804 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
807 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
808 /// and CmpRHS are both known to be integer constants.
809 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
810 ConstantInt *DivRHS) {
811 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
812 const APInt &CmpRHSV = CmpRHS->getValue();
814 // FIXME: If the operand types don't match the type of the divide
815 // then don't attempt this transform. The code below doesn't have the
816 // logic to deal with a signed divide and an unsigned compare (and
817 // vice versa). This is because (x /s C1) <s C2 produces different
818 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
819 // (x /u C1) <u C2. Simply casting the operands and result won't
820 // work. :( The if statement below tests that condition and bails
822 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
823 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
825 if (DivRHS->isZero())
826 return 0; // The ProdOV computation fails on divide by zero.
827 if (DivIsSigned && DivRHS->isAllOnesValue())
828 return 0; // The overflow computation also screws up here
829 if (DivRHS->isOne()) {
830 // This eliminates some funny cases with INT_MIN.
831 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
835 // Compute Prod = CI * DivRHS. We are essentially solving an equation
836 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
837 // C2 (CI). By solving for X we can turn this into a range check
838 // instead of computing a divide.
839 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
841 // Determine if the product overflows by seeing if the product is
842 // not equal to the divide. Make sure we do the same kind of divide
843 // as in the LHS instruction that we're folding.
844 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
845 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
847 // Get the ICmp opcode
848 ICmpInst::Predicate Pred = ICI.getPredicate();
850 /// If the division is known to be exact, then there is no remainder from the
851 /// divide, so the covered range size is unit, otherwise it is the divisor.
852 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
854 // Figure out the interval that is being checked. For example, a comparison
855 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
856 // Compute this interval based on the constants involved and the signedness of
857 // the compare/divide. This computes a half-open interval, keeping track of
858 // whether either value in the interval overflows. After analysis each
859 // overflow variable is set to 0 if it's corresponding bound variable is valid
860 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
861 int LoOverflow = 0, HiOverflow = 0;
862 Constant *LoBound = 0, *HiBound = 0;
864 if (!DivIsSigned) { // udiv
865 // e.g. X/5 op 3 --> [15, 20)
867 HiOverflow = LoOverflow = ProdOV;
869 // If this is not an exact divide, then many values in the range collapse
870 // to the same result value.
871 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
874 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
875 if (CmpRHSV == 0) { // (X / pos) op 0
876 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
877 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
879 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
880 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
881 HiOverflow = LoOverflow = ProdOV;
883 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
884 } else { // (X / pos) op neg
885 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
886 HiBound = AddOne(Prod);
887 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
889 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
890 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
893 } else if (DivRHS->isNegative()) { // Divisor is < 0.
895 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
896 if (CmpRHSV == 0) { // (X / neg) op 0
897 // e.g. X/-5 op 0 --> [-4, 5)
898 LoBound = AddOne(RangeSize);
899 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
900 if (HiBound == DivRHS) { // -INTMIN = INTMIN
901 HiOverflow = 1; // [INTMIN+1, overflow)
902 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
904 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
905 // e.g. X/-5 op 3 --> [-19, -14)
906 HiBound = AddOne(Prod);
907 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
909 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
910 } else { // (X / neg) op neg
911 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
912 LoOverflow = HiOverflow = ProdOV;
914 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
917 // Dividing by a negative swaps the condition. LT <-> GT
918 Pred = ICmpInst::getSwappedPredicate(Pred);
921 Value *X = DivI->getOperand(0);
923 default: llvm_unreachable("Unhandled icmp opcode!");
924 case ICmpInst::ICMP_EQ:
925 if (LoOverflow && HiOverflow)
926 return ReplaceInstUsesWith(ICI, Builder->getFalse());
928 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
929 ICmpInst::ICMP_UGE, X, LoBound);
931 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
932 ICmpInst::ICMP_ULT, X, HiBound);
933 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
935 case ICmpInst::ICMP_NE:
936 if (LoOverflow && HiOverflow)
937 return ReplaceInstUsesWith(ICI, Builder->getTrue());
939 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
940 ICmpInst::ICMP_ULT, X, LoBound);
942 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
943 ICmpInst::ICMP_UGE, X, HiBound);
944 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
945 DivIsSigned, false));
946 case ICmpInst::ICMP_ULT:
947 case ICmpInst::ICMP_SLT:
948 if (LoOverflow == +1) // Low bound is greater than input range.
949 return ReplaceInstUsesWith(ICI, Builder->getTrue());
950 if (LoOverflow == -1) // Low bound is less than input range.
951 return ReplaceInstUsesWith(ICI, Builder->getFalse());
952 return new ICmpInst(Pred, X, LoBound);
953 case ICmpInst::ICMP_UGT:
954 case ICmpInst::ICMP_SGT:
955 if (HiOverflow == +1) // High bound greater than input range.
956 return ReplaceInstUsesWith(ICI, Builder->getFalse());
957 if (HiOverflow == -1) // High bound less than input range.
958 return ReplaceInstUsesWith(ICI, Builder->getTrue());
959 if (Pred == ICmpInst::ICMP_UGT)
960 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
961 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
965 /// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
966 Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
967 ConstantInt *ShAmt) {
968 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
970 // Check that the shift amount is in range. If not, don't perform
971 // undefined shifts. When the shift is visited it will be
973 uint32_t TypeBits = CmpRHSV.getBitWidth();
974 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
975 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
978 if (!ICI.isEquality()) {
979 // If we have an unsigned comparison and an ashr, we can't simplify this.
980 // Similarly for signed comparisons with lshr.
981 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
984 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
985 // by a power of 2. Since we already have logic to simplify these,
986 // transform to div and then simplify the resultant comparison.
987 if (Shr->getOpcode() == Instruction::AShr &&
988 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
991 // Revisit the shift (to delete it).
995 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
998 Shr->getOpcode() == Instruction::AShr ?
999 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
1000 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
1002 ICI.setOperand(0, Tmp);
1004 // If the builder folded the binop, just return it.
1005 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
1009 // Otherwise, fold this div/compare.
1010 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1011 TheDiv->getOpcode() == Instruction::UDiv);
1013 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1014 assert(Res && "This div/cst should have folded!");
1019 // If we are comparing against bits always shifted out, the
1020 // comparison cannot succeed.
1021 APInt Comp = CmpRHSV << ShAmtVal;
1022 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
1023 if (Shr->getOpcode() == Instruction::LShr)
1024 Comp = Comp.lshr(ShAmtVal);
1026 Comp = Comp.ashr(ShAmtVal);
1028 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1029 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1030 Constant *Cst = Builder->getInt1(IsICMP_NE);
1031 return ReplaceInstUsesWith(ICI, Cst);
1034 // Otherwise, check to see if the bits shifted out are known to be zero.
1035 // If so, we can compare against the unshifted value:
1036 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
1037 if (Shr->hasOneUse() && Shr->isExact())
1038 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
1040 if (Shr->hasOneUse()) {
1041 // Otherwise strength reduce the shift into an and.
1042 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1043 Constant *Mask = Builder->getInt(Val);
1045 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1046 Mask, Shr->getName()+".mask");
1047 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1053 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1055 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1058 const APInt &RHSV = RHS->getValue();
1060 switch (LHSI->getOpcode()) {
1061 case Instruction::Trunc:
1062 if (ICI.isEquality() && LHSI->hasOneUse()) {
1063 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1064 // of the high bits truncated out of x are known.
1065 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1066 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
1067 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
1068 ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
1070 // If all the high bits are known, we can do this xform.
1071 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1072 // Pull in the high bits from known-ones set.
1073 APInt NewRHS = RHS->getValue().zext(SrcBits);
1074 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
1075 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1076 Builder->getInt(NewRHS));
1081 case Instruction::Xor: // (icmp pred (xor X, XorCst), CI)
1082 if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1083 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1085 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1086 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1087 Value *CompareVal = LHSI->getOperand(0);
1089 // If the sign bit of the XorCst is not set, there is no change to
1090 // the operation, just stop using the Xor.
1091 if (!XorCst->isNegative()) {
1092 ICI.setOperand(0, CompareVal);
1097 // Was the old condition true if the operand is positive?
1098 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
1100 // If so, the new one isn't.
1101 isTrueIfPositive ^= true;
1103 if (isTrueIfPositive)
1104 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1107 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1111 if (LHSI->hasOneUse()) {
1112 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1113 if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1114 const APInt &SignBit = XorCst->getValue();
1115 ICmpInst::Predicate Pred = ICI.isSigned()
1116 ? ICI.getUnsignedPredicate()
1117 : ICI.getSignedPredicate();
1118 return new ICmpInst(Pred, LHSI->getOperand(0),
1119 Builder->getInt(RHSV ^ SignBit));
1122 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
1123 if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1124 const APInt &NotSignBit = XorCst->getValue();
1125 ICmpInst::Predicate Pred = ICI.isSigned()
1126 ? ICI.getUnsignedPredicate()
1127 : ICI.getSignedPredicate();
1128 Pred = ICI.getSwappedPredicate(Pred);
1129 return new ICmpInst(Pred, LHSI->getOperand(0),
1130 Builder->getInt(RHSV ^ NotSignBit));
1134 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1135 // iff -C is a power of 2
1136 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
1137 XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1138 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
1140 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1141 // iff -C is a power of 2
1142 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
1143 XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1144 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
1147 case Instruction::And: // (icmp pred (and X, AndCst), RHS)
1148 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1149 LHSI->getOperand(0)->hasOneUse()) {
1150 ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
1152 // If the LHS is an AND of a truncating cast, we can widen the
1153 // and/compare to be the input width without changing the value
1154 // produced, eliminating a cast.
1155 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1156 // We can do this transformation if either the AND constant does not
1157 // have its sign bit set or if it is an equality comparison.
1158 // Extending a relational comparison when we're checking the sign
1159 // bit would not work.
1160 if (ICI.isEquality() ||
1161 (!AndCst->isNegative() && RHSV.isNonNegative())) {
1163 Builder->CreateAnd(Cast->getOperand(0),
1164 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
1165 NewAnd->takeName(LHSI);
1166 return new ICmpInst(ICI.getPredicate(), NewAnd,
1167 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
1171 // If the LHS is an AND of a zext, and we have an equality compare, we can
1172 // shrink the and/compare to the smaller type, eliminating the cast.
1173 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
1174 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
1175 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1176 // should fold the icmp to true/false in that case.
1177 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1179 Builder->CreateAnd(Cast->getOperand(0),
1180 ConstantExpr::getTrunc(AndCst, Ty));
1181 NewAnd->takeName(LHSI);
1182 return new ICmpInst(ICI.getPredicate(), NewAnd,
1183 ConstantExpr::getTrunc(RHS, Ty));
1187 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1188 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1189 // happens a LOT in code produced by the C front-end, for bitfield
1191 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1192 if (Shift && !Shift->isShift())
1196 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
1198 // We can fold this as long as we can't shift unknown bits
1199 // into the mask. This can happen with signed shift
1200 // rights, as they sign-extend. With logical shifts,
1201 // we must still make sure the comparison is not signed
1202 // because we are effectively changing the
1203 // position of the sign bit (PR17827).
1204 // TODO: We can relax these constraints a bit more.
1206 bool CanFold = false;
1207 unsigned ShiftOpcode = Shift->getOpcode();
1208 if (ShiftOpcode == Instruction::AShr) {
1209 // To test for the bad case of the signed shr, see if any
1210 // of the bits shifted in could be tested after the mask.
1211 Type *ShiftType = Shift->getType();
1212 Type *AndType = AndCst->getType();
1214 unsigned ShiftBitWidth = ShiftType->getPrimitiveSizeInBits();
1215 unsigned AndBitWidth = AndType->getPrimitiveSizeInBits();
1217 int ShAmtVal = ShiftBitWidth - ShAmt->getLimitedValue(ShiftBitWidth);
1219 if ((APInt::getHighBitsSet(AndBitWidth, AndBitWidth - ShAmtVal) &
1220 AndCst->getValue()) == 0)
1222 } else if (ShiftOpcode == Instruction::Shl ||
1223 ShiftOpcode == Instruction::LShr) {
1224 CanFold = !ICI.isSigned();
1229 if (ShiftOpcode == Instruction::Shl)
1230 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1232 NewCst = ConstantExpr::getShl(RHS, ShAmt);
1234 // Check to see if we are shifting out any of the bits being
1236 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
1237 // If we shifted bits out, the fold is not going to work out.
1238 // As a special case, check to see if this means that the
1239 // result is always true or false now.
1240 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1241 return ReplaceInstUsesWith(ICI, Builder->getFalse());
1242 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1243 return ReplaceInstUsesWith(ICI, Builder->getTrue());
1245 ICI.setOperand(1, NewCst);
1246 Constant *NewAndCst;
1247 if (ShiftOpcode == Instruction::Shl)
1248 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
1250 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1251 LHSI->setOperand(1, NewAndCst);
1252 LHSI->setOperand(0, Shift->getOperand(0));
1253 Worklist.Add(Shift); // Shift is dead.
1259 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1260 // preferable because it allows the C<<Y expression to be hoisted out
1261 // of a loop if Y is invariant and X is not.
1262 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1263 ICI.isEquality() && !Shift->isArithmeticShift() &&
1264 !isa<Constant>(Shift->getOperand(0))) {
1267 if (Shift->getOpcode() == Instruction::LShr) {
1268 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
1270 // Insert a logical shift.
1271 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
1274 // Compute X & (C << Y).
1276 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1278 ICI.setOperand(0, NewAnd);
1282 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1283 // bit set in (X & AndCst) will produce a result greater than RHSV.
1284 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
1285 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1286 if ((NTZ < AndCst->getBitWidth()) &&
1287 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
1288 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1289 Constant::getNullValue(RHS->getType()));
1293 // Try to optimize things like "A[i]&42 == 0" to index computations.
1294 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1295 if (GetElementPtrInst *GEP =
1296 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1297 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1298 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1299 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1300 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1301 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1306 // X & -C == -C -> X > u ~C
1307 // X & -C != -C -> X <= u ~C
1308 // iff C is a power of 2
1309 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1310 return new ICmpInst(
1311 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1312 : ICmpInst::ICMP_ULE,
1313 LHSI->getOperand(0), SubOne(RHS));
1316 case Instruction::Or: {
1317 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1320 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1321 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1322 // -> and (icmp eq P, null), (icmp eq Q, null).
1323 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1324 Constant::getNullValue(P->getType()));
1325 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1326 Constant::getNullValue(Q->getType()));
1328 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1329 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1331 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1337 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1338 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1341 // If this is a signed comparison to 0 and the mul is sign preserving,
1342 // use the mul LHS operand instead.
1343 ICmpInst::Predicate pred = ICI.getPredicate();
1344 if (isSignTest(pred, RHS) && !Val->isZero() &&
1345 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1346 return new ICmpInst(Val->isNegative() ?
1347 ICmpInst::getSwappedPredicate(pred) : pred,
1348 LHSI->getOperand(0),
1349 Constant::getNullValue(RHS->getType()));
1354 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
1355 uint32_t TypeBits = RHSV.getBitWidth();
1356 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1359 // (1 << X) pred P2 -> X pred Log2(P2)
1360 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1361 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1362 ICmpInst::Predicate Pred = ICI.getPredicate();
1363 if (ICI.isUnsigned()) {
1364 if (!RHSVIsPowerOf2) {
1365 // (1 << X) < 30 -> X <= 4
1366 // (1 << X) <= 30 -> X <= 4
1367 // (1 << X) >= 30 -> X > 4
1368 // (1 << X) > 30 -> X > 4
1369 if (Pred == ICmpInst::ICMP_ULT)
1370 Pred = ICmpInst::ICMP_ULE;
1371 else if (Pred == ICmpInst::ICMP_UGE)
1372 Pred = ICmpInst::ICMP_UGT;
1374 unsigned RHSLog2 = RHSV.logBase2();
1376 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
1377 // (1 << X) > 2147483648 -> X > 31 -> false
1378 // (1 << X) <= 2147483648 -> X <= 31 -> true
1379 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1380 if (RHSLog2 == TypeBits-1) {
1381 if (Pred == ICmpInst::ICMP_UGE)
1382 Pred = ICmpInst::ICMP_EQ;
1383 else if (Pred == ICmpInst::ICMP_UGT)
1384 return ReplaceInstUsesWith(ICI, Builder->getFalse());
1385 else if (Pred == ICmpInst::ICMP_ULE)
1386 return ReplaceInstUsesWith(ICI, Builder->getTrue());
1387 else if (Pred == ICmpInst::ICMP_ULT)
1388 Pred = ICmpInst::ICMP_NE;
1391 return new ICmpInst(Pred, X,
1392 ConstantInt::get(RHS->getType(), RHSLog2));
1393 } else if (ICI.isSigned()) {
1394 if (RHSV.isAllOnesValue()) {
1395 // (1 << X) <= -1 -> X == 31
1396 if (Pred == ICmpInst::ICMP_SLE)
1397 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1398 ConstantInt::get(RHS->getType(), TypeBits-1));
1400 // (1 << X) > -1 -> X != 31
1401 if (Pred == ICmpInst::ICMP_SGT)
1402 return new ICmpInst(ICmpInst::ICMP_NE, X,
1403 ConstantInt::get(RHS->getType(), TypeBits-1));
1405 // (1 << X) < 0 -> X == 31
1406 // (1 << X) <= 0 -> X == 31
1407 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1408 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1409 ConstantInt::get(RHS->getType(), TypeBits-1));
1411 // (1 << X) >= 0 -> X != 31
1412 // (1 << X) > 0 -> X != 31
1413 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1414 return new ICmpInst(ICmpInst::ICMP_NE, X,
1415 ConstantInt::get(RHS->getType(), TypeBits-1));
1417 } else if (ICI.isEquality()) {
1419 return new ICmpInst(
1420 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
1422 return ReplaceInstUsesWith(
1423 ICI, Pred == ICmpInst::ICMP_EQ ? Builder->getFalse()
1424 : Builder->getTrue());
1430 // Check that the shift amount is in range. If not, don't perform
1431 // undefined shifts. When the shift is visited it will be
1433 if (ShAmt->uge(TypeBits))
1436 if (ICI.isEquality()) {
1437 // If we are comparing against bits always shifted out, the
1438 // comparison cannot succeed.
1440 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1442 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1443 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1444 Constant *Cst = Builder->getInt1(IsICMP_NE);
1445 return ReplaceInstUsesWith(ICI, Cst);
1448 // If the shift is NUW, then it is just shifting out zeros, no need for an
1450 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1451 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1452 ConstantExpr::getLShr(RHS, ShAmt));
1454 // If the shift is NSW and we compare to 0, then it is just shifting out
1455 // sign bits, no need for an AND either.
1456 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1457 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1458 ConstantExpr::getLShr(RHS, ShAmt));
1460 if (LHSI->hasOneUse()) {
1461 // Otherwise strength reduce the shift into an and.
1462 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1463 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
1464 TypeBits - ShAmtVal));
1467 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1468 return new ICmpInst(ICI.getPredicate(), And,
1469 ConstantExpr::getLShr(RHS, ShAmt));
1473 // If this is a signed comparison to 0 and the shift is sign preserving,
1474 // use the shift LHS operand instead.
1475 ICmpInst::Predicate pred = ICI.getPredicate();
1476 if (isSignTest(pred, RHS) &&
1477 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1478 return new ICmpInst(pred,
1479 LHSI->getOperand(0),
1480 Constant::getNullValue(RHS->getType()));
1482 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1483 bool TrueIfSigned = false;
1484 if (LHSI->hasOneUse() &&
1485 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1486 // (X << 31) <s 0 --> (X&1) != 0
1487 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
1488 APInt::getOneBitSet(TypeBits,
1489 TypeBits-ShAmt->getZExtValue()-1));
1491 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1492 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1493 And, Constant::getNullValue(And->getType()));
1496 // Transform (icmp pred iM (shl iM %v, N), CI)
1497 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1498 // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
1499 // This enables to get rid of the shift in favor of a trunc which can be
1500 // free on the target. It has the additional benefit of comparing to a
1501 // smaller constant, which will be target friendly.
1502 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
1503 if (LHSI->hasOneUse() &&
1504 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
1505 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1506 Constant *NCI = ConstantExpr::getTrunc(
1507 ConstantExpr::getAShr(RHS,
1508 ConstantInt::get(RHS->getType(), Amt)),
1510 return new ICmpInst(ICI.getPredicate(),
1511 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
1518 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
1519 case Instruction::AShr: {
1520 // Handle equality comparisons of shift-by-constant.
1521 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1522 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1523 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
1527 // Handle exact shr's.
1528 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1529 if (RHSV.isMinValue())
1530 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1535 case Instruction::SDiv:
1536 case Instruction::UDiv:
1537 // Fold: icmp pred ([us]div X, C1), C2 -> range test
1538 // Fold this div into the comparison, producing a range check.
1539 // Determine, based on the divide type, what the range is being
1540 // checked. If there is an overflow on the low or high side, remember
1541 // it, otherwise compute the range [low, hi) bounding the new value.
1542 // See: InsertRangeTest above for the kinds of replacements possible.
1543 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1544 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1549 case Instruction::Sub: {
1550 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
1552 const APInt &LHSV = LHSC->getValue();
1554 // C1-X <u C2 -> (X|(C2-1)) == C1
1555 // iff C1 & (C2-1) == C2-1
1556 // C2 is a power of 2
1557 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1558 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
1559 return new ICmpInst(ICmpInst::ICMP_EQ,
1560 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
1563 // C1-X >u C2 -> (X|C2) != C1
1564 // iff C1 & C2 == C2
1565 // C2+1 is a power of 2
1566 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1567 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
1568 return new ICmpInst(ICmpInst::ICMP_NE,
1569 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
1573 case Instruction::Add:
1574 // Fold: icmp pred (add X, C1), C2
1575 if (!ICI.isEquality()) {
1576 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1578 const APInt &LHSV = LHSC->getValue();
1580 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1583 if (ICI.isSigned()) {
1584 if (CR.getLower().isSignBit()) {
1585 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1586 Builder->getInt(CR.getUpper()));
1587 } else if (CR.getUpper().isSignBit()) {
1588 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1589 Builder->getInt(CR.getLower()));
1592 if (CR.getLower().isMinValue()) {
1593 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1594 Builder->getInt(CR.getUpper()));
1595 } else if (CR.getUpper().isMinValue()) {
1596 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1597 Builder->getInt(CR.getLower()));
1601 // X-C1 <u C2 -> (X & -C2) == C1
1602 // iff C1 & (C2-1) == 0
1603 // C2 is a power of 2
1604 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1605 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
1606 return new ICmpInst(ICmpInst::ICMP_EQ,
1607 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
1608 ConstantExpr::getNeg(LHSC));
1610 // X-C1 >u C2 -> (X & ~C2) != C1
1612 // C2+1 is a power of 2
1613 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1614 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
1615 return new ICmpInst(ICmpInst::ICMP_NE,
1616 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
1617 ConstantExpr::getNeg(LHSC));
1622 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1623 if (ICI.isEquality()) {
1624 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1626 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
1627 // the second operand is a constant, simplify a bit.
1628 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1629 switch (BO->getOpcode()) {
1630 case Instruction::SRem:
1631 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1632 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1633 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
1634 if (V.sgt(1) && V.isPowerOf2()) {
1636 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1638 return new ICmpInst(ICI.getPredicate(), NewRem,
1639 Constant::getNullValue(BO->getType()));
1643 case Instruction::Add:
1644 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1645 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1646 if (BO->hasOneUse())
1647 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1648 ConstantExpr::getSub(RHS, BOp1C));
1649 } else if (RHSV == 0) {
1650 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1651 // efficiently invertible, or if the add has just this one use.
1652 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1654 if (Value *NegVal = dyn_castNegVal(BOp1))
1655 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
1656 if (Value *NegVal = dyn_castNegVal(BOp0))
1657 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
1658 if (BO->hasOneUse()) {
1659 Value *Neg = Builder->CreateNeg(BOp1);
1661 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1665 case Instruction::Xor:
1666 // For the xor case, we can xor two constants together, eliminating
1667 // the explicit xor.
1668 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1669 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1670 ConstantExpr::getXor(RHS, BOC));
1671 } else if (RHSV == 0) {
1672 // Replace ((xor A, B) != 0) with (A != B)
1673 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1677 case Instruction::Sub:
1678 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1679 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1680 if (BO->hasOneUse())
1681 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1682 ConstantExpr::getSub(BOp0C, RHS));
1683 } else if (RHSV == 0) {
1684 // Replace ((sub A, B) != 0) with (A != B)
1685 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1689 case Instruction::Or:
1690 // If bits are being or'd in that are not present in the constant we
1691 // are comparing against, then the comparison could never succeed!
1692 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1693 Constant *NotCI = ConstantExpr::getNot(RHS);
1694 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1695 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
1699 case Instruction::And:
1700 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1701 // If bits are being compared against that are and'd out, then the
1702 // comparison can never succeed!
1703 if ((RHSV & ~BOC->getValue()) != 0)
1704 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
1706 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1707 if (RHS == BOC && RHSV.isPowerOf2())
1708 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1709 ICmpInst::ICMP_NE, LHSI,
1710 Constant::getNullValue(RHS->getType()));
1712 // Don't perform the following transforms if the AND has multiple uses
1713 if (!BO->hasOneUse())
1716 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1717 if (BOC->getValue().isSignBit()) {
1718 Value *X = BO->getOperand(0);
1719 Constant *Zero = Constant::getNullValue(X->getType());
1720 ICmpInst::Predicate pred = isICMP_NE ?
1721 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1722 return new ICmpInst(pred, X, Zero);
1725 // ((X & ~7) == 0) --> X < 8
1726 if (RHSV == 0 && isHighOnes(BOC)) {
1727 Value *X = BO->getOperand(0);
1728 Constant *NegX = ConstantExpr::getNeg(BOC);
1729 ICmpInst::Predicate pred = isICMP_NE ?
1730 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1731 return new ICmpInst(pred, X, NegX);
1735 case Instruction::Mul:
1736 if (RHSV == 0 && BO->hasNoSignedWrap()) {
1737 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1738 // The trivial case (mul X, 0) is handled by InstSimplify
1739 // General case : (mul X, C) != 0 iff X != 0
1740 // (mul X, C) == 0 iff X == 0
1742 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1743 Constant::getNullValue(RHS->getType()));
1749 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1750 // Handle icmp {eq|ne} <intrinsic>, intcst.
1751 switch (II->getIntrinsicID()) {
1752 case Intrinsic::bswap:
1754 ICI.setOperand(0, II->getArgOperand(0));
1755 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
1757 case Intrinsic::ctlz:
1758 case Intrinsic::cttz:
1759 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1760 if (RHSV == RHS->getType()->getBitWidth()) {
1762 ICI.setOperand(0, II->getArgOperand(0));
1763 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1767 case Intrinsic::ctpop:
1768 // popcount(A) == 0 -> A == 0 and likewise for !=
1769 if (RHS->isZero()) {
1771 ICI.setOperand(0, II->getArgOperand(0));
1772 ICI.setOperand(1, RHS);
1784 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1785 /// We only handle extending casts so far.
1787 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1788 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1789 Value *LHSCIOp = LHSCI->getOperand(0);
1790 Type *SrcTy = LHSCIOp->getType();
1791 Type *DestTy = LHSCI->getType();
1794 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
1795 // integer type is the same size as the pointer type.
1796 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
1797 TD->getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
1799 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1800 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1801 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1802 RHSOp = RHSC->getOperand(0);
1803 // If the pointer types don't match, insert a bitcast.
1804 if (LHSCIOp->getType() != RHSOp->getType())
1805 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1809 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1812 // The code below only handles extension cast instructions, so far.
1814 if (LHSCI->getOpcode() != Instruction::ZExt &&
1815 LHSCI->getOpcode() != Instruction::SExt)
1818 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1819 bool isSignedCmp = ICI.isSigned();
1821 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1822 // Not an extension from the same type?
1823 RHSCIOp = CI->getOperand(0);
1824 if (RHSCIOp->getType() != LHSCIOp->getType())
1827 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1828 // and the other is a zext), then we can't handle this.
1829 if (CI->getOpcode() != LHSCI->getOpcode())
1832 // Deal with equality cases early.
1833 if (ICI.isEquality())
1834 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1836 // A signed comparison of sign extended values simplifies into a
1837 // signed comparison.
1838 if (isSignedCmp && isSignedExt)
1839 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1841 // The other three cases all fold into an unsigned comparison.
1842 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1845 // If we aren't dealing with a constant on the RHS, exit early
1846 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1850 // Compute the constant that would happen if we truncated to SrcTy then
1851 // reextended to DestTy.
1852 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1853 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1856 // If the re-extended constant didn't change...
1858 // Deal with equality cases early.
1859 if (ICI.isEquality())
1860 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1862 // A signed comparison of sign extended values simplifies into a
1863 // signed comparison.
1864 if (isSignedExt && isSignedCmp)
1865 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1867 // The other three cases all fold into an unsigned comparison.
1868 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1871 // The re-extended constant changed so the constant cannot be represented
1872 // in the shorter type. Consequently, we cannot emit a simple comparison.
1873 // All the cases that fold to true or false will have already been handled
1874 // by SimplifyICmpInst, so only deal with the tricky case.
1876 if (isSignedCmp || !isSignedExt)
1879 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1880 // should have been folded away previously and not enter in here.
1882 // We're performing an unsigned comp with a sign extended value.
1883 // This is true if the input is >= 0. [aka >s -1]
1884 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1885 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
1887 // Finally, return the value computed.
1888 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
1889 return ReplaceInstUsesWith(ICI, Result);
1891 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
1892 return BinaryOperator::CreateNot(Result);
1895 /// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1896 /// I = icmp ugt (add (add A, B), CI2), CI1
1897 /// If this is of the form:
1899 /// if (sum+128 >u 255)
1900 /// Then replace it with llvm.sadd.with.overflow.i8.
1902 static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1903 ConstantInt *CI2, ConstantInt *CI1,
1905 // The transformation we're trying to do here is to transform this into an
1906 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1907 // with a narrower add, and discard the add-with-constant that is part of the
1908 // range check (if we can't eliminate it, this isn't profitable).
1910 // In order to eliminate the add-with-constant, the compare can be its only
1912 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1913 if (!AddWithCst->hasOneUse()) return 0;
1915 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1916 if (!CI2->getValue().isPowerOf2()) return 0;
1917 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1918 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
1920 // The width of the new add formed is 1 more than the bias.
1923 // Check to see that CI1 is an all-ones value with NewWidth bits.
1924 if (CI1->getBitWidth() == NewWidth ||
1925 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1928 // This is only really a signed overflow check if the inputs have been
1929 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1930 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1931 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1932 if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1933 IC.ComputeNumSignBits(B) < NeededSignBits)
1936 // In order to replace the original add with a narrower
1937 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1938 // and truncates that discard the high bits of the add. Verify that this is
1940 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1941 for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1943 if (*UI == AddWithCst) continue;
1945 // Only accept truncates for now. We would really like a nice recursive
1946 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1947 // chain to see which bits of a value are actually demanded. If the
1948 // original add had another add which was then immediately truncated, we
1949 // could still do the transformation.
1950 TruncInst *TI = dyn_cast<TruncInst>(*UI);
1952 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1955 // If the pattern matches, truncate the inputs to the narrower type and
1956 // use the sadd_with_overflow intrinsic to efficiently compute both the
1957 // result and the overflow bit.
1958 Module *M = I.getParent()->getParent()->getParent();
1960 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1961 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
1964 InstCombiner::BuilderTy *Builder = IC.Builder;
1966 // Put the new code above the original add, in case there are any uses of the
1967 // add between the add and the compare.
1968 Builder->SetInsertPoint(OrigAdd);
1970 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1971 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1972 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1973 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1974 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
1976 // The inner add was the result of the narrow add, zero extended to the
1977 // wider type. Replace it with the result computed by the intrinsic.
1978 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
1980 // The original icmp gets replaced with the overflow value.
1981 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1984 static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1986 // Don't bother doing this transformation for pointers, don't do it for
1988 if (!isa<IntegerType>(OrigAddV->getType())) return 0;
1990 // If the add is a constant expr, then we don't bother transforming it.
1991 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1992 if (OrigAdd == 0) return 0;
1994 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
1996 // Put the new code above the original add, in case there are any uses of the
1997 // add between the add and the compare.
1998 InstCombiner::BuilderTy *Builder = IC.Builder;
1999 Builder->SetInsertPoint(OrigAdd);
2001 Module *M = I.getParent()->getParent()->getParent();
2002 Type *Ty = LHS->getType();
2003 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
2004 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
2005 Value *Add = Builder->CreateExtractValue(Call, 0);
2007 IC.ReplaceInstUsesWith(*OrigAdd, Add);
2009 // The original icmp gets replaced with the overflow value.
2010 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
2013 // DemandedBitsLHSMask - When performing a comparison against a constant,
2014 // it is possible that not all the bits in the LHS are demanded. This helper
2015 // method computes the mask that IS demanded.
2016 static APInt DemandedBitsLHSMask(ICmpInst &I,
2017 unsigned BitWidth, bool isSignCheck) {
2019 return APInt::getSignBit(BitWidth);
2021 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2022 if (!CI) return APInt::getAllOnesValue(BitWidth);
2023 const APInt &RHS = CI->getValue();
2025 switch (I.getPredicate()) {
2026 // For a UGT comparison, we don't care about any bits that
2027 // correspond to the trailing ones of the comparand. The value of these
2028 // bits doesn't impact the outcome of the comparison, because any value
2029 // greater than the RHS must differ in a bit higher than these due to carry.
2030 case ICmpInst::ICMP_UGT: {
2031 unsigned trailingOnes = RHS.countTrailingOnes();
2032 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2036 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2037 // Any value less than the RHS must differ in a higher bit because of carries.
2038 case ICmpInst::ICMP_ULT: {
2039 unsigned trailingZeros = RHS.countTrailingZeros();
2040 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2045 return APInt::getAllOnesValue(BitWidth);
2050 /// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2051 /// should be swapped.
2052 /// The descision is based on how many times these two operands are reused
2053 /// as subtract operands and their positions in those instructions.
2054 /// The rational is that several architectures use the same instruction for
2055 /// both subtract and cmp, thus it is better if the order of those operands
2057 /// \return true if Op0 and Op1 should be swapped.
2058 static bool swapMayExposeCSEOpportunities(const Value * Op0,
2059 const Value * Op1) {
2060 // Filter out pointer value as those cannot appears directly in subtract.
2061 // FIXME: we may want to go through inttoptrs or bitcasts.
2062 if (Op0->getType()->isPointerTy())
2064 // Count every uses of both Op0 and Op1 in a subtract.
2065 // Each time Op0 is the first operand, count -1: swapping is bad, the
2066 // subtract has already the same layout as the compare.
2067 // Each time Op0 is the second operand, count +1: swapping is good, the
2068 // subtract has a diffrent layout as the compare.
2069 // At the end, if the benefit is greater than 0, Op0 should come second to
2070 // expose more CSE opportunities.
2071 int GlobalSwapBenefits = 0;
2072 for (Value::const_use_iterator UI = Op0->use_begin(), UIEnd = Op0->use_end(); UI != UIEnd; ++UI) {
2073 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(*UI);
2074 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2076 // If Op0 is the first argument, this is not beneficial to swap the
2078 int LocalSwapBenefits = -1;
2079 unsigned Op1Idx = 1;
2080 if (BinOp->getOperand(Op1Idx) == Op0) {
2082 LocalSwapBenefits = 1;
2084 if (BinOp->getOperand(Op1Idx) != Op1)
2086 GlobalSwapBenefits += LocalSwapBenefits;
2088 return GlobalSwapBenefits > 0;
2091 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
2092 bool Changed = false;
2093 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2094 unsigned Op0Cplxity = getComplexity(Op0);
2095 unsigned Op1Cplxity = getComplexity(Op1);
2097 /// Orders the operands of the compare so that they are listed from most
2098 /// complex to least complex. This puts constants before unary operators,
2099 /// before binary operators.
2100 if (Op0Cplxity < Op1Cplxity ||
2101 (Op0Cplxity == Op1Cplxity &&
2102 swapMayExposeCSEOpportunities(Op0, Op1))) {
2104 std::swap(Op0, Op1);
2108 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
2109 return ReplaceInstUsesWith(I, V);
2111 // comparing -val or val with non-zero is the same as just comparing val
2112 // ie, abs(val) != 0 -> val != 0
2113 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
2115 Value *Cond, *SelectTrue, *SelectFalse;
2116 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
2117 m_Value(SelectFalse)))) {
2118 if (Value *V = dyn_castNegVal(SelectTrue)) {
2119 if (V == SelectFalse)
2120 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2122 else if (Value *V = dyn_castNegVal(SelectFalse)) {
2123 if (V == SelectTrue)
2124 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2129 Type *Ty = Op0->getType();
2131 // icmp's with boolean values can always be turned into bitwise operations
2132 if (Ty->isIntegerTy(1)) {
2133 switch (I.getPredicate()) {
2134 default: llvm_unreachable("Invalid icmp instruction!");
2135 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
2136 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
2137 return BinaryOperator::CreateNot(Xor);
2139 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
2140 return BinaryOperator::CreateXor(Op0, Op1);
2142 case ICmpInst::ICMP_UGT:
2143 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
2145 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
2146 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2147 return BinaryOperator::CreateAnd(Not, Op1);
2149 case ICmpInst::ICMP_SGT:
2150 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
2152 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
2153 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2154 return BinaryOperator::CreateAnd(Not, Op0);
2156 case ICmpInst::ICMP_UGE:
2157 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
2159 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
2160 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2161 return BinaryOperator::CreateOr(Not, Op1);
2163 case ICmpInst::ICMP_SGE:
2164 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
2166 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
2167 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2168 return BinaryOperator::CreateOr(Not, Op0);
2173 unsigned BitWidth = 0;
2174 if (Ty->isIntOrIntVectorTy())
2175 BitWidth = Ty->getScalarSizeInBits();
2176 else if (TD) // Pointers require TD info to get their size.
2177 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
2179 bool isSignBit = false;
2181 // See if we are doing a comparison with a constant.
2182 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2183 Value *A = 0, *B = 0;
2185 // Match the following pattern, which is a common idiom when writing
2186 // overflow-safe integer arithmetic function. The source performs an
2187 // addition in wider type, and explicitly checks for overflow using
2188 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
2189 // sadd_with_overflow intrinsic.
2191 // TODO: This could probably be generalized to handle other overflow-safe
2192 // operations if we worked out the formulas to compute the appropriate
2196 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
2198 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
2199 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2200 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
2201 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
2205 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2206 if (I.isEquality() && CI->isZero() &&
2207 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
2208 // (icmp cond A B) if cond is equality
2209 return new ICmpInst(I.getPredicate(), A, B);
2212 // If we have an icmp le or icmp ge instruction, turn it into the
2213 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
2214 // them being folded in the code below. The SimplifyICmpInst code has
2215 // already handled the edge cases for us, so we just assert on them.
2216 switch (I.getPredicate()) {
2218 case ICmpInst::ICMP_ULE:
2219 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
2220 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
2221 Builder->getInt(CI->getValue()+1));
2222 case ICmpInst::ICMP_SLE:
2223 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
2224 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2225 Builder->getInt(CI->getValue()+1));
2226 case ICmpInst::ICMP_UGE:
2227 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
2228 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
2229 Builder->getInt(CI->getValue()-1));
2230 case ICmpInst::ICMP_SGE:
2231 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
2232 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2233 Builder->getInt(CI->getValue()-1));
2236 // If this comparison is a normal comparison, it demands all
2237 // bits, if it is a sign bit comparison, it only demands the sign bit.
2239 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2242 // See if we can fold the comparison based on range information we can get
2243 // by checking whether bits are known to be zero or one in the input.
2244 if (BitWidth != 0) {
2245 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2246 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2248 if (SimplifyDemandedBits(I.getOperandUse(0),
2249 DemandedBitsLHSMask(I, BitWidth, isSignBit),
2250 Op0KnownZero, Op0KnownOne, 0))
2252 if (SimplifyDemandedBits(I.getOperandUse(1),
2253 APInt::getAllOnesValue(BitWidth),
2254 Op1KnownZero, Op1KnownOne, 0))
2257 // Given the known and unknown bits, compute a range that the LHS could be
2258 // in. Compute the Min, Max and RHS values based on the known bits. For the
2259 // EQ and NE we use unsigned values.
2260 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2261 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2263 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2265 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2268 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2270 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2274 // If Min and Max are known to be the same, then SimplifyDemandedBits
2275 // figured out that the LHS is a constant. Just constant fold this now so
2276 // that code below can assume that Min != Max.
2277 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2278 return new ICmpInst(I.getPredicate(),
2279 ConstantInt::get(Op0->getType(), Op0Min), Op1);
2280 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2281 return new ICmpInst(I.getPredicate(), Op0,
2282 ConstantInt::get(Op1->getType(), Op1Min));
2284 // Based on the range information we know about the LHS, see if we can
2285 // simplify this comparison. For example, (x&4) < 8 is always true.
2286 switch (I.getPredicate()) {
2287 default: llvm_unreachable("Unknown icmp opcode!");
2288 case ICmpInst::ICMP_EQ: {
2289 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2290 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2292 // If all bits are known zero except for one, then we know at most one
2293 // bit is set. If the comparison is against zero, then this is a check
2294 // to see if *that* bit is set.
2295 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2296 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2297 // If the LHS is an AND with the same constant, look through it.
2299 ConstantInt *LHSC = 0;
2300 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2301 LHSC->getValue() != Op0KnownZeroInverted)
2304 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2305 // then turn "((1 << x)&8) == 0" into "x != 3".
2307 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2308 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
2309 return new ICmpInst(ICmpInst::ICMP_NE, X,
2310 ConstantInt::get(X->getType(), CmpVal));
2313 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2314 // then turn "((8 >>u x)&1) == 0" into "x != 3".
2316 if (Op0KnownZeroInverted == 1 &&
2317 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2318 return new ICmpInst(ICmpInst::ICMP_NE, X,
2319 ConstantInt::get(X->getType(),
2320 CI->countTrailingZeros()));
2325 case ICmpInst::ICMP_NE: {
2326 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2327 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2329 // If all bits are known zero except for one, then we know at most one
2330 // bit is set. If the comparison is against zero, then this is a check
2331 // to see if *that* bit is set.
2332 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2333 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2334 // If the LHS is an AND with the same constant, look through it.
2336 ConstantInt *LHSC = 0;
2337 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2338 LHSC->getValue() != Op0KnownZeroInverted)
2341 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2342 // then turn "((1 << x)&8) != 0" into "x == 3".
2344 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2345 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
2346 return new ICmpInst(ICmpInst::ICMP_EQ, X,
2347 ConstantInt::get(X->getType(), CmpVal));
2350 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2351 // then turn "((8 >>u x)&1) != 0" into "x == 3".
2353 if (Op0KnownZeroInverted == 1 &&
2354 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2355 return new ICmpInst(ICmpInst::ICMP_EQ, X,
2356 ConstantInt::get(X->getType(),
2357 CI->countTrailingZeros()));
2362 case ICmpInst::ICMP_ULT:
2363 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
2364 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2365 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
2366 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2367 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2368 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2369 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2370 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2371 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2372 Builder->getInt(CI->getValue()-1));
2374 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2375 if (CI->isMinValue(true))
2376 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2377 Constant::getAllOnesValue(Op0->getType()));
2380 case ICmpInst::ICMP_UGT:
2381 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
2382 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2383 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
2384 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2386 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2387 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2388 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2389 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2390 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2391 Builder->getInt(CI->getValue()+1));
2393 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2394 if (CI->isMaxValue(true))
2395 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2396 Constant::getNullValue(Op0->getType()));
2399 case ICmpInst::ICMP_SLT:
2400 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
2401 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2402 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
2403 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2404 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2405 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2406 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2407 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2408 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2409 Builder->getInt(CI->getValue()-1));
2412 case ICmpInst::ICMP_SGT:
2413 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
2414 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2415 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
2416 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2418 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2419 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2420 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2421 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2422 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2423 Builder->getInt(CI->getValue()+1));
2426 case ICmpInst::ICMP_SGE:
2427 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2428 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
2429 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2430 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
2431 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2433 case ICmpInst::ICMP_SLE:
2434 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2435 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
2436 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2437 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
2438 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2440 case ICmpInst::ICMP_UGE:
2441 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2442 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
2443 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2444 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
2445 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2447 case ICmpInst::ICMP_ULE:
2448 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2449 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
2450 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2451 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
2452 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2456 // Turn a signed comparison into an unsigned one if both operands
2457 // are known to have the same sign.
2459 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2460 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2461 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2464 // Test if the ICmpInst instruction is used exclusively by a select as
2465 // part of a minimum or maximum operation. If so, refrain from doing
2466 // any other folding. This helps out other analyses which understand
2467 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2468 // and CodeGen. And in this case, at least one of the comparison
2469 // operands has at least one user besides the compare (the select),
2470 // which would often largely negate the benefit of folding anyway.
2472 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2473 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2474 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2477 // See if we are doing a comparison between a constant and an instruction that
2478 // can be folded into the comparison.
2479 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2480 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2481 // instruction, see if that instruction also has constants so that the
2482 // instruction can be folded into the icmp
2483 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2484 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2488 // Handle icmp with constant (but not simple integer constant) RHS
2489 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2490 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2491 switch (LHSI->getOpcode()) {
2492 case Instruction::GetElementPtr:
2493 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2494 if (RHSC->isNullValue() &&
2495 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2496 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2497 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2499 case Instruction::PHI:
2500 // Only fold icmp into the PHI if the phi and icmp are in the same
2501 // block. If in the same block, we're encouraging jump threading. If
2502 // not, we are just pessimizing the code by making an i1 phi.
2503 if (LHSI->getParent() == I.getParent())
2504 if (Instruction *NV = FoldOpIntoPhi(I))
2507 case Instruction::Select: {
2508 // If either operand of the select is a constant, we can fold the
2509 // comparison into the select arms, which will cause one to be
2510 // constant folded and the select turned into a bitwise or.
2511 Value *Op1 = 0, *Op2 = 0;
2512 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2513 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2514 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2515 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2517 // We only want to perform this transformation if it will not lead to
2518 // additional code. This is true if either both sides of the select
2519 // fold to a constant (in which case the icmp is replaced with a select
2520 // which will usually simplify) or this is the only user of the
2521 // select (in which case we are trading a select+icmp for a simpler
2523 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2525 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2528 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2530 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2534 case Instruction::IntToPtr:
2535 // icmp pred inttoptr(X), null -> icmp pred X, 0
2536 if (RHSC->isNullValue() && TD &&
2537 TD->getIntPtrType(RHSC->getType()) ==
2538 LHSI->getOperand(0)->getType())
2539 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2540 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2543 case Instruction::Load:
2544 // Try to optimize things like "A[i] > 4" to index computations.
2545 if (GetElementPtrInst *GEP =
2546 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2547 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2548 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2549 !cast<LoadInst>(LHSI)->isVolatile())
2550 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2557 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2558 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2559 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2561 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2562 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2563 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2566 // Test to see if the operands of the icmp are casted versions of other
2567 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
2569 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
2570 if (Op0->getType()->isPointerTy() &&
2571 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
2572 // We keep moving the cast from the left operand over to the right
2573 // operand, where it can often be eliminated completely.
2574 Op0 = CI->getOperand(0);
2576 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2577 // so eliminate it as well.
2578 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2579 Op1 = CI2->getOperand(0);
2581 // If Op1 is a constant, we can fold the cast into the constant.
2582 if (Op0->getType() != Op1->getType()) {
2583 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2584 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2586 // Otherwise, cast the RHS right before the icmp
2587 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2590 return new ICmpInst(I.getPredicate(), Op0, Op1);
2594 if (isa<CastInst>(Op0)) {
2595 // Handle the special case of: icmp (cast bool to X), <cst>
2596 // This comes up when you have code like
2599 // For generality, we handle any zero-extension of any operand comparison
2600 // with a constant or another cast from the same type.
2601 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2602 if (Instruction *R = visitICmpInstWithCastAndCast(I))
2606 // Special logic for binary operators.
2607 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2608 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2610 CmpInst::Predicate Pred = I.getPredicate();
2611 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2612 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2613 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2614 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2615 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2616 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2617 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2618 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2619 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2621 // Analyze the case when either Op0 or Op1 is an add instruction.
2622 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2623 Value *A = 0, *B = 0, *C = 0, *D = 0;
2624 if (BO0 && BO0->getOpcode() == Instruction::Add)
2625 A = BO0->getOperand(0), B = BO0->getOperand(1);
2626 if (BO1 && BO1->getOpcode() == Instruction::Add)
2627 C = BO1->getOperand(0), D = BO1->getOperand(1);
2629 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2630 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2631 return new ICmpInst(Pred, A == Op1 ? B : A,
2632 Constant::getNullValue(Op1->getType()));
2634 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2635 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2636 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2639 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
2640 if (A && C && (A == C || A == D || B == C || B == D) &&
2641 NoOp0WrapProblem && NoOp1WrapProblem &&
2642 // Try not to increase register pressure.
2643 BO0->hasOneUse() && BO1->hasOneUse()) {
2644 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2647 // C + B == C + D -> B == D
2650 } else if (A == D) {
2651 // D + B == C + D -> B == C
2654 } else if (B == C) {
2655 // A + C == C + D -> A == D
2660 // A + D == C + D -> A == C
2664 return new ICmpInst(Pred, Y, Z);
2667 // icmp slt (X + -1), Y -> icmp sle X, Y
2668 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
2669 match(B, m_AllOnes()))
2670 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
2672 // icmp sge (X + -1), Y -> icmp sgt X, Y
2673 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
2674 match(B, m_AllOnes()))
2675 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
2677 // icmp sle (X + 1), Y -> icmp slt X, Y
2678 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
2680 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
2682 // icmp sgt (X + 1), Y -> icmp sge X, Y
2683 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
2685 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
2687 // if C1 has greater magnitude than C2:
2688 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
2689 // s.t. C3 = C1 - C2
2691 // if C2 has greater magnitude than C1:
2692 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
2693 // s.t. C3 = C2 - C1
2694 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
2695 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
2696 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
2697 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
2698 const APInt &AP1 = C1->getValue();
2699 const APInt &AP2 = C2->getValue();
2700 if (AP1.isNegative() == AP2.isNegative()) {
2701 APInt AP1Abs = C1->getValue().abs();
2702 APInt AP2Abs = C2->getValue().abs();
2703 if (AP1Abs.uge(AP2Abs)) {
2704 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
2705 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
2706 return new ICmpInst(Pred, NewAdd, C);
2708 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
2709 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
2710 return new ICmpInst(Pred, A, NewAdd);
2716 // Analyze the case when either Op0 or Op1 is a sub instruction.
2717 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2718 A = 0; B = 0; C = 0; D = 0;
2719 if (BO0 && BO0->getOpcode() == Instruction::Sub)
2720 A = BO0->getOperand(0), B = BO0->getOperand(1);
2721 if (BO1 && BO1->getOpcode() == Instruction::Sub)
2722 C = BO1->getOperand(0), D = BO1->getOperand(1);
2724 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2725 if (A == Op1 && NoOp0WrapProblem)
2726 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2728 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2729 if (C == Op0 && NoOp1WrapProblem)
2730 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2732 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
2733 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2734 // Try not to increase register pressure.
2735 BO0->hasOneUse() && BO1->hasOneUse())
2736 return new ICmpInst(Pred, A, C);
2738 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2739 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2740 // Try not to increase register pressure.
2741 BO0->hasOneUse() && BO1->hasOneUse())
2742 return new ICmpInst(Pred, D, B);
2744 BinaryOperator *SRem = NULL;
2745 // icmp (srem X, Y), Y
2746 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2747 Op1 == BO0->getOperand(1))
2749 // icmp Y, (srem X, Y)
2750 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2751 Op0 == BO1->getOperand(1))
2754 // We don't check hasOneUse to avoid increasing register pressure because
2755 // the value we use is the same value this instruction was already using.
2756 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2758 case ICmpInst::ICMP_EQ:
2759 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2760 case ICmpInst::ICMP_NE:
2761 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2762 case ICmpInst::ICMP_SGT:
2763 case ICmpInst::ICMP_SGE:
2764 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2765 Constant::getAllOnesValue(SRem->getType()));
2766 case ICmpInst::ICMP_SLT:
2767 case ICmpInst::ICMP_SLE:
2768 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2769 Constant::getNullValue(SRem->getType()));
2773 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2774 BO0->hasOneUse() && BO1->hasOneUse() &&
2775 BO0->getOperand(1) == BO1->getOperand(1)) {
2776 switch (BO0->getOpcode()) {
2778 case Instruction::Add:
2779 case Instruction::Sub:
2780 case Instruction::Xor:
2781 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
2782 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2783 BO1->getOperand(0));
2784 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2785 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2786 if (CI->getValue().isSignBit()) {
2787 ICmpInst::Predicate Pred = I.isSigned()
2788 ? I.getUnsignedPredicate()
2789 : I.getSignedPredicate();
2790 return new ICmpInst(Pred, BO0->getOperand(0),
2791 BO1->getOperand(0));
2794 if (CI->isMaxValue(true)) {
2795 ICmpInst::Predicate Pred = I.isSigned()
2796 ? I.getUnsignedPredicate()
2797 : I.getSignedPredicate();
2798 Pred = I.getSwappedPredicate(Pred);
2799 return new ICmpInst(Pred, BO0->getOperand(0),
2800 BO1->getOperand(0));
2804 case Instruction::Mul:
2805 if (!I.isEquality())
2808 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2809 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2810 // Mask = -1 >> count-trailing-zeros(Cst).
2811 if (!CI->isZero() && !CI->isOne()) {
2812 const APInt &AP = CI->getValue();
2813 ConstantInt *Mask = ConstantInt::get(I.getContext(),
2814 APInt::getLowBitsSet(AP.getBitWidth(),
2816 AP.countTrailingZeros()));
2817 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2818 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2819 return new ICmpInst(I.getPredicate(), And1, And2);
2823 case Instruction::UDiv:
2824 case Instruction::LShr:
2828 case Instruction::SDiv:
2829 case Instruction::AShr:
2830 if (!BO0->isExact() || !BO1->isExact())
2832 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2833 BO1->getOperand(0));
2834 case Instruction::Shl: {
2835 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2836 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2839 if (!NSW && I.isSigned())
2841 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2842 BO1->getOperand(0));
2849 // Transform (A & ~B) == 0 --> (A & B) != 0
2850 // and (A & ~B) != 0 --> (A & B) == 0
2851 // if A is a power of 2.
2852 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2853 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A) && I.isEquality())
2854 return new ICmpInst(I.getInversePredicate(),
2855 Builder->CreateAnd(A, B),
2858 // ~x < ~y --> y < x
2859 // ~x < cst --> ~cst < x
2860 if (match(Op0, m_Not(m_Value(A)))) {
2861 if (match(Op1, m_Not(m_Value(B))))
2862 return new ICmpInst(I.getPredicate(), B, A);
2863 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
2864 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2867 // (a+b) <u a --> llvm.uadd.with.overflow.
2868 // (a+b) <u b --> llvm.uadd.with.overflow.
2869 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
2870 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2871 (Op1 == A || Op1 == B))
2872 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2875 // a >u (a+b) --> llvm.uadd.with.overflow.
2876 // b >u (a+b) --> llvm.uadd.with.overflow.
2877 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2878 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2879 (Op0 == A || Op0 == B))
2880 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2884 if (I.isEquality()) {
2885 Value *A, *B, *C, *D;
2887 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2888 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
2889 Value *OtherVal = A == Op1 ? B : A;
2890 return new ICmpInst(I.getPredicate(), OtherVal,
2891 Constant::getNullValue(A->getType()));
2894 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2895 // A^c1 == C^c2 --> A == C^(c1^c2)
2896 ConstantInt *C1, *C2;
2897 if (match(B, m_ConstantInt(C1)) &&
2898 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2899 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
2900 Value *Xor = Builder->CreateXor(C, NC);
2901 return new ICmpInst(I.getPredicate(), A, Xor);
2904 // A^B == A^D -> B == D
2905 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2906 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2907 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2908 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2912 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2913 (A == Op0 || B == Op0)) {
2914 // A == (A^B) -> B == 0
2915 Value *OtherVal = A == Op0 ? B : A;
2916 return new ICmpInst(I.getPredicate(), OtherVal,
2917 Constant::getNullValue(A->getType()));
2920 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
2921 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
2922 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
2923 Value *X = 0, *Y = 0, *Z = 0;
2926 X = B; Y = D; Z = A;
2927 } else if (A == D) {
2928 X = B; Y = C; Z = A;
2929 } else if (B == C) {
2930 X = A; Y = D; Z = B;
2931 } else if (B == D) {
2932 X = A; Y = C; Z = B;
2935 if (X) { // Build (X^Y) & Z
2936 Op1 = Builder->CreateXor(X, Y);
2937 Op1 = Builder->CreateAnd(Op1, Z);
2938 I.setOperand(0, Op1);
2939 I.setOperand(1, Constant::getNullValue(Op1->getType()));
2944 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
2945 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
2947 if ((Op0->hasOneUse() &&
2948 match(Op0, m_ZExt(m_Value(A))) &&
2949 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
2950 (Op1->hasOneUse() &&
2951 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
2952 match(Op1, m_ZExt(m_Value(A))))) {
2953 APInt Pow2 = Cst1->getValue() + 1;
2954 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
2955 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
2956 return new ICmpInst(I.getPredicate(), A,
2957 Builder->CreateTrunc(B, A->getType()));
2960 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
2961 // For lshr and ashr pairs.
2962 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
2963 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
2964 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
2965 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
2966 unsigned TypeBits = Cst1->getBitWidth();
2967 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
2968 if (ShAmt < TypeBits && ShAmt != 0) {
2969 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
2970 ? ICmpInst::ICMP_UGE
2971 : ICmpInst::ICMP_ULT;
2972 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
2973 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
2974 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
2978 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2979 // "icmp (and X, mask), cst"
2981 if (Op0->hasOneUse() &&
2982 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2983 m_ConstantInt(ShAmt))))) &&
2984 match(Op1, m_ConstantInt(Cst1)) &&
2985 // Only do this when A has multiple uses. This is most important to do
2986 // when it exposes other optimizations.
2988 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
2990 if (ShAmt < ASize) {
2992 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2995 APInt CmpV = Cst1->getValue().zext(ASize);
2998 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2999 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
3005 Value *X; ConstantInt *Cst;
3007 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
3008 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
3011 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
3012 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
3014 return Changed ? &I : 0;
3017 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
3019 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
3022 if (!isa<ConstantFP>(RHSC)) return 0;
3023 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
3025 // Get the width of the mantissa. We don't want to hack on conversions that
3026 // might lose information from the integer, e.g. "i64 -> float"
3027 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
3028 if (MantissaWidth == -1) return 0; // Unknown.
3030 // Check to see that the input is converted from an integer type that is small
3031 // enough that preserves all bits. TODO: check here for "known" sign bits.
3032 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
3033 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
3035 // If this is a uitofp instruction, we need an extra bit to hold the sign.
3036 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
3040 // If the conversion would lose info, don't hack on this.
3041 if ((int)InputSize > MantissaWidth)
3044 // Otherwise, we can potentially simplify the comparison. We know that it
3045 // will always come through as an integer value and we know the constant is
3046 // not a NAN (it would have been previously simplified).
3047 assert(!RHS.isNaN() && "NaN comparison not already folded!");
3049 ICmpInst::Predicate Pred;
3050 switch (I.getPredicate()) {
3051 default: llvm_unreachable("Unexpected predicate!");
3052 case FCmpInst::FCMP_UEQ:
3053 case FCmpInst::FCMP_OEQ:
3054 Pred = ICmpInst::ICMP_EQ;
3056 case FCmpInst::FCMP_UGT:
3057 case FCmpInst::FCMP_OGT:
3058 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
3060 case FCmpInst::FCMP_UGE:
3061 case FCmpInst::FCMP_OGE:
3062 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
3064 case FCmpInst::FCMP_ULT:
3065 case FCmpInst::FCMP_OLT:
3066 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
3068 case FCmpInst::FCMP_ULE:
3069 case FCmpInst::FCMP_OLE:
3070 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
3072 case FCmpInst::FCMP_UNE:
3073 case FCmpInst::FCMP_ONE:
3074 Pred = ICmpInst::ICMP_NE;
3076 case FCmpInst::FCMP_ORD:
3077 return ReplaceInstUsesWith(I, Builder->getTrue());
3078 case FCmpInst::FCMP_UNO:
3079 return ReplaceInstUsesWith(I, Builder->getFalse());
3082 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
3084 // Now we know that the APFloat is a normal number, zero or inf.
3086 // See if the FP constant is too large for the integer. For example,
3087 // comparing an i8 to 300.0.
3088 unsigned IntWidth = IntTy->getScalarSizeInBits();
3091 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
3092 // and large values.
3093 APFloat SMax(RHS.getSemantics());
3094 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
3095 APFloat::rmNearestTiesToEven);
3096 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
3097 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
3098 Pred == ICmpInst::ICMP_SLE)
3099 return ReplaceInstUsesWith(I, Builder->getTrue());
3100 return ReplaceInstUsesWith(I, Builder->getFalse());
3103 // If the RHS value is > UnsignedMax, fold the comparison. This handles
3104 // +INF and large values.
3105 APFloat UMax(RHS.getSemantics());
3106 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
3107 APFloat::rmNearestTiesToEven);
3108 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
3109 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
3110 Pred == ICmpInst::ICMP_ULE)
3111 return ReplaceInstUsesWith(I, Builder->getTrue());
3112 return ReplaceInstUsesWith(I, Builder->getFalse());
3117 // See if the RHS value is < SignedMin.
3118 APFloat SMin(RHS.getSemantics());
3119 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
3120 APFloat::rmNearestTiesToEven);
3121 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
3122 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
3123 Pred == ICmpInst::ICMP_SGE)
3124 return ReplaceInstUsesWith(I, Builder->getTrue());
3125 return ReplaceInstUsesWith(I, Builder->getFalse());
3128 // See if the RHS value is < UnsignedMin.
3129 APFloat SMin(RHS.getSemantics());
3130 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
3131 APFloat::rmNearestTiesToEven);
3132 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
3133 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
3134 Pred == ICmpInst::ICMP_UGE)
3135 return ReplaceInstUsesWith(I, Builder->getTrue());
3136 return ReplaceInstUsesWith(I, Builder->getFalse());
3140 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
3141 // [0, UMAX], but it may still be fractional. See if it is fractional by
3142 // casting the FP value to the integer value and back, checking for equality.
3143 // Don't do this for zero, because -0.0 is not fractional.
3144 Constant *RHSInt = LHSUnsigned
3145 ? ConstantExpr::getFPToUI(RHSC, IntTy)
3146 : ConstantExpr::getFPToSI(RHSC, IntTy);
3147 if (!RHS.isZero()) {
3148 bool Equal = LHSUnsigned
3149 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
3150 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
3152 // If we had a comparison against a fractional value, we have to adjust
3153 // the compare predicate and sometimes the value. RHSC is rounded towards
3154 // zero at this point.
3156 default: llvm_unreachable("Unexpected integer comparison!");
3157 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
3158 return ReplaceInstUsesWith(I, Builder->getTrue());
3159 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
3160 return ReplaceInstUsesWith(I, Builder->getFalse());
3161 case ICmpInst::ICMP_ULE:
3162 // (float)int <= 4.4 --> int <= 4
3163 // (float)int <= -4.4 --> false
3164 if (RHS.isNegative())
3165 return ReplaceInstUsesWith(I, Builder->getFalse());
3167 case ICmpInst::ICMP_SLE:
3168 // (float)int <= 4.4 --> int <= 4
3169 // (float)int <= -4.4 --> int < -4
3170 if (RHS.isNegative())
3171 Pred = ICmpInst::ICMP_SLT;
3173 case ICmpInst::ICMP_ULT:
3174 // (float)int < -4.4 --> false
3175 // (float)int < 4.4 --> int <= 4
3176 if (RHS.isNegative())
3177 return ReplaceInstUsesWith(I, Builder->getFalse());
3178 Pred = ICmpInst::ICMP_ULE;
3180 case ICmpInst::ICMP_SLT:
3181 // (float)int < -4.4 --> int < -4
3182 // (float)int < 4.4 --> int <= 4
3183 if (!RHS.isNegative())
3184 Pred = ICmpInst::ICMP_SLE;
3186 case ICmpInst::ICMP_UGT:
3187 // (float)int > 4.4 --> int > 4
3188 // (float)int > -4.4 --> true
3189 if (RHS.isNegative())
3190 return ReplaceInstUsesWith(I, Builder->getTrue());
3192 case ICmpInst::ICMP_SGT:
3193 // (float)int > 4.4 --> int > 4
3194 // (float)int > -4.4 --> int >= -4
3195 if (RHS.isNegative())
3196 Pred = ICmpInst::ICMP_SGE;
3198 case ICmpInst::ICMP_UGE:
3199 // (float)int >= -4.4 --> true
3200 // (float)int >= 4.4 --> int > 4
3201 if (RHS.isNegative())
3202 return ReplaceInstUsesWith(I, Builder->getTrue());
3203 Pred = ICmpInst::ICMP_UGT;
3205 case ICmpInst::ICMP_SGE:
3206 // (float)int >= -4.4 --> int >= -4
3207 // (float)int >= 4.4 --> int > 4
3208 if (!RHS.isNegative())
3209 Pred = ICmpInst::ICMP_SGT;
3215 // Lower this FP comparison into an appropriate integer version of the
3217 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
3220 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
3221 bool Changed = false;
3223 /// Orders the operands of the compare so that they are listed from most
3224 /// complex to least complex. This puts constants before unary operators,
3225 /// before binary operators.
3226 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
3231 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3233 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
3234 return ReplaceInstUsesWith(I, V);
3236 // Simplify 'fcmp pred X, X'
3238 switch (I.getPredicate()) {
3239 default: llvm_unreachable("Unknown predicate!");
3240 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
3241 case FCmpInst::FCMP_ULT: // True if unordered or less than
3242 case FCmpInst::FCMP_UGT: // True if unordered or greater than
3243 case FCmpInst::FCMP_UNE: // True if unordered or not equal
3244 // Canonicalize these to be 'fcmp uno %X, 0.0'.
3245 I.setPredicate(FCmpInst::FCMP_UNO);
3246 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3249 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
3250 case FCmpInst::FCMP_OEQ: // True if ordered and equal
3251 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
3252 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
3253 // Canonicalize these to be 'fcmp ord %X, 0.0'.
3254 I.setPredicate(FCmpInst::FCMP_ORD);
3255 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3260 // Handle fcmp with constant RHS
3261 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3262 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3263 switch (LHSI->getOpcode()) {
3264 case Instruction::FPExt: {
3265 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
3266 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
3267 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
3271 const fltSemantics *Sem;
3272 // FIXME: This shouldn't be here.
3273 if (LHSExt->getSrcTy()->isHalfTy())
3274 Sem = &APFloat::IEEEhalf;
3275 else if (LHSExt->getSrcTy()->isFloatTy())
3276 Sem = &APFloat::IEEEsingle;
3277 else if (LHSExt->getSrcTy()->isDoubleTy())
3278 Sem = &APFloat::IEEEdouble;
3279 else if (LHSExt->getSrcTy()->isFP128Ty())
3280 Sem = &APFloat::IEEEquad;
3281 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
3282 Sem = &APFloat::x87DoubleExtended;
3283 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
3284 Sem = &APFloat::PPCDoubleDouble;
3289 APFloat F = RHSF->getValueAPF();
3290 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
3292 // Avoid lossy conversions and denormals. Zero is a special case
3293 // that's OK to convert.
3297 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
3298 APFloat::cmpLessThan) || Fabs.isZero()))
3300 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3301 ConstantFP::get(RHSC->getContext(), F));
3304 case Instruction::PHI:
3305 // Only fold fcmp into the PHI if the phi and fcmp are in the same
3306 // block. If in the same block, we're encouraging jump threading. If
3307 // not, we are just pessimizing the code by making an i1 phi.
3308 if (LHSI->getParent() == I.getParent())
3309 if (Instruction *NV = FoldOpIntoPhi(I))
3312 case Instruction::SIToFP:
3313 case Instruction::UIToFP:
3314 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
3317 case Instruction::Select: {
3318 // If either operand of the select is a constant, we can fold the
3319 // comparison into the select arms, which will cause one to be
3320 // constant folded and the select turned into a bitwise or.
3321 Value *Op1 = 0, *Op2 = 0;
3322 if (LHSI->hasOneUse()) {
3323 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3324 // Fold the known value into the constant operand.
3325 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3326 // Insert a new FCmp of the other select operand.
3327 Op2 = Builder->CreateFCmp(I.getPredicate(),
3328 LHSI->getOperand(2), RHSC, I.getName());
3329 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3330 // Fold the known value into the constant operand.
3331 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3332 // Insert a new FCmp of the other select operand.
3333 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
3339 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3342 case Instruction::FSub: {
3343 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3345 if (match(LHSI, m_FNeg(m_Value(Op))))
3346 return new FCmpInst(I.getSwappedPredicate(), Op,
3347 ConstantExpr::getFNeg(RHSC));
3350 case Instruction::Load:
3351 if (GetElementPtrInst *GEP =
3352 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3353 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3354 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3355 !cast<LoadInst>(LHSI)->isVolatile())
3356 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3360 case Instruction::Call: {
3361 CallInst *CI = cast<CallInst>(LHSI);
3363 // Various optimization for fabs compared with zero.
3364 if (RHSC->isNullValue() && CI->getCalledFunction() &&
3365 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3367 if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3368 Func == LibFunc::fabsl) {
3369 switch (I.getPredicate()) {
3371 // fabs(x) < 0 --> false
3372 case FCmpInst::FCMP_OLT:
3373 return ReplaceInstUsesWith(I, Builder->getFalse());
3374 // fabs(x) > 0 --> x != 0
3375 case FCmpInst::FCMP_OGT:
3376 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3378 // fabs(x) <= 0 --> x == 0
3379 case FCmpInst::FCMP_OLE:
3380 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3382 // fabs(x) >= 0 --> !isnan(x)
3383 case FCmpInst::FCMP_OGE:
3384 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3386 // fabs(x) == 0 --> x == 0
3387 // fabs(x) != 0 --> x != 0
3388 case FCmpInst::FCMP_OEQ:
3389 case FCmpInst::FCMP_UEQ:
3390 case FCmpInst::FCMP_ONE:
3391 case FCmpInst::FCMP_UNE:
3392 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3401 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
3403 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
3404 return new FCmpInst(I.getSwappedPredicate(), X, Y);
3406 // fcmp (fpext x), (fpext y) -> fcmp x, y
3407 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3408 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3409 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3410 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3411 RHSExt->getOperand(0));
3413 return Changed ? &I : 0;