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) return 0;
232 Constant *Init = GV->getInitializer();
233 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
236 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
237 if (ArrayElementCount > 1024) return 0; // Don't blow up on huge arrays.
239 // There are many forms of this optimization we can handle, for now, just do
240 // the simple index into a single-dimensional array.
242 // Require: GEP GV, 0, i {{, constant indices}}
243 if (GEP->getNumOperands() < 3 ||
244 !isa<ConstantInt>(GEP->getOperand(1)) ||
245 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
246 isa<Constant>(GEP->getOperand(2)))
249 // Check that indices after the variable are constants and in-range for the
250 // type they index. Collect the indices. This is typically for arrays of
252 SmallVector<unsigned, 4> LaterIndices;
254 Type *EltTy = Init->getType()->getArrayElementType();
255 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
256 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
257 if (Idx == 0) return 0; // Variable index.
259 uint64_t IdxVal = Idx->getZExtValue();
260 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
262 if (StructType *STy = dyn_cast<StructType>(EltTy))
263 EltTy = STy->getElementType(IdxVal);
264 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
265 if (IdxVal >= ATy->getNumElements()) return 0;
266 EltTy = ATy->getElementType();
268 return 0; // Unknown type.
271 LaterIndices.push_back(IdxVal);
274 enum { Overdefined = -3, Undefined = -2 };
276 // Variables for our state machines.
278 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
279 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
280 // and 87 is the second (and last) index. FirstTrueElement is -2 when
281 // undefined, otherwise set to the first true element. SecondTrueElement is
282 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
283 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
285 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
286 // form "i != 47 & i != 87". Same state transitions as for true elements.
287 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
289 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
290 /// define a state machine that triggers for ranges of values that the index
291 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
292 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
293 /// index in the range (inclusive). We use -2 for undefined here because we
294 /// use relative comparisons and don't want 0-1 to match -1.
295 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
297 // MagicBitvector - This is a magic bitvector where we set a bit if the
298 // comparison is true for element 'i'. If there are 64 elements or less in
299 // the array, this will fully represent all the comparison results.
300 uint64_t MagicBitvector = 0;
303 // Scan the array and see if one of our patterns matches.
304 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
305 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
306 Constant *Elt = Init->getAggregateElement(i);
307 if (Elt == 0) return 0;
309 // If this is indexing an array of structures, get the structure element.
310 if (!LaterIndices.empty())
311 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
313 // If the element is masked, handle it.
314 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
316 // Find out if the comparison would be true or false for the i'th element.
317 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
318 CompareRHS, TD, TLI);
319 // If the result is undef for this element, ignore it.
320 if (isa<UndefValue>(C)) {
321 // Extend range state machines to cover this element in case there is an
322 // undef in the middle of the range.
323 if (TrueRangeEnd == (int)i-1)
325 if (FalseRangeEnd == (int)i-1)
330 // If we can't compute the result for any of the elements, we have to give
331 // up evaluating the entire conditional.
332 if (!isa<ConstantInt>(C)) return 0;
334 // Otherwise, we know if the comparison is true or false for this element,
335 // update our state machines.
336 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
338 // State machine for single/double/range index comparison.
340 // Update the TrueElement state machine.
341 if (FirstTrueElement == Undefined)
342 FirstTrueElement = TrueRangeEnd = i; // First true element.
344 // Update double-compare state machine.
345 if (SecondTrueElement == Undefined)
346 SecondTrueElement = i;
348 SecondTrueElement = Overdefined;
350 // Update range state machine.
351 if (TrueRangeEnd == (int)i-1)
354 TrueRangeEnd = Overdefined;
357 // Update the FalseElement state machine.
358 if (FirstFalseElement == Undefined)
359 FirstFalseElement = FalseRangeEnd = i; // First false element.
361 // Update double-compare state machine.
362 if (SecondFalseElement == Undefined)
363 SecondFalseElement = i;
365 SecondFalseElement = Overdefined;
367 // Update range state machine.
368 if (FalseRangeEnd == (int)i-1)
371 FalseRangeEnd = Overdefined;
376 // If this element is in range, update our magic bitvector.
377 if (i < 64 && IsTrueForElt)
378 MagicBitvector |= 1ULL << i;
380 // If all of our states become overdefined, bail out early. Since the
381 // predicate is expensive, only check it every 8 elements. This is only
382 // really useful for really huge arrays.
383 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
384 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
385 FalseRangeEnd == Overdefined)
389 // Now that we've scanned the entire array, emit our new comparison(s). We
390 // order the state machines in complexity of the generated code.
391 Value *Idx = GEP->getOperand(2);
393 // If the index is larger than the pointer size of the target, truncate the
394 // index down like the GEP would do implicitly. We don't have to do this for
395 // an inbounds GEP because the index can't be out of range.
396 if (!GEP->isInBounds() &&
397 Idx->getType()->getPrimitiveSizeInBits() > TD->getPointerSizeInBits())
398 Idx = Builder->CreateTrunc(Idx, TD->getIntPtrType(Idx->getContext()));
400 // If the comparison is only true for one or two elements, emit direct
402 if (SecondTrueElement != Overdefined) {
403 // None true -> false.
404 if (FirstTrueElement == Undefined)
405 return ReplaceInstUsesWith(ICI, Builder->getFalse());
407 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
409 // True for one element -> 'i == 47'.
410 if (SecondTrueElement == Undefined)
411 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
413 // True for two elements -> 'i == 47 | i == 72'.
414 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
415 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
416 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
417 return BinaryOperator::CreateOr(C1, C2);
420 // If the comparison is only false for one or two elements, emit direct
422 if (SecondFalseElement != Overdefined) {
423 // None false -> true.
424 if (FirstFalseElement == Undefined)
425 return ReplaceInstUsesWith(ICI, Builder->getTrue());
427 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
429 // False for one element -> 'i != 47'.
430 if (SecondFalseElement == Undefined)
431 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
433 // False for two elements -> 'i != 47 & i != 72'.
434 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
435 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
436 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
437 return BinaryOperator::CreateAnd(C1, C2);
440 // If the comparison can be replaced with a range comparison for the elements
441 // where it is true, emit the range check.
442 if (TrueRangeEnd != Overdefined) {
443 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
445 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
446 if (FirstTrueElement) {
447 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
448 Idx = Builder->CreateAdd(Idx, Offs);
451 Value *End = ConstantInt::get(Idx->getType(),
452 TrueRangeEnd-FirstTrueElement+1);
453 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
456 // False range check.
457 if (FalseRangeEnd != Overdefined) {
458 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
459 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
460 if (FirstFalseElement) {
461 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
462 Idx = Builder->CreateAdd(Idx, Offs);
465 Value *End = ConstantInt::get(Idx->getType(),
466 FalseRangeEnd-FirstFalseElement);
467 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
471 // If a magic bitvector captures the entire comparison state
472 // of this load, replace it with computation that does:
473 // ((magic_cst >> i) & 1) != 0
477 // Look for an appropriate type:
478 // - The type of Idx if the magic fits
479 // - The smallest fitting legal type if we have a DataLayout
481 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
484 Ty = TD->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
485 else if (ArrayElementCount <= 32)
486 Ty = Type::getInt32Ty(Init->getContext());
489 Value *V = Builder->CreateIntCast(Idx, Ty, false);
490 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
491 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
492 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
500 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
501 /// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
502 /// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
503 /// be complex, and scales are involved. The above expression would also be
504 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
505 /// This later form is less amenable to optimization though, and we are allowed
506 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
508 /// If we can't emit an optimized form for this expression, this returns null.
510 static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
511 DataLayout &TD = *IC.getDataLayout();
512 gep_type_iterator GTI = gep_type_begin(GEP);
514 // Check to see if this gep only has a single variable index. If so, and if
515 // any constant indices are a multiple of its scale, then we can compute this
516 // in terms of the scale of the variable index. For example, if the GEP
517 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
518 // because the expression will cross zero at the same point.
519 unsigned i, e = GEP->getNumOperands();
521 for (i = 1; i != e; ++i, ++GTI) {
522 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
523 // Compute the aggregate offset of constant indices.
524 if (CI->isZero()) continue;
526 // Handle a struct index, which adds its field offset to the pointer.
527 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
528 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
530 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
531 Offset += Size*CI->getSExtValue();
534 // Found our variable index.
539 // If there are no variable indices, we must have a constant offset, just
540 // evaluate it the general way.
541 if (i == e) return 0;
543 Value *VariableIdx = GEP->getOperand(i);
544 // Determine the scale factor of the variable element. For example, this is
545 // 4 if the variable index is into an array of i32.
546 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
548 // Verify that there are no other variable indices. If so, emit the hard way.
549 for (++i, ++GTI; i != e; ++i, ++GTI) {
550 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
553 // Compute the aggregate offset of constant indices.
554 if (CI->isZero()) continue;
556 // Handle a struct index, which adds its field offset to the pointer.
557 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
558 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
560 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
561 Offset += Size*CI->getSExtValue();
565 // Okay, we know we have a single variable index, which must be a
566 // pointer/array/vector index. If there is no offset, life is simple, return
568 unsigned IntPtrWidth = TD.getPointerSizeInBits();
570 // Cast to intptrty in case a truncation occurs. If an extension is needed,
571 // we don't need to bother extending: the extension won't affect where the
572 // computation crosses zero.
573 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
574 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
575 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
580 // Otherwise, there is an index. The computation we will do will be modulo
581 // the pointer size, so get it.
582 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
584 Offset &= PtrSizeMask;
585 VariableScale &= PtrSizeMask;
587 // To do this transformation, any constant index must be a multiple of the
588 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
589 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
590 // multiple of the variable scale.
591 int64_t NewOffs = Offset / (int64_t)VariableScale;
592 if (Offset != NewOffs*(int64_t)VariableScale)
595 // Okay, we can do this evaluation. Start by converting the index to intptr.
596 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
597 if (VariableIdx->getType() != IntPtrTy)
598 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
600 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
601 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
604 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
605 /// else. At this point we know that the GEP is on the LHS of the comparison.
606 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
607 ICmpInst::Predicate Cond,
609 // Don't transform signed compares of GEPs into index compares. Even if the
610 // GEP is inbounds, the final add of the base pointer can have signed overflow
611 // and would change the result of the icmp.
612 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
613 // the maximum signed value for the pointer type.
614 if (ICmpInst::isSigned(Cond))
617 // Look through bitcasts.
618 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
619 RHS = BCI->getOperand(0);
621 Value *PtrBase = GEPLHS->getOperand(0);
622 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
623 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
624 // This transformation (ignoring the base and scales) is valid because we
625 // know pointers can't overflow since the gep is inbounds. See if we can
626 // output an optimized form.
627 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
629 // If not, synthesize the offset the hard way.
631 Offset = EmitGEPOffset(GEPLHS);
632 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
633 Constant::getNullValue(Offset->getType()));
634 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
635 // If the base pointers are different, but the indices are the same, just
636 // compare the base pointer.
637 if (PtrBase != GEPRHS->getOperand(0)) {
638 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
639 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
640 GEPRHS->getOperand(0)->getType();
642 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
643 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
644 IndicesTheSame = false;
648 // If all indices are the same, just compare the base pointers.
650 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
651 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
653 // If we're comparing GEPs with two base pointers that only differ in type
654 // and both GEPs have only constant indices or just one use, then fold
655 // the compare with the adjusted indices.
656 if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
657 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
658 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
659 PtrBase->stripPointerCasts() ==
660 GEPRHS->getOperand(0)->stripPointerCasts()) {
661 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
662 EmitGEPOffset(GEPLHS),
663 EmitGEPOffset(GEPRHS));
664 return ReplaceInstUsesWith(I, Cmp);
667 // Otherwise, the base pointers are different and the indices are
668 // different, bail out.
672 // If one of the GEPs has all zero indices, recurse.
673 bool AllZeros = true;
674 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
675 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
676 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
681 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
682 ICmpInst::getSwappedPredicate(Cond), I);
684 // If the other GEP has all zero indices, recurse.
686 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
687 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
688 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
693 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
695 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
696 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
697 // If the GEPs only differ by one index, compare it.
698 unsigned NumDifferences = 0; // Keep track of # differences.
699 unsigned DiffOperand = 0; // The operand that differs.
700 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
701 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
702 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
703 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
704 // Irreconcilable differences.
708 if (NumDifferences++) break;
713 if (NumDifferences == 0) // SAME GEP?
714 return ReplaceInstUsesWith(I, // No comparison is needed here.
715 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
717 else if (NumDifferences == 1 && GEPsInBounds) {
718 Value *LHSV = GEPLHS->getOperand(DiffOperand);
719 Value *RHSV = GEPRHS->getOperand(DiffOperand);
720 // Make sure we do a signed comparison here.
721 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
725 // Only lower this if the icmp is the only user of the GEP or if we expect
726 // the result to fold to a constant!
729 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
730 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
731 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
732 Value *L = EmitGEPOffset(GEPLHS);
733 Value *R = EmitGEPOffset(GEPRHS);
734 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
740 /// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
741 Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
742 Value *X, ConstantInt *CI,
743 ICmpInst::Predicate Pred,
745 // If we have X+0, exit early (simplifying logic below) and let it get folded
746 // elsewhere. icmp X+0, X -> icmp X, X
748 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
749 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
752 // (X+4) == X -> false.
753 if (Pred == ICmpInst::ICMP_EQ)
754 return ReplaceInstUsesWith(ICI, Builder->getFalse());
756 // (X+4) != X -> true.
757 if (Pred == ICmpInst::ICMP_NE)
758 return ReplaceInstUsesWith(ICI, Builder->getTrue());
760 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
761 // so the values can never be equal. Similarly for all other "or equals"
764 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
765 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
766 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
767 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
769 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
770 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
773 // (X+1) >u X --> X <u (0-1) --> X != 255
774 // (X+2) >u X --> X <u (0-2) --> X <u 254
775 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
776 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
777 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
779 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
780 ConstantInt *SMax = ConstantInt::get(X->getContext(),
781 APInt::getSignedMaxValue(BitWidth));
783 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
784 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
785 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
786 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
787 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
788 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
789 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
790 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
792 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
793 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
794 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
795 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
796 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
797 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
799 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
800 Constant *C = Builder->getInt(CI->getValue()-1);
801 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
804 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
805 /// and CmpRHS are both known to be integer constants.
806 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
807 ConstantInt *DivRHS) {
808 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
809 const APInt &CmpRHSV = CmpRHS->getValue();
811 // FIXME: If the operand types don't match the type of the divide
812 // then don't attempt this transform. The code below doesn't have the
813 // logic to deal with a signed divide and an unsigned compare (and
814 // vice versa). This is because (x /s C1) <s C2 produces different
815 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
816 // (x /u C1) <u C2. Simply casting the operands and result won't
817 // work. :( The if statement below tests that condition and bails
819 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
820 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
822 if (DivRHS->isZero())
823 return 0; // The ProdOV computation fails on divide by zero.
824 if (DivIsSigned && DivRHS->isAllOnesValue())
825 return 0; // The overflow computation also screws up here
826 if (DivRHS->isOne()) {
827 // This eliminates some funny cases with INT_MIN.
828 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
832 // Compute Prod = CI * DivRHS. We are essentially solving an equation
833 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
834 // C2 (CI). By solving for X we can turn this into a range check
835 // instead of computing a divide.
836 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
838 // Determine if the product overflows by seeing if the product is
839 // not equal to the divide. Make sure we do the same kind of divide
840 // as in the LHS instruction that we're folding.
841 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
842 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
844 // Get the ICmp opcode
845 ICmpInst::Predicate Pred = ICI.getPredicate();
847 /// If the division is known to be exact, then there is no remainder from the
848 /// divide, so the covered range size is unit, otherwise it is the divisor.
849 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
851 // Figure out the interval that is being checked. For example, a comparison
852 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
853 // Compute this interval based on the constants involved and the signedness of
854 // the compare/divide. This computes a half-open interval, keeping track of
855 // whether either value in the interval overflows. After analysis each
856 // overflow variable is set to 0 if it's corresponding bound variable is valid
857 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
858 int LoOverflow = 0, HiOverflow = 0;
859 Constant *LoBound = 0, *HiBound = 0;
861 if (!DivIsSigned) { // udiv
862 // e.g. X/5 op 3 --> [15, 20)
864 HiOverflow = LoOverflow = ProdOV;
866 // If this is not an exact divide, then many values in the range collapse
867 // to the same result value.
868 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
871 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
872 if (CmpRHSV == 0) { // (X / pos) op 0
873 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
874 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
876 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
877 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
878 HiOverflow = LoOverflow = ProdOV;
880 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
881 } else { // (X / pos) op neg
882 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
883 HiBound = AddOne(Prod);
884 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
886 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
887 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
890 } else if (DivRHS->isNegative()) { // Divisor is < 0.
892 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
893 if (CmpRHSV == 0) { // (X / neg) op 0
894 // e.g. X/-5 op 0 --> [-4, 5)
895 LoBound = AddOne(RangeSize);
896 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
897 if (HiBound == DivRHS) { // -INTMIN = INTMIN
898 HiOverflow = 1; // [INTMIN+1, overflow)
899 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
901 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
902 // e.g. X/-5 op 3 --> [-19, -14)
903 HiBound = AddOne(Prod);
904 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
906 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
907 } else { // (X / neg) op neg
908 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
909 LoOverflow = HiOverflow = ProdOV;
911 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
914 // Dividing by a negative swaps the condition. LT <-> GT
915 Pred = ICmpInst::getSwappedPredicate(Pred);
918 Value *X = DivI->getOperand(0);
920 default: llvm_unreachable("Unhandled icmp opcode!");
921 case ICmpInst::ICMP_EQ:
922 if (LoOverflow && HiOverflow)
923 return ReplaceInstUsesWith(ICI, Builder->getFalse());
925 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
926 ICmpInst::ICMP_UGE, X, LoBound);
928 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
929 ICmpInst::ICMP_ULT, X, HiBound);
930 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
932 case ICmpInst::ICMP_NE:
933 if (LoOverflow && HiOverflow)
934 return ReplaceInstUsesWith(ICI, Builder->getTrue());
936 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
937 ICmpInst::ICMP_ULT, X, LoBound);
939 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
940 ICmpInst::ICMP_UGE, X, HiBound);
941 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
942 DivIsSigned, false));
943 case ICmpInst::ICMP_ULT:
944 case ICmpInst::ICMP_SLT:
945 if (LoOverflow == +1) // Low bound is greater than input range.
946 return ReplaceInstUsesWith(ICI, Builder->getTrue());
947 if (LoOverflow == -1) // Low bound is less than input range.
948 return ReplaceInstUsesWith(ICI, Builder->getFalse());
949 return new ICmpInst(Pred, X, LoBound);
950 case ICmpInst::ICMP_UGT:
951 case ICmpInst::ICMP_SGT:
952 if (HiOverflow == +1) // High bound greater than input range.
953 return ReplaceInstUsesWith(ICI, Builder->getFalse());
954 if (HiOverflow == -1) // High bound less than input range.
955 return ReplaceInstUsesWith(ICI, Builder->getTrue());
956 if (Pred == ICmpInst::ICMP_UGT)
957 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
958 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
962 /// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
963 Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
964 ConstantInt *ShAmt) {
965 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
967 // Check that the shift amount is in range. If not, don't perform
968 // undefined shifts. When the shift is visited it will be
970 uint32_t TypeBits = CmpRHSV.getBitWidth();
971 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
972 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
975 if (!ICI.isEquality()) {
976 // If we have an unsigned comparison and an ashr, we can't simplify this.
977 // Similarly for signed comparisons with lshr.
978 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
981 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
982 // by a power of 2. Since we already have logic to simplify these,
983 // transform to div and then simplify the resultant comparison.
984 if (Shr->getOpcode() == Instruction::AShr &&
985 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
988 // Revisit the shift (to delete it).
992 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
995 Shr->getOpcode() == Instruction::AShr ?
996 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
997 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
999 ICI.setOperand(0, Tmp);
1001 // If the builder folded the binop, just return it.
1002 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
1006 // Otherwise, fold this div/compare.
1007 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1008 TheDiv->getOpcode() == Instruction::UDiv);
1010 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1011 assert(Res && "This div/cst should have folded!");
1016 // If we are comparing against bits always shifted out, the
1017 // comparison cannot succeed.
1018 APInt Comp = CmpRHSV << ShAmtVal;
1019 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
1020 if (Shr->getOpcode() == Instruction::LShr)
1021 Comp = Comp.lshr(ShAmtVal);
1023 Comp = Comp.ashr(ShAmtVal);
1025 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1026 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1027 Constant *Cst = Builder->getInt1(IsICMP_NE);
1028 return ReplaceInstUsesWith(ICI, Cst);
1031 // Otherwise, check to see if the bits shifted out are known to be zero.
1032 // If so, we can compare against the unshifted value:
1033 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
1034 if (Shr->hasOneUse() && Shr->isExact())
1035 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
1037 if (Shr->hasOneUse()) {
1038 // Otherwise strength reduce the shift into an and.
1039 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1040 Constant *Mask = Builder->getInt(Val);
1042 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1043 Mask, Shr->getName()+".mask");
1044 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1050 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1052 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1055 const APInt &RHSV = RHS->getValue();
1057 switch (LHSI->getOpcode()) {
1058 case Instruction::Trunc:
1059 if (ICI.isEquality() && LHSI->hasOneUse()) {
1060 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1061 // of the high bits truncated out of x are known.
1062 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1063 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
1064 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
1065 ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
1067 // If all the high bits are known, we can do this xform.
1068 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1069 // Pull in the high bits from known-ones set.
1070 APInt NewRHS = RHS->getValue().zext(SrcBits);
1071 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
1072 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1073 Builder->getInt(NewRHS));
1078 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
1079 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1080 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1082 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1083 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1084 Value *CompareVal = LHSI->getOperand(0);
1086 // If the sign bit of the XorCST is not set, there is no change to
1087 // the operation, just stop using the Xor.
1088 if (!XorCST->isNegative()) {
1089 ICI.setOperand(0, CompareVal);
1094 // Was the old condition true if the operand is positive?
1095 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
1097 // If so, the new one isn't.
1098 isTrueIfPositive ^= true;
1100 if (isTrueIfPositive)
1101 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1104 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1108 if (LHSI->hasOneUse()) {
1109 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1110 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
1111 const APInt &SignBit = XorCST->getValue();
1112 ICmpInst::Predicate Pred = ICI.isSigned()
1113 ? ICI.getUnsignedPredicate()
1114 : ICI.getSignedPredicate();
1115 return new ICmpInst(Pred, LHSI->getOperand(0),
1116 Builder->getInt(RHSV ^ SignBit));
1119 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
1120 if (!ICI.isEquality() && XorCST->isMaxValue(true)) {
1121 const APInt &NotSignBit = XorCST->getValue();
1122 ICmpInst::Predicate Pred = ICI.isSigned()
1123 ? ICI.getUnsignedPredicate()
1124 : ICI.getSignedPredicate();
1125 Pred = ICI.getSwappedPredicate(Pred);
1126 return new ICmpInst(Pred, LHSI->getOperand(0),
1127 Builder->getInt(RHSV ^ NotSignBit));
1132 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
1133 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1134 LHSI->getOperand(0)->hasOneUse()) {
1135 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1137 // If the LHS is an AND of a truncating cast, we can widen the
1138 // and/compare to be the input width without changing the value
1139 // produced, eliminating a cast.
1140 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1141 // We can do this transformation if either the AND constant does not
1142 // have its sign bit set or if it is an equality comparison.
1143 // Extending a relational comparison when we're checking the sign
1144 // bit would not work.
1145 if (ICI.isEquality() ||
1146 (!AndCST->isNegative() && RHSV.isNonNegative())) {
1148 Builder->CreateAnd(Cast->getOperand(0),
1149 ConstantExpr::getZExt(AndCST, Cast->getSrcTy()));
1150 NewAnd->takeName(LHSI);
1151 return new ICmpInst(ICI.getPredicate(), NewAnd,
1152 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
1156 // If the LHS is an AND of a zext, and we have an equality compare, we can
1157 // shrink the and/compare to the smaller type, eliminating the cast.
1158 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
1159 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
1160 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1161 // should fold the icmp to true/false in that case.
1162 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1164 Builder->CreateAnd(Cast->getOperand(0),
1165 ConstantExpr::getTrunc(AndCST, Ty));
1166 NewAnd->takeName(LHSI);
1167 return new ICmpInst(ICI.getPredicate(), NewAnd,
1168 ConstantExpr::getTrunc(RHS, Ty));
1172 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1173 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1174 // happens a LOT in code produced by the C front-end, for bitfield
1176 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1177 if (Shift && !Shift->isShift())
1181 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
1182 Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
1183 Type *AndTy = AndCST->getType(); // Type of the and.
1185 // We can fold this as long as we can't shift unknown bits
1186 // into the mask. This can only happen with signed shift
1187 // rights, as they sign-extend.
1189 bool CanFold = Shift->isLogicalShift();
1191 // To test for the bad case of the signed shr, see if any
1192 // of the bits shifted in could be tested after the mask.
1193 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1194 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
1196 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
1197 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
1198 AndCST->getValue()) == 0)
1204 if (Shift->getOpcode() == Instruction::Shl)
1205 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1207 NewCst = ConstantExpr::getShl(RHS, ShAmt);
1209 // Check to see if we are shifting out any of the bits being
1211 if (ConstantExpr::get(Shift->getOpcode(),
1212 NewCst, ShAmt) != RHS) {
1213 // If we shifted bits out, the fold is not going to work out.
1214 // As a special case, check to see if this means that the
1215 // result is always true or false now.
1216 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1217 return ReplaceInstUsesWith(ICI, Builder->getFalse());
1218 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1219 return ReplaceInstUsesWith(ICI, Builder->getTrue());
1221 ICI.setOperand(1, NewCst);
1222 Constant *NewAndCST;
1223 if (Shift->getOpcode() == Instruction::Shl)
1224 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1226 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1227 LHSI->setOperand(1, NewAndCST);
1228 LHSI->setOperand(0, Shift->getOperand(0));
1229 Worklist.Add(Shift); // Shift is dead.
1235 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1236 // preferable because it allows the C<<Y expression to be hoisted out
1237 // of a loop if Y is invariant and X is not.
1238 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1239 ICI.isEquality() && !Shift->isArithmeticShift() &&
1240 !isa<Constant>(Shift->getOperand(0))) {
1243 if (Shift->getOpcode() == Instruction::LShr) {
1244 NS = Builder->CreateShl(AndCST, Shift->getOperand(1));
1246 // Insert a logical shift.
1247 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1));
1250 // Compute X & (C << Y).
1252 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1254 ICI.setOperand(0, NewAnd);
1258 // Replace ((X & AndCST) > RHSV) with ((X & AndCST) != 0), if any
1259 // bit set in (X & AndCST) will produce a result greater than RHSV.
1260 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
1261 unsigned NTZ = AndCST->getValue().countTrailingZeros();
1262 if ((NTZ < AndCST->getBitWidth()) &&
1263 APInt::getOneBitSet(AndCST->getBitWidth(), NTZ).ugt(RHSV))
1264 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1265 Constant::getNullValue(RHS->getType()));
1269 // Try to optimize things like "A[i]&42 == 0" to index computations.
1270 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1271 if (GetElementPtrInst *GEP =
1272 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1273 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1274 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1275 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1276 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1277 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1283 case Instruction::Or: {
1284 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1287 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1288 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1289 // -> and (icmp eq P, null), (icmp eq Q, null).
1290 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1291 Constant::getNullValue(P->getType()));
1292 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1293 Constant::getNullValue(Q->getType()));
1295 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1296 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1298 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1304 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1305 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1308 // If this is a signed comparison to 0 and the mul is sign preserving,
1309 // use the mul LHS operand instead.
1310 ICmpInst::Predicate pred = ICI.getPredicate();
1311 if (isSignTest(pred, RHS) && !Val->isZero() &&
1312 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1313 return new ICmpInst(Val->isNegative() ?
1314 ICmpInst::getSwappedPredicate(pred) : pred,
1315 LHSI->getOperand(0),
1316 Constant::getNullValue(RHS->getType()));
1321 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
1322 uint32_t TypeBits = RHSV.getBitWidth();
1323 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1326 // (1 << X) pred P2 -> X pred Log2(P2)
1327 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1328 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1329 ICmpInst::Predicate Pred = ICI.getPredicate();
1330 if (ICI.isUnsigned()) {
1331 if (!RHSVIsPowerOf2) {
1332 // (1 << X) < 30 -> X <= 4
1333 // (1 << X) <= 30 -> X <= 4
1334 // (1 << X) >= 30 -> X > 4
1335 // (1 << X) > 30 -> X > 4
1336 if (Pred == ICmpInst::ICMP_ULT)
1337 Pred = ICmpInst::ICMP_ULE;
1338 else if (Pred == ICmpInst::ICMP_UGE)
1339 Pred = ICmpInst::ICMP_UGT;
1341 unsigned RHSLog2 = RHSV.logBase2();
1343 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
1344 // (1 << X) > 2147483648 -> X > 31 -> false
1345 // (1 << X) <= 2147483648 -> X <= 31 -> true
1346 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1347 if (RHSLog2 == TypeBits-1) {
1348 if (Pred == ICmpInst::ICMP_UGE)
1349 Pred = ICmpInst::ICMP_EQ;
1350 else if (Pred == ICmpInst::ICMP_UGT)
1351 return ReplaceInstUsesWith(ICI, Builder->getFalse());
1352 else if (Pred == ICmpInst::ICMP_ULE)
1353 return ReplaceInstUsesWith(ICI, Builder->getTrue());
1354 else if (Pred == ICmpInst::ICMP_ULT)
1355 Pred = ICmpInst::ICMP_NE;
1358 return new ICmpInst(Pred, X,
1359 ConstantInt::get(RHS->getType(), RHSLog2));
1360 } else if (ICI.isSigned()) {
1361 if (RHSV.isAllOnesValue()) {
1362 // (1 << X) <= -1 -> X == 31
1363 if (Pred == ICmpInst::ICMP_SLE)
1364 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1365 ConstantInt::get(RHS->getType(), TypeBits-1));
1367 // (1 << X) > -1 -> X != 31
1368 if (Pred == ICmpInst::ICMP_SGT)
1369 return new ICmpInst(ICmpInst::ICMP_NE, X,
1370 ConstantInt::get(RHS->getType(), TypeBits-1));
1372 // (1 << X) < 0 -> X == 31
1373 // (1 << X) <= 0 -> X == 31
1374 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1375 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1376 ConstantInt::get(RHS->getType(), TypeBits-1));
1378 // (1 << X) >= 0 -> X != 31
1379 // (1 << X) > 0 -> X != 31
1380 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1381 return new ICmpInst(ICmpInst::ICMP_NE, X,
1382 ConstantInt::get(RHS->getType(), TypeBits-1));
1384 } else if (ICI.isEquality()) {
1386 return new ICmpInst(
1387 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
1389 return ReplaceInstUsesWith(
1390 ICI, Pred == ICmpInst::ICMP_EQ ? Builder->getFalse()
1391 : Builder->getTrue());
1397 // Check that the shift amount is in range. If not, don't perform
1398 // undefined shifts. When the shift is visited it will be
1400 if (ShAmt->uge(TypeBits))
1403 if (ICI.isEquality()) {
1404 // If we are comparing against bits always shifted out, the
1405 // comparison cannot succeed.
1407 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1409 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1410 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1411 Constant *Cst = Builder->getInt1(IsICMP_NE);
1412 return ReplaceInstUsesWith(ICI, Cst);
1415 // If the shift is NUW, then it is just shifting out zeros, no need for an
1417 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1418 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1419 ConstantExpr::getLShr(RHS, ShAmt));
1421 // If the shift is NSW and we compare to 0, then it is just shifting out
1422 // sign bits, no need for an AND either.
1423 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1424 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1425 ConstantExpr::getLShr(RHS, ShAmt));
1427 if (LHSI->hasOneUse()) {
1428 // Otherwise strength reduce the shift into an and.
1429 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1430 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
1431 TypeBits - ShAmtVal));
1434 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1435 return new ICmpInst(ICI.getPredicate(), And,
1436 ConstantExpr::getLShr(RHS, ShAmt));
1440 // If this is a signed comparison to 0 and the shift is sign preserving,
1441 // use the shift LHS operand instead.
1442 ICmpInst::Predicate pred = ICI.getPredicate();
1443 if (isSignTest(pred, RHS) &&
1444 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1445 return new ICmpInst(pred,
1446 LHSI->getOperand(0),
1447 Constant::getNullValue(RHS->getType()));
1449 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1450 bool TrueIfSigned = false;
1451 if (LHSI->hasOneUse() &&
1452 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1453 // (X << 31) <s 0 --> (X&1) != 0
1454 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
1455 APInt::getOneBitSet(TypeBits,
1456 TypeBits-ShAmt->getZExtValue()-1));
1458 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1459 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1460 And, Constant::getNullValue(And->getType()));
1463 // Transform (icmp pred iM (shl iM %v, N), CI)
1464 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1465 // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
1466 // This enables to get rid of the shift in favor of a trunc which can be
1467 // free on the target. It has the additional benefit of comparing to a
1468 // smaller constant, which will be target friendly.
1469 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
1470 if (LHSI->hasOneUse() &&
1471 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
1472 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1473 Constant *NCI = ConstantExpr::getTrunc(
1474 ConstantExpr::getAShr(RHS,
1475 ConstantInt::get(RHS->getType(), Amt)),
1477 return new ICmpInst(ICI.getPredicate(),
1478 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
1485 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
1486 case Instruction::AShr: {
1487 // Handle equality comparisons of shift-by-constant.
1488 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1489 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1490 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
1494 // Handle exact shr's.
1495 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1496 if (RHSV.isMinValue())
1497 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1502 case Instruction::SDiv:
1503 case Instruction::UDiv:
1504 // Fold: icmp pred ([us]div X, C1), C2 -> range test
1505 // Fold this div into the comparison, producing a range check.
1506 // Determine, based on the divide type, what the range is being
1507 // checked. If there is an overflow on the low or high side, remember
1508 // it, otherwise compute the range [low, hi) bounding the new value.
1509 // See: InsertRangeTest above for the kinds of replacements possible.
1510 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1511 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1516 case Instruction::Add:
1517 // Fold: icmp pred (add X, C1), C2
1518 if (!ICI.isEquality()) {
1519 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1521 const APInt &LHSV = LHSC->getValue();
1523 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1526 if (ICI.isSigned()) {
1527 if (CR.getLower().isSignBit()) {
1528 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1529 Builder->getInt(CR.getUpper()));
1530 } else if (CR.getUpper().isSignBit()) {
1531 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1532 Builder->getInt(CR.getLower()));
1535 if (CR.getLower().isMinValue()) {
1536 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1537 Builder->getInt(CR.getUpper()));
1538 } else if (CR.getUpper().isMinValue()) {
1539 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1540 Builder->getInt(CR.getLower()));
1547 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1548 if (ICI.isEquality()) {
1549 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1551 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
1552 // the second operand is a constant, simplify a bit.
1553 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1554 switch (BO->getOpcode()) {
1555 case Instruction::SRem:
1556 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1557 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1558 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
1559 if (V.sgt(1) && V.isPowerOf2()) {
1561 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1563 return new ICmpInst(ICI.getPredicate(), NewRem,
1564 Constant::getNullValue(BO->getType()));
1568 case Instruction::Add:
1569 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1570 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1571 if (BO->hasOneUse())
1572 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1573 ConstantExpr::getSub(RHS, BOp1C));
1574 } else if (RHSV == 0) {
1575 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1576 // efficiently invertible, or if the add has just this one use.
1577 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1579 if (Value *NegVal = dyn_castNegVal(BOp1))
1580 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
1581 if (Value *NegVal = dyn_castNegVal(BOp0))
1582 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
1583 if (BO->hasOneUse()) {
1584 Value *Neg = Builder->CreateNeg(BOp1);
1586 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1590 case Instruction::Xor:
1591 // For the xor case, we can xor two constants together, eliminating
1592 // the explicit xor.
1593 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1594 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1595 ConstantExpr::getXor(RHS, BOC));
1596 } else if (RHSV == 0) {
1597 // Replace ((xor A, B) != 0) with (A != B)
1598 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1602 case Instruction::Sub:
1603 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1604 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1605 if (BO->hasOneUse())
1606 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1607 ConstantExpr::getSub(BOp0C, RHS));
1608 } else if (RHSV == 0) {
1609 // Replace ((sub A, B) != 0) with (A != B)
1610 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1614 case Instruction::Or:
1615 // If bits are being or'd in that are not present in the constant we
1616 // are comparing against, then the comparison could never succeed!
1617 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1618 Constant *NotCI = ConstantExpr::getNot(RHS);
1619 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1620 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
1624 case Instruction::And:
1625 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1626 // If bits are being compared against that are and'd out, then the
1627 // comparison can never succeed!
1628 if ((RHSV & ~BOC->getValue()) != 0)
1629 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
1631 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1632 if (RHS == BOC && RHSV.isPowerOf2())
1633 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1634 ICmpInst::ICMP_NE, LHSI,
1635 Constant::getNullValue(RHS->getType()));
1637 // Don't perform the following transforms if the AND has multiple uses
1638 if (!BO->hasOneUse())
1641 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1642 if (BOC->getValue().isSignBit()) {
1643 Value *X = BO->getOperand(0);
1644 Constant *Zero = Constant::getNullValue(X->getType());
1645 ICmpInst::Predicate pred = isICMP_NE ?
1646 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1647 return new ICmpInst(pred, X, Zero);
1650 // ((X & ~7) == 0) --> X < 8
1651 if (RHSV == 0 && isHighOnes(BOC)) {
1652 Value *X = BO->getOperand(0);
1653 Constant *NegX = ConstantExpr::getNeg(BOC);
1654 ICmpInst::Predicate pred = isICMP_NE ?
1655 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1656 return new ICmpInst(pred, X, NegX);
1660 case Instruction::Mul:
1661 if (RHSV == 0 && BO->hasNoSignedWrap()) {
1662 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1663 // The trivial case (mul X, 0) is handled by InstSimplify
1664 // General case : (mul X, C) != 0 iff X != 0
1665 // (mul X, C) == 0 iff X == 0
1667 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1668 Constant::getNullValue(RHS->getType()));
1674 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1675 // Handle icmp {eq|ne} <intrinsic>, intcst.
1676 switch (II->getIntrinsicID()) {
1677 case Intrinsic::bswap:
1679 ICI.setOperand(0, II->getArgOperand(0));
1680 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
1682 case Intrinsic::ctlz:
1683 case Intrinsic::cttz:
1684 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1685 if (RHSV == RHS->getType()->getBitWidth()) {
1687 ICI.setOperand(0, II->getArgOperand(0));
1688 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1692 case Intrinsic::ctpop:
1693 // popcount(A) == 0 -> A == 0 and likewise for !=
1694 if (RHS->isZero()) {
1696 ICI.setOperand(0, II->getArgOperand(0));
1697 ICI.setOperand(1, RHS);
1709 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1710 /// We only handle extending casts so far.
1712 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1713 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1714 Value *LHSCIOp = LHSCI->getOperand(0);
1715 Type *SrcTy = LHSCIOp->getType();
1716 Type *DestTy = LHSCI->getType();
1719 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
1720 // integer type is the same size as the pointer type.
1721 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
1722 TD->getPointerSizeInBits() ==
1723 cast<IntegerType>(DestTy)->getBitWidth()) {
1725 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1726 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1727 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1728 RHSOp = RHSC->getOperand(0);
1729 // If the pointer types don't match, insert a bitcast.
1730 if (LHSCIOp->getType() != RHSOp->getType())
1731 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1735 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1738 // The code below only handles extension cast instructions, so far.
1740 if (LHSCI->getOpcode() != Instruction::ZExt &&
1741 LHSCI->getOpcode() != Instruction::SExt)
1744 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1745 bool isSignedCmp = ICI.isSigned();
1747 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1748 // Not an extension from the same type?
1749 RHSCIOp = CI->getOperand(0);
1750 if (RHSCIOp->getType() != LHSCIOp->getType())
1753 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1754 // and the other is a zext), then we can't handle this.
1755 if (CI->getOpcode() != LHSCI->getOpcode())
1758 // Deal with equality cases early.
1759 if (ICI.isEquality())
1760 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1762 // A signed comparison of sign extended values simplifies into a
1763 // signed comparison.
1764 if (isSignedCmp && isSignedExt)
1765 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1767 // The other three cases all fold into an unsigned comparison.
1768 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1771 // If we aren't dealing with a constant on the RHS, exit early
1772 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1776 // Compute the constant that would happen if we truncated to SrcTy then
1777 // reextended to DestTy.
1778 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1779 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1782 // If the re-extended constant didn't change...
1784 // Deal with equality cases early.
1785 if (ICI.isEquality())
1786 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1788 // A signed comparison of sign extended values simplifies into a
1789 // signed comparison.
1790 if (isSignedExt && isSignedCmp)
1791 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1793 // The other three cases all fold into an unsigned comparison.
1794 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1797 // The re-extended constant changed so the constant cannot be represented
1798 // in the shorter type. Consequently, we cannot emit a simple comparison.
1799 // All the cases that fold to true or false will have already been handled
1800 // by SimplifyICmpInst, so only deal with the tricky case.
1802 if (isSignedCmp || !isSignedExt)
1805 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1806 // should have been folded away previously and not enter in here.
1808 // We're performing an unsigned comp with a sign extended value.
1809 // This is true if the input is >= 0. [aka >s -1]
1810 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1811 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
1813 // Finally, return the value computed.
1814 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
1815 return ReplaceInstUsesWith(ICI, Result);
1817 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
1818 return BinaryOperator::CreateNot(Result);
1821 /// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1822 /// I = icmp ugt (add (add A, B), CI2), CI1
1823 /// If this is of the form:
1825 /// if (sum+128 >u 255)
1826 /// Then replace it with llvm.sadd.with.overflow.i8.
1828 static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1829 ConstantInt *CI2, ConstantInt *CI1,
1831 // The transformation we're trying to do here is to transform this into an
1832 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1833 // with a narrower add, and discard the add-with-constant that is part of the
1834 // range check (if we can't eliminate it, this isn't profitable).
1836 // In order to eliminate the add-with-constant, the compare can be its only
1838 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1839 if (!AddWithCst->hasOneUse()) return 0;
1841 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1842 if (!CI2->getValue().isPowerOf2()) return 0;
1843 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1844 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
1846 // The width of the new add formed is 1 more than the bias.
1849 // Check to see that CI1 is an all-ones value with NewWidth bits.
1850 if (CI1->getBitWidth() == NewWidth ||
1851 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1854 // This is only really a signed overflow check if the inputs have been
1855 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1856 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1857 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1858 if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1859 IC.ComputeNumSignBits(B) < NeededSignBits)
1862 // In order to replace the original add with a narrower
1863 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1864 // and truncates that discard the high bits of the add. Verify that this is
1866 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1867 for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1869 if (*UI == AddWithCst) continue;
1871 // Only accept truncates for now. We would really like a nice recursive
1872 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1873 // chain to see which bits of a value are actually demanded. If the
1874 // original add had another add which was then immediately truncated, we
1875 // could still do the transformation.
1876 TruncInst *TI = dyn_cast<TruncInst>(*UI);
1878 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1881 // If the pattern matches, truncate the inputs to the narrower type and
1882 // use the sadd_with_overflow intrinsic to efficiently compute both the
1883 // result and the overflow bit.
1884 Module *M = I.getParent()->getParent()->getParent();
1886 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1887 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
1890 InstCombiner::BuilderTy *Builder = IC.Builder;
1892 // Put the new code above the original add, in case there are any uses of the
1893 // add between the add and the compare.
1894 Builder->SetInsertPoint(OrigAdd);
1896 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1897 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1898 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1899 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1900 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
1902 // The inner add was the result of the narrow add, zero extended to the
1903 // wider type. Replace it with the result computed by the intrinsic.
1904 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
1906 // The original icmp gets replaced with the overflow value.
1907 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1910 static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1912 // Don't bother doing this transformation for pointers, don't do it for
1914 if (!isa<IntegerType>(OrigAddV->getType())) return 0;
1916 // If the add is a constant expr, then we don't bother transforming it.
1917 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1918 if (OrigAdd == 0) return 0;
1920 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
1922 // Put the new code above the original add, in case there are any uses of the
1923 // add between the add and the compare.
1924 InstCombiner::BuilderTy *Builder = IC.Builder;
1925 Builder->SetInsertPoint(OrigAdd);
1927 Module *M = I.getParent()->getParent()->getParent();
1928 Type *Ty = LHS->getType();
1929 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1930 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1931 Value *Add = Builder->CreateExtractValue(Call, 0);
1933 IC.ReplaceInstUsesWith(*OrigAdd, Add);
1935 // The original icmp gets replaced with the overflow value.
1936 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
1939 // DemandedBitsLHSMask - When performing a comparison against a constant,
1940 // it is possible that not all the bits in the LHS are demanded. This helper
1941 // method computes the mask that IS demanded.
1942 static APInt DemandedBitsLHSMask(ICmpInst &I,
1943 unsigned BitWidth, bool isSignCheck) {
1945 return APInt::getSignBit(BitWidth);
1947 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
1948 if (!CI) return APInt::getAllOnesValue(BitWidth);
1949 const APInt &RHS = CI->getValue();
1951 switch (I.getPredicate()) {
1952 // For a UGT comparison, we don't care about any bits that
1953 // correspond to the trailing ones of the comparand. The value of these
1954 // bits doesn't impact the outcome of the comparison, because any value
1955 // greater than the RHS must differ in a bit higher than these due to carry.
1956 case ICmpInst::ICMP_UGT: {
1957 unsigned trailingOnes = RHS.countTrailingOnes();
1958 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
1962 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
1963 // Any value less than the RHS must differ in a higher bit because of carries.
1964 case ICmpInst::ICMP_ULT: {
1965 unsigned trailingZeros = RHS.countTrailingZeros();
1966 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
1971 return APInt::getAllOnesValue(BitWidth);
1976 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
1977 bool Changed = false;
1978 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1980 /// Orders the operands of the compare so that they are listed from most
1981 /// complex to least complex. This puts constants before unary operators,
1982 /// before binary operators.
1983 if (getComplexity(Op0) < getComplexity(Op1)) {
1985 std::swap(Op0, Op1);
1989 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
1990 return ReplaceInstUsesWith(I, V);
1992 // comparing -val or val with non-zero is the same as just comparing val
1993 // ie, abs(val) != 0 -> val != 0
1994 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
1996 Value *Cond, *SelectTrue, *SelectFalse;
1997 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
1998 m_Value(SelectFalse)))) {
1999 if (Value *V = dyn_castNegVal(SelectTrue)) {
2000 if (V == SelectFalse)
2001 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2003 else if (Value *V = dyn_castNegVal(SelectFalse)) {
2004 if (V == SelectTrue)
2005 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2010 Type *Ty = Op0->getType();
2012 // icmp's with boolean values can always be turned into bitwise operations
2013 if (Ty->isIntegerTy(1)) {
2014 switch (I.getPredicate()) {
2015 default: llvm_unreachable("Invalid icmp instruction!");
2016 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
2017 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
2018 return BinaryOperator::CreateNot(Xor);
2020 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
2021 return BinaryOperator::CreateXor(Op0, Op1);
2023 case ICmpInst::ICMP_UGT:
2024 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
2026 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
2027 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2028 return BinaryOperator::CreateAnd(Not, Op1);
2030 case ICmpInst::ICMP_SGT:
2031 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
2033 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
2034 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2035 return BinaryOperator::CreateAnd(Not, Op0);
2037 case ICmpInst::ICMP_UGE:
2038 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
2040 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
2041 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2042 return BinaryOperator::CreateOr(Not, Op1);
2044 case ICmpInst::ICMP_SGE:
2045 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
2047 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
2048 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2049 return BinaryOperator::CreateOr(Not, Op0);
2054 unsigned BitWidth = 0;
2055 if (Ty->isIntOrIntVectorTy())
2056 BitWidth = Ty->getScalarSizeInBits();
2057 else if (TD) // Pointers require TD info to get their size.
2058 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
2060 bool isSignBit = false;
2062 // See if we are doing a comparison with a constant.
2063 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2064 Value *A = 0, *B = 0;
2066 // Match the following pattern, which is a common idiom when writing
2067 // overflow-safe integer arithmetic function. The source performs an
2068 // addition in wider type, and explicitly checks for overflow using
2069 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
2070 // sadd_with_overflow intrinsic.
2072 // TODO: This could probably be generalized to handle other overflow-safe
2073 // operations if we worked out the formulas to compute the appropriate
2077 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
2079 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
2080 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2081 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
2082 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
2086 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2087 if (I.isEquality() && CI->isZero() &&
2088 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
2089 // (icmp cond A B) if cond is equality
2090 return new ICmpInst(I.getPredicate(), A, B);
2093 // If we have an icmp le or icmp ge instruction, turn it into the
2094 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
2095 // them being folded in the code below. The SimplifyICmpInst code has
2096 // already handled the edge cases for us, so we just assert on them.
2097 switch (I.getPredicate()) {
2099 case ICmpInst::ICMP_ULE:
2100 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
2101 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
2102 Builder->getInt(CI->getValue()+1));
2103 case ICmpInst::ICMP_SLE:
2104 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
2105 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2106 Builder->getInt(CI->getValue()+1));
2107 case ICmpInst::ICMP_UGE:
2108 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
2109 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
2110 Builder->getInt(CI->getValue()-1));
2111 case ICmpInst::ICMP_SGE:
2112 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
2113 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2114 Builder->getInt(CI->getValue()-1));
2117 // If this comparison is a normal comparison, it demands all
2118 // bits, if it is a sign bit comparison, it only demands the sign bit.
2120 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2123 // See if we can fold the comparison based on range information we can get
2124 // by checking whether bits are known to be zero or one in the input.
2125 if (BitWidth != 0) {
2126 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2127 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2129 if (SimplifyDemandedBits(I.getOperandUse(0),
2130 DemandedBitsLHSMask(I, BitWidth, isSignBit),
2131 Op0KnownZero, Op0KnownOne, 0))
2133 if (SimplifyDemandedBits(I.getOperandUse(1),
2134 APInt::getAllOnesValue(BitWidth),
2135 Op1KnownZero, Op1KnownOne, 0))
2138 // Given the known and unknown bits, compute a range that the LHS could be
2139 // in. Compute the Min, Max and RHS values based on the known bits. For the
2140 // EQ and NE we use unsigned values.
2141 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2142 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2144 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2146 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2149 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2151 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2155 // If Min and Max are known to be the same, then SimplifyDemandedBits
2156 // figured out that the LHS is a constant. Just constant fold this now so
2157 // that code below can assume that Min != Max.
2158 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2159 return new ICmpInst(I.getPredicate(),
2160 ConstantInt::get(Op0->getType(), Op0Min), Op1);
2161 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2162 return new ICmpInst(I.getPredicate(), Op0,
2163 ConstantInt::get(Op1->getType(), Op1Min));
2165 // Based on the range information we know about the LHS, see if we can
2166 // simplify this comparison. For example, (x&4) < 8 is always true.
2167 switch (I.getPredicate()) {
2168 default: llvm_unreachable("Unknown icmp opcode!");
2169 case ICmpInst::ICMP_EQ: {
2170 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2171 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2173 // If all bits are known zero except for one, then we know at most one
2174 // bit is set. If the comparison is against zero, then this is a check
2175 // to see if *that* bit is set.
2176 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2177 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2178 // If the LHS is an AND with the same constant, look through it.
2180 ConstantInt *LHSC = 0;
2181 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2182 LHSC->getValue() != Op0KnownZeroInverted)
2185 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2186 // then turn "((1 << x)&8) == 0" into "x != 3".
2188 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2189 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
2190 return new ICmpInst(ICmpInst::ICMP_NE, X,
2191 ConstantInt::get(X->getType(), CmpVal));
2194 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2195 // then turn "((8 >>u x)&1) == 0" into "x != 3".
2197 if (Op0KnownZeroInverted == 1 &&
2198 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2199 return new ICmpInst(ICmpInst::ICMP_NE, X,
2200 ConstantInt::get(X->getType(),
2201 CI->countTrailingZeros()));
2206 case ICmpInst::ICMP_NE: {
2207 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2208 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2210 // If all bits are known zero except for one, then we know at most one
2211 // bit is set. If the comparison is against zero, then this is a check
2212 // to see if *that* bit is set.
2213 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2214 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2215 // If the LHS is an AND with the same constant, look through it.
2217 ConstantInt *LHSC = 0;
2218 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2219 LHSC->getValue() != Op0KnownZeroInverted)
2222 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2223 // then turn "((1 << x)&8) != 0" into "x == 3".
2225 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2226 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
2227 return new ICmpInst(ICmpInst::ICMP_EQ, X,
2228 ConstantInt::get(X->getType(), CmpVal));
2231 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2232 // then turn "((8 >>u x)&1) != 0" into "x == 3".
2234 if (Op0KnownZeroInverted == 1 &&
2235 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2236 return new ICmpInst(ICmpInst::ICMP_EQ, X,
2237 ConstantInt::get(X->getType(),
2238 CI->countTrailingZeros()));
2243 case ICmpInst::ICMP_ULT:
2244 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
2245 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2246 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
2247 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2248 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2249 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2250 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2251 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2252 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2253 Builder->getInt(CI->getValue()-1));
2255 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2256 if (CI->isMinValue(true))
2257 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2258 Constant::getAllOnesValue(Op0->getType()));
2261 case ICmpInst::ICMP_UGT:
2262 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
2263 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2264 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
2265 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2267 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2268 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2269 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2270 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2271 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2272 Builder->getInt(CI->getValue()+1));
2274 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2275 if (CI->isMaxValue(true))
2276 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2277 Constant::getNullValue(Op0->getType()));
2280 case ICmpInst::ICMP_SLT:
2281 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
2282 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2283 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
2284 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2285 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2286 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2287 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2288 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2289 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2290 Builder->getInt(CI->getValue()-1));
2293 case ICmpInst::ICMP_SGT:
2294 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
2295 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2296 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
2297 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2299 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2300 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2301 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2302 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2303 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2304 Builder->getInt(CI->getValue()+1));
2307 case ICmpInst::ICMP_SGE:
2308 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2309 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
2310 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2311 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
2312 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2314 case ICmpInst::ICMP_SLE:
2315 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2316 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
2317 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2318 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
2319 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2321 case ICmpInst::ICMP_UGE:
2322 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2323 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
2324 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2325 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
2326 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2328 case ICmpInst::ICMP_ULE:
2329 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2330 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
2331 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2332 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
2333 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2337 // Turn a signed comparison into an unsigned one if both operands
2338 // are known to have the same sign.
2340 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2341 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2342 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2345 // Test if the ICmpInst instruction is used exclusively by a select as
2346 // part of a minimum or maximum operation. If so, refrain from doing
2347 // any other folding. This helps out other analyses which understand
2348 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2349 // and CodeGen. And in this case, at least one of the comparison
2350 // operands has at least one user besides the compare (the select),
2351 // which would often largely negate the benefit of folding anyway.
2353 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2354 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2355 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2358 // See if we are doing a comparison between a constant and an instruction that
2359 // can be folded into the comparison.
2360 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2361 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2362 // instruction, see if that instruction also has constants so that the
2363 // instruction can be folded into the icmp
2364 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2365 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2369 // Handle icmp with constant (but not simple integer constant) RHS
2370 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2371 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2372 switch (LHSI->getOpcode()) {
2373 case Instruction::GetElementPtr:
2374 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2375 if (RHSC->isNullValue() &&
2376 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2377 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2378 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2380 case Instruction::PHI:
2381 // Only fold icmp into the PHI if the phi and icmp are in the same
2382 // block. If in the same block, we're encouraging jump threading. If
2383 // not, we are just pessimizing the code by making an i1 phi.
2384 if (LHSI->getParent() == I.getParent())
2385 if (Instruction *NV = FoldOpIntoPhi(I))
2388 case Instruction::Select: {
2389 // If either operand of the select is a constant, we can fold the
2390 // comparison into the select arms, which will cause one to be
2391 // constant folded and the select turned into a bitwise or.
2392 Value *Op1 = 0, *Op2 = 0;
2393 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2394 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2395 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2396 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2398 // We only want to perform this transformation if it will not lead to
2399 // additional code. This is true if either both sides of the select
2400 // fold to a constant (in which case the icmp is replaced with a select
2401 // which will usually simplify) or this is the only user of the
2402 // select (in which case we are trading a select+icmp for a simpler
2404 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2406 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2409 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2411 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2415 case Instruction::IntToPtr:
2416 // icmp pred inttoptr(X), null -> icmp pred X, 0
2417 if (RHSC->isNullValue() && TD &&
2418 TD->getIntPtrType(RHSC->getContext()) ==
2419 LHSI->getOperand(0)->getType())
2420 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2421 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2424 case Instruction::Load:
2425 // Try to optimize things like "A[i] > 4" to index computations.
2426 if (GetElementPtrInst *GEP =
2427 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2428 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2429 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2430 !cast<LoadInst>(LHSI)->isVolatile())
2431 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2438 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2439 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2440 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2442 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2443 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2444 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2447 // Test to see if the operands of the icmp are casted versions of other
2448 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
2450 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
2451 if (Op0->getType()->isPointerTy() &&
2452 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
2453 // We keep moving the cast from the left operand over to the right
2454 // operand, where it can often be eliminated completely.
2455 Op0 = CI->getOperand(0);
2457 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2458 // so eliminate it as well.
2459 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2460 Op1 = CI2->getOperand(0);
2462 // If Op1 is a constant, we can fold the cast into the constant.
2463 if (Op0->getType() != Op1->getType()) {
2464 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2465 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2467 // Otherwise, cast the RHS right before the icmp
2468 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2471 return new ICmpInst(I.getPredicate(), Op0, Op1);
2475 if (isa<CastInst>(Op0)) {
2476 // Handle the special case of: icmp (cast bool to X), <cst>
2477 // This comes up when you have code like
2480 // For generality, we handle any zero-extension of any operand comparison
2481 // with a constant or another cast from the same type.
2482 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2483 if (Instruction *R = visitICmpInstWithCastAndCast(I))
2487 // Special logic for binary operators.
2488 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2489 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2491 CmpInst::Predicate Pred = I.getPredicate();
2492 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2493 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2494 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2495 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2496 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2497 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2498 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2499 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2500 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2502 // Analyze the case when either Op0 or Op1 is an add instruction.
2503 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2504 Value *A = 0, *B = 0, *C = 0, *D = 0;
2505 if (BO0 && BO0->getOpcode() == Instruction::Add)
2506 A = BO0->getOperand(0), B = BO0->getOperand(1);
2507 if (BO1 && BO1->getOpcode() == Instruction::Add)
2508 C = BO1->getOperand(0), D = BO1->getOperand(1);
2510 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2511 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2512 return new ICmpInst(Pred, A == Op1 ? B : A,
2513 Constant::getNullValue(Op1->getType()));
2515 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2516 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2517 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2520 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
2521 if (A && C && (A == C || A == D || B == C || B == D) &&
2522 NoOp0WrapProblem && NoOp1WrapProblem &&
2523 // Try not to increase register pressure.
2524 BO0->hasOneUse() && BO1->hasOneUse()) {
2525 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2528 // C + B == C + D -> B == D
2531 } else if (A == D) {
2532 // D + B == C + D -> B == C
2535 } else if (B == C) {
2536 // A + C == C + D -> A == D
2541 // A + D == C + D -> A == C
2545 return new ICmpInst(Pred, Y, Z);
2548 // icmp slt (X + -1), Y -> icmp sle X, Y
2549 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
2550 match(B, m_AllOnes()))
2551 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
2553 // icmp sge (X + -1), Y -> icmp sgt X, Y
2554 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
2555 match(B, m_AllOnes()))
2556 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
2558 // icmp sle (X + 1), Y -> icmp slt X, Y
2559 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
2561 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
2563 // icmp sgt (X + 1), Y -> icmp sge X, Y
2564 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
2566 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
2568 // if C1 has greater magnitude than C2:
2569 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
2570 // s.t. C3 = C1 - C2
2572 // if C2 has greater magnitude than C1:
2573 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
2574 // s.t. C3 = C2 - C1
2575 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
2576 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
2577 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
2578 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
2579 const APInt &AP1 = C1->getValue();
2580 const APInt &AP2 = C2->getValue();
2581 if (AP1.isNegative() == AP2.isNegative()) {
2582 APInt AP1Abs = C1->getValue().abs();
2583 APInt AP2Abs = C2->getValue().abs();
2584 if (AP1Abs.uge(AP2Abs)) {
2585 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
2586 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
2587 return new ICmpInst(Pred, NewAdd, C);
2589 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
2590 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
2591 return new ICmpInst(Pred, A, NewAdd);
2597 // Analyze the case when either Op0 or Op1 is a sub instruction.
2598 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2599 A = 0; B = 0; C = 0; D = 0;
2600 if (BO0 && BO0->getOpcode() == Instruction::Sub)
2601 A = BO0->getOperand(0), B = BO0->getOperand(1);
2602 if (BO1 && BO1->getOpcode() == Instruction::Sub)
2603 C = BO1->getOperand(0), D = BO1->getOperand(1);
2605 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2606 if (A == Op1 && NoOp0WrapProblem)
2607 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2609 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2610 if (C == Op0 && NoOp1WrapProblem)
2611 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2613 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
2614 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2615 // Try not to increase register pressure.
2616 BO0->hasOneUse() && BO1->hasOneUse())
2617 return new ICmpInst(Pred, A, C);
2619 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2620 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2621 // Try not to increase register pressure.
2622 BO0->hasOneUse() && BO1->hasOneUse())
2623 return new ICmpInst(Pred, D, B);
2625 BinaryOperator *SRem = NULL;
2626 // icmp (srem X, Y), Y
2627 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2628 Op1 == BO0->getOperand(1))
2630 // icmp Y, (srem X, Y)
2631 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2632 Op0 == BO1->getOperand(1))
2635 // We don't check hasOneUse to avoid increasing register pressure because
2636 // the value we use is the same value this instruction was already using.
2637 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2639 case ICmpInst::ICMP_EQ:
2640 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2641 case ICmpInst::ICMP_NE:
2642 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2643 case ICmpInst::ICMP_SGT:
2644 case ICmpInst::ICMP_SGE:
2645 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2646 Constant::getAllOnesValue(SRem->getType()));
2647 case ICmpInst::ICMP_SLT:
2648 case ICmpInst::ICMP_SLE:
2649 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2650 Constant::getNullValue(SRem->getType()));
2654 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2655 BO0->hasOneUse() && BO1->hasOneUse() &&
2656 BO0->getOperand(1) == BO1->getOperand(1)) {
2657 switch (BO0->getOpcode()) {
2659 case Instruction::Add:
2660 case Instruction::Sub:
2661 case Instruction::Xor:
2662 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
2663 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2664 BO1->getOperand(0));
2665 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2666 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2667 if (CI->getValue().isSignBit()) {
2668 ICmpInst::Predicate Pred = I.isSigned()
2669 ? I.getUnsignedPredicate()
2670 : I.getSignedPredicate();
2671 return new ICmpInst(Pred, BO0->getOperand(0),
2672 BO1->getOperand(0));
2675 if (CI->isMaxValue(true)) {
2676 ICmpInst::Predicate Pred = I.isSigned()
2677 ? I.getUnsignedPredicate()
2678 : I.getSignedPredicate();
2679 Pred = I.getSwappedPredicate(Pred);
2680 return new ICmpInst(Pred, BO0->getOperand(0),
2681 BO1->getOperand(0));
2685 case Instruction::Mul:
2686 if (!I.isEquality())
2689 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2690 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2691 // Mask = -1 >> count-trailing-zeros(Cst).
2692 if (!CI->isZero() && !CI->isOne()) {
2693 const APInt &AP = CI->getValue();
2694 ConstantInt *Mask = ConstantInt::get(I.getContext(),
2695 APInt::getLowBitsSet(AP.getBitWidth(),
2697 AP.countTrailingZeros()));
2698 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2699 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2700 return new ICmpInst(I.getPredicate(), And1, And2);
2704 case Instruction::UDiv:
2705 case Instruction::LShr:
2709 case Instruction::SDiv:
2710 case Instruction::AShr:
2711 if (!BO0->isExact() || !BO1->isExact())
2713 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2714 BO1->getOperand(0));
2715 case Instruction::Shl: {
2716 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2717 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2720 if (!NSW && I.isSigned())
2722 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2723 BO1->getOperand(0));
2730 // Transform (A & ~B) == 0 --> (A & B) != 0
2731 // and (A & ~B) != 0 --> (A & B) == 0
2732 // if A is a power of 2.
2733 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2734 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A) && I.isEquality())
2735 return new ICmpInst(I.getInversePredicate(),
2736 Builder->CreateAnd(A, B),
2739 // ~x < ~y --> y < x
2740 // ~x < cst --> ~cst < x
2741 if (match(Op0, m_Not(m_Value(A)))) {
2742 if (match(Op1, m_Not(m_Value(B))))
2743 return new ICmpInst(I.getPredicate(), B, A);
2744 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
2745 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2748 // (a+b) <u a --> llvm.uadd.with.overflow.
2749 // (a+b) <u b --> llvm.uadd.with.overflow.
2750 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
2751 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2752 (Op1 == A || Op1 == B))
2753 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2756 // a >u (a+b) --> llvm.uadd.with.overflow.
2757 // b >u (a+b) --> llvm.uadd.with.overflow.
2758 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2759 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2760 (Op0 == A || Op0 == B))
2761 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2765 if (I.isEquality()) {
2766 Value *A, *B, *C, *D;
2768 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2769 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
2770 Value *OtherVal = A == Op1 ? B : A;
2771 return new ICmpInst(I.getPredicate(), OtherVal,
2772 Constant::getNullValue(A->getType()));
2775 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2776 // A^c1 == C^c2 --> A == C^(c1^c2)
2777 ConstantInt *C1, *C2;
2778 if (match(B, m_ConstantInt(C1)) &&
2779 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2780 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
2781 Value *Xor = Builder->CreateXor(C, NC);
2782 return new ICmpInst(I.getPredicate(), A, Xor);
2785 // A^B == A^D -> B == D
2786 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2787 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2788 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2789 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2793 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2794 (A == Op0 || B == Op0)) {
2795 // A == (A^B) -> B == 0
2796 Value *OtherVal = A == Op0 ? B : A;
2797 return new ICmpInst(I.getPredicate(), OtherVal,
2798 Constant::getNullValue(A->getType()));
2801 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
2802 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
2803 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
2804 Value *X = 0, *Y = 0, *Z = 0;
2807 X = B; Y = D; Z = A;
2808 } else if (A == D) {
2809 X = B; Y = C; Z = A;
2810 } else if (B == C) {
2811 X = A; Y = D; Z = B;
2812 } else if (B == D) {
2813 X = A; Y = C; Z = B;
2816 if (X) { // Build (X^Y) & Z
2817 Op1 = Builder->CreateXor(X, Y);
2818 Op1 = Builder->CreateAnd(Op1, Z);
2819 I.setOperand(0, Op1);
2820 I.setOperand(1, Constant::getNullValue(Op1->getType()));
2825 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
2826 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
2828 if ((Op0->hasOneUse() &&
2829 match(Op0, m_ZExt(m_Value(A))) &&
2830 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
2831 (Op1->hasOneUse() &&
2832 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
2833 match(Op1, m_ZExt(m_Value(A))))) {
2834 APInt Pow2 = Cst1->getValue() + 1;
2835 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
2836 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
2837 return new ICmpInst(I.getPredicate(), A,
2838 Builder->CreateTrunc(B, A->getType()));
2841 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2842 // "icmp (and X, mask), cst"
2844 if (Op0->hasOneUse() &&
2845 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2846 m_ConstantInt(ShAmt))))) &&
2847 match(Op1, m_ConstantInt(Cst1)) &&
2848 // Only do this when A has multiple uses. This is most important to do
2849 // when it exposes other optimizations.
2851 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
2853 if (ShAmt < ASize) {
2855 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2858 APInt CmpV = Cst1->getValue().zext(ASize);
2861 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2862 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2868 Value *X; ConstantInt *Cst;
2870 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
2871 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
2874 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
2875 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
2877 return Changed ? &I : 0;
2885 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2887 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2890 if (!isa<ConstantFP>(RHSC)) return 0;
2891 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
2893 // Get the width of the mantissa. We don't want to hack on conversions that
2894 // might lose information from the integer, e.g. "i64 -> float"
2895 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2896 if (MantissaWidth == -1) return 0; // Unknown.
2898 // Check to see that the input is converted from an integer type that is small
2899 // enough that preserves all bits. TODO: check here for "known" sign bits.
2900 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
2901 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
2903 // If this is a uitofp instruction, we need an extra bit to hold the sign.
2904 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
2908 // If the conversion would lose info, don't hack on this.
2909 if ((int)InputSize > MantissaWidth)
2912 // Otherwise, we can potentially simplify the comparison. We know that it
2913 // will always come through as an integer value and we know the constant is
2914 // not a NAN (it would have been previously simplified).
2915 assert(!RHS.isNaN() && "NaN comparison not already folded!");
2917 ICmpInst::Predicate Pred;
2918 switch (I.getPredicate()) {
2919 default: llvm_unreachable("Unexpected predicate!");
2920 case FCmpInst::FCMP_UEQ:
2921 case FCmpInst::FCMP_OEQ:
2922 Pred = ICmpInst::ICMP_EQ;
2924 case FCmpInst::FCMP_UGT:
2925 case FCmpInst::FCMP_OGT:
2926 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
2928 case FCmpInst::FCMP_UGE:
2929 case FCmpInst::FCMP_OGE:
2930 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
2932 case FCmpInst::FCMP_ULT:
2933 case FCmpInst::FCMP_OLT:
2934 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
2936 case FCmpInst::FCMP_ULE:
2937 case FCmpInst::FCMP_OLE:
2938 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
2940 case FCmpInst::FCMP_UNE:
2941 case FCmpInst::FCMP_ONE:
2942 Pred = ICmpInst::ICMP_NE;
2944 case FCmpInst::FCMP_ORD:
2945 return ReplaceInstUsesWith(I, Builder->getTrue());
2946 case FCmpInst::FCMP_UNO:
2947 return ReplaceInstUsesWith(I, Builder->getFalse());
2950 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
2952 // Now we know that the APFloat is a normal number, zero or inf.
2954 // See if the FP constant is too large for the integer. For example,
2955 // comparing an i8 to 300.0.
2956 unsigned IntWidth = IntTy->getScalarSizeInBits();
2959 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
2960 // and large values.
2961 APFloat SMax(RHS.getSemantics());
2962 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
2963 APFloat::rmNearestTiesToEven);
2964 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
2965 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
2966 Pred == ICmpInst::ICMP_SLE)
2967 return ReplaceInstUsesWith(I, Builder->getTrue());
2968 return ReplaceInstUsesWith(I, Builder->getFalse());
2971 // If the RHS value is > UnsignedMax, fold the comparison. This handles
2972 // +INF and large values.
2973 APFloat UMax(RHS.getSemantics());
2974 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
2975 APFloat::rmNearestTiesToEven);
2976 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
2977 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
2978 Pred == ICmpInst::ICMP_ULE)
2979 return ReplaceInstUsesWith(I, Builder->getTrue());
2980 return ReplaceInstUsesWith(I, Builder->getFalse());
2985 // See if the RHS value is < SignedMin.
2986 APFloat SMin(RHS.getSemantics());
2987 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
2988 APFloat::rmNearestTiesToEven);
2989 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
2990 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
2991 Pred == ICmpInst::ICMP_SGE)
2992 return ReplaceInstUsesWith(I, Builder->getTrue());
2993 return ReplaceInstUsesWith(I, Builder->getFalse());
2996 // See if the RHS value is < UnsignedMin.
2997 APFloat SMin(RHS.getSemantics());
2998 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
2999 APFloat::rmNearestTiesToEven);
3000 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
3001 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
3002 Pred == ICmpInst::ICMP_UGE)
3003 return ReplaceInstUsesWith(I, Builder->getTrue());
3004 return ReplaceInstUsesWith(I, Builder->getFalse());
3008 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
3009 // [0, UMAX], but it may still be fractional. See if it is fractional by
3010 // casting the FP value to the integer value and back, checking for equality.
3011 // Don't do this for zero, because -0.0 is not fractional.
3012 Constant *RHSInt = LHSUnsigned
3013 ? ConstantExpr::getFPToUI(RHSC, IntTy)
3014 : ConstantExpr::getFPToSI(RHSC, IntTy);
3015 if (!RHS.isZero()) {
3016 bool Equal = LHSUnsigned
3017 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
3018 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
3020 // If we had a comparison against a fractional value, we have to adjust
3021 // the compare predicate and sometimes the value. RHSC is rounded towards
3022 // zero at this point.
3024 default: llvm_unreachable("Unexpected integer comparison!");
3025 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
3026 return ReplaceInstUsesWith(I, Builder->getTrue());
3027 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
3028 return ReplaceInstUsesWith(I, Builder->getFalse());
3029 case ICmpInst::ICMP_ULE:
3030 // (float)int <= 4.4 --> int <= 4
3031 // (float)int <= -4.4 --> false
3032 if (RHS.isNegative())
3033 return ReplaceInstUsesWith(I, Builder->getFalse());
3035 case ICmpInst::ICMP_SLE:
3036 // (float)int <= 4.4 --> int <= 4
3037 // (float)int <= -4.4 --> int < -4
3038 if (RHS.isNegative())
3039 Pred = ICmpInst::ICMP_SLT;
3041 case ICmpInst::ICMP_ULT:
3042 // (float)int < -4.4 --> false
3043 // (float)int < 4.4 --> int <= 4
3044 if (RHS.isNegative())
3045 return ReplaceInstUsesWith(I, Builder->getFalse());
3046 Pred = ICmpInst::ICMP_ULE;
3048 case ICmpInst::ICMP_SLT:
3049 // (float)int < -4.4 --> int < -4
3050 // (float)int < 4.4 --> int <= 4
3051 if (!RHS.isNegative())
3052 Pred = ICmpInst::ICMP_SLE;
3054 case ICmpInst::ICMP_UGT:
3055 // (float)int > 4.4 --> int > 4
3056 // (float)int > -4.4 --> true
3057 if (RHS.isNegative())
3058 return ReplaceInstUsesWith(I, Builder->getTrue());
3060 case ICmpInst::ICMP_SGT:
3061 // (float)int > 4.4 --> int > 4
3062 // (float)int > -4.4 --> int >= -4
3063 if (RHS.isNegative())
3064 Pred = ICmpInst::ICMP_SGE;
3066 case ICmpInst::ICMP_UGE:
3067 // (float)int >= -4.4 --> true
3068 // (float)int >= 4.4 --> int > 4
3069 if (RHS.isNegative())
3070 return ReplaceInstUsesWith(I, Builder->getTrue());
3071 Pred = ICmpInst::ICMP_UGT;
3073 case ICmpInst::ICMP_SGE:
3074 // (float)int >= -4.4 --> int >= -4
3075 // (float)int >= 4.4 --> int > 4
3076 if (!RHS.isNegative())
3077 Pred = ICmpInst::ICMP_SGT;
3083 // Lower this FP comparison into an appropriate integer version of the
3085 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
3088 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
3089 bool Changed = false;
3091 /// Orders the operands of the compare so that they are listed from most
3092 /// complex to least complex. This puts constants before unary operators,
3093 /// before binary operators.
3094 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
3099 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3101 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
3102 return ReplaceInstUsesWith(I, V);
3104 // Simplify 'fcmp pred X, X'
3106 switch (I.getPredicate()) {
3107 default: llvm_unreachable("Unknown predicate!");
3108 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
3109 case FCmpInst::FCMP_ULT: // True if unordered or less than
3110 case FCmpInst::FCMP_UGT: // True if unordered or greater than
3111 case FCmpInst::FCMP_UNE: // True if unordered or not equal
3112 // Canonicalize these to be 'fcmp uno %X, 0.0'.
3113 I.setPredicate(FCmpInst::FCMP_UNO);
3114 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3117 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
3118 case FCmpInst::FCMP_OEQ: // True if ordered and equal
3119 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
3120 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
3121 // Canonicalize these to be 'fcmp ord %X, 0.0'.
3122 I.setPredicate(FCmpInst::FCMP_ORD);
3123 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3128 // Handle fcmp with constant RHS
3129 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3130 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3131 switch (LHSI->getOpcode()) {
3132 case Instruction::FPExt: {
3133 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
3134 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
3135 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
3139 const fltSemantics *Sem;
3140 // FIXME: This shouldn't be here.
3141 if (LHSExt->getSrcTy()->isHalfTy())
3142 Sem = &APFloat::IEEEhalf;
3143 else if (LHSExt->getSrcTy()->isFloatTy())
3144 Sem = &APFloat::IEEEsingle;
3145 else if (LHSExt->getSrcTy()->isDoubleTy())
3146 Sem = &APFloat::IEEEdouble;
3147 else if (LHSExt->getSrcTy()->isFP128Ty())
3148 Sem = &APFloat::IEEEquad;
3149 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
3150 Sem = &APFloat::x87DoubleExtended;
3151 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
3152 Sem = &APFloat::PPCDoubleDouble;
3157 APFloat F = RHSF->getValueAPF();
3158 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
3160 // Avoid lossy conversions and denormals. Zero is a special case
3161 // that's OK to convert.
3165 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
3166 APFloat::cmpLessThan) || Fabs.isZero()))
3168 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3169 ConstantFP::get(RHSC->getContext(), F));
3172 case Instruction::PHI:
3173 // Only fold fcmp into the PHI if the phi and fcmp are in the same
3174 // block. If in the same block, we're encouraging jump threading. If
3175 // not, we are just pessimizing the code by making an i1 phi.
3176 if (LHSI->getParent() == I.getParent())
3177 if (Instruction *NV = FoldOpIntoPhi(I))
3180 case Instruction::SIToFP:
3181 case Instruction::UIToFP:
3182 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
3185 case Instruction::Select: {
3186 // If either operand of the select is a constant, we can fold the
3187 // comparison into the select arms, which will cause one to be
3188 // constant folded and the select turned into a bitwise or.
3189 Value *Op1 = 0, *Op2 = 0;
3190 if (LHSI->hasOneUse()) {
3191 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3192 // Fold the known value into the constant operand.
3193 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3194 // Insert a new FCmp of the other select operand.
3195 Op2 = Builder->CreateFCmp(I.getPredicate(),
3196 LHSI->getOperand(2), RHSC, I.getName());
3197 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3198 // Fold the known value into the constant operand.
3199 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3200 // Insert a new FCmp of the other select operand.
3201 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
3207 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3210 case Instruction::FSub: {
3211 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3213 if (match(LHSI, m_FNeg(m_Value(Op))))
3214 return new FCmpInst(I.getSwappedPredicate(), Op,
3215 ConstantExpr::getFNeg(RHSC));
3218 case Instruction::Load:
3219 if (GetElementPtrInst *GEP =
3220 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3221 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3222 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3223 !cast<LoadInst>(LHSI)->isVolatile())
3224 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3228 case Instruction::Call: {
3229 CallInst *CI = cast<CallInst>(LHSI);
3231 // Various optimization for fabs compared with zero.
3232 if (RHSC->isNullValue() && CI->getCalledFunction() &&
3233 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3235 if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3236 Func == LibFunc::fabsl) {
3237 switch (I.getPredicate()) {
3239 // fabs(x) < 0 --> false
3240 case FCmpInst::FCMP_OLT:
3241 return ReplaceInstUsesWith(I, Builder->getFalse());
3242 // fabs(x) > 0 --> x != 0
3243 case FCmpInst::FCMP_OGT:
3244 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3246 // fabs(x) <= 0 --> x == 0
3247 case FCmpInst::FCMP_OLE:
3248 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3250 // fabs(x) >= 0 --> !isnan(x)
3251 case FCmpInst::FCMP_OGE:
3252 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3254 // fabs(x) == 0 --> x == 0
3255 // fabs(x) != 0 --> x != 0
3256 case FCmpInst::FCMP_OEQ:
3257 case FCmpInst::FCMP_UEQ:
3258 case FCmpInst::FCMP_ONE:
3259 case FCmpInst::FCMP_UNE:
3260 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3269 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
3271 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
3272 return new FCmpInst(I.getSwappedPredicate(), X, Y);
3274 // fcmp (fpext x), (fpext y) -> fcmp x, y
3275 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3276 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3277 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3278 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3279 RHSExt->getOperand(0));
3281 return Changed ? &I : 0;