blob: 249de571e553efcc98eb28d7dc6e36ef3e0658f0 [file] [log] [blame]
Chris Lattner02446fc2010-01-04 07:37:31 +00001//===- InstCombineCompares.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitICmp and visitFCmp functions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
15#include "llvm/IntrinsicInst.h"
Eli Friedman74703252011-07-20 21:57:23 +000016#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner02446fc2010-01-04 07:37:31 +000017#include "llvm/Analysis/InstructionSimplify.h"
18#include "llvm/Analysis/MemoryBuiltins.h"
19#include "llvm/Target/TargetData.h"
20#include "llvm/Support/ConstantRange.h"
21#include "llvm/Support/GetElementPtrTypeIterator.h"
22#include "llvm/Support/PatternMatch.h"
23using namespace llvm;
24using namespace PatternMatch;
25
Chris Lattnerb20c0b52011-02-10 05:23:05 +000026static ConstantInt *getOne(Constant *C) {
27 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
28}
29
Chris Lattner02446fc2010-01-04 07:37:31 +000030/// AddOne - Add one to a ConstantInt
31static Constant *AddOne(Constant *C) {
32 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
33}
34/// SubOne - Subtract one from a ConstantInt
Chris Lattnerb20c0b52011-02-10 05:23:05 +000035static Constant *SubOne(Constant *C) {
36 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner02446fc2010-01-04 07:37:31 +000037}
38
39static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
40 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
41}
42
43static bool HasAddOverflow(ConstantInt *Result,
44 ConstantInt *In1, ConstantInt *In2,
45 bool IsSigned) {
Chris Lattnerc73b24d2011-07-15 06:08:15 +000046 if (!IsSigned)
Chris Lattner02446fc2010-01-04 07:37:31 +000047 return Result->getValue().ult(In1->getValue());
Chris Lattnerc73b24d2011-07-15 06:08:15 +000048
49 if (In2->isNegative())
50 return Result->getValue().sgt(In1->getValue());
51 return Result->getValue().slt(In1->getValue());
Chris Lattner02446fc2010-01-04 07:37:31 +000052}
53
54/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
55/// overflowed for this type.
56static bool AddWithOverflow(Constant *&Result, Constant *In1,
57 Constant *In2, bool IsSigned = false) {
58 Result = ConstantExpr::getAdd(In1, In2);
59
Chris Lattnerdb125cf2011-07-18 04:54:35 +000060 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner02446fc2010-01-04 07:37:31 +000061 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
62 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
63 if (HasAddOverflow(ExtractElement(Result, Idx),
64 ExtractElement(In1, Idx),
65 ExtractElement(In2, Idx),
66 IsSigned))
67 return true;
68 }
69 return false;
70 }
71
72 return HasAddOverflow(cast<ConstantInt>(Result),
73 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
74 IsSigned);
75}
76
77static bool HasSubOverflow(ConstantInt *Result,
78 ConstantInt *In1, ConstantInt *In2,
79 bool IsSigned) {
Chris Lattnerc73b24d2011-07-15 06:08:15 +000080 if (!IsSigned)
Chris Lattner02446fc2010-01-04 07:37:31 +000081 return Result->getValue().ugt(In1->getValue());
Jim Grosbach0cc4a952011-09-30 18:09:53 +000082
Chris Lattnerc73b24d2011-07-15 06:08:15 +000083 if (In2->isNegative())
84 return Result->getValue().slt(In1->getValue());
85
86 return Result->getValue().sgt(In1->getValue());
Chris Lattner02446fc2010-01-04 07:37:31 +000087}
88
89/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
90/// overflowed for this type.
91static bool SubWithOverflow(Constant *&Result, Constant *In1,
92 Constant *In2, bool IsSigned = false) {
93 Result = ConstantExpr::getSub(In1, In2);
94
Chris Lattnerdb125cf2011-07-18 04:54:35 +000095 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner02446fc2010-01-04 07:37:31 +000096 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
97 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
98 if (HasSubOverflow(ExtractElement(Result, Idx),
99 ExtractElement(In1, Idx),
100 ExtractElement(In2, Idx),
101 IsSigned))
102 return true;
103 }
104 return false;
105 }
106
107 return HasSubOverflow(cast<ConstantInt>(Result),
108 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
109 IsSigned);
110}
111
112/// isSignBitCheck - Given an exploded icmp instruction, return true if the
113/// comparison only checks the sign bit. If it only checks the sign bit, set
114/// TrueIfSigned if the result of the comparison is true when the input value is
115/// signed.
116static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
117 bool &TrueIfSigned) {
118 switch (pred) {
119 case ICmpInst::ICMP_SLT: // True if LHS s< 0
120 TrueIfSigned = true;
121 return RHS->isZero();
122 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
123 TrueIfSigned = true;
124 return RHS->isAllOnesValue();
125 case ICmpInst::ICMP_SGT: // True if LHS s> -1
126 TrueIfSigned = false;
127 return RHS->isAllOnesValue();
128 case ICmpInst::ICMP_UGT:
129 // True if LHS u> RHS and RHS == high-bit-mask - 1
130 TrueIfSigned = true;
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000131 return RHS->isMaxValue(true);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000132 case ICmpInst::ICMP_UGE:
Chris Lattner02446fc2010-01-04 07:37:31 +0000133 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
134 TrueIfSigned = true;
135 return RHS->getValue().isSignBit();
136 default:
137 return false;
138 }
139}
140
141// isHighOnes - Return true if the constant is of the form 1+0+.
142// This is the same as lowones(~X).
143static bool isHighOnes(const ConstantInt *CI) {
144 return (~CI->getValue() + 1).isPowerOf2();
145}
146
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000147/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
Chris Lattner02446fc2010-01-04 07:37:31 +0000148/// set of known zero and one bits, compute the maximum and minimum values that
149/// could have the specified known zero and known one bits, returning them in
150/// min/max.
151static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
152 const APInt& KnownOne,
153 APInt& Min, APInt& Max) {
154 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
155 KnownZero.getBitWidth() == Min.getBitWidth() &&
156 KnownZero.getBitWidth() == Max.getBitWidth() &&
157 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
158 APInt UnknownBits = ~(KnownZero|KnownOne);
159
160 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
161 // bit if it is unknown.
162 Min = KnownOne;
163 Max = KnownOne|UnknownBits;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000164
Chris Lattner02446fc2010-01-04 07:37:31 +0000165 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad7a874dd2010-12-01 08:53:58 +0000166 Min.setBit(Min.getBitWidth()-1);
167 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner02446fc2010-01-04 07:37:31 +0000168 }
169}
170
171// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
172// a set of known zero and one bits, compute the maximum and minimum values that
173// could have the specified known zero and known one bits, returning them in
174// min/max.
175static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
176 const APInt &KnownOne,
177 APInt &Min, APInt &Max) {
178 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
179 KnownZero.getBitWidth() == Min.getBitWidth() &&
180 KnownZero.getBitWidth() == Max.getBitWidth() &&
181 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
182 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000183
Chris Lattner02446fc2010-01-04 07:37:31 +0000184 // The minimum value is when the unknown bits are all zeros.
185 Min = KnownOne;
186 // The maximum value is when the unknown bits are all ones.
187 Max = KnownOne|UnknownBits;
188}
189
190
191
192/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
193/// cmp pred (load (gep GV, ...)), cmpcst
194/// where GV is a global variable with a constant initializer. Try to simplify
195/// this into some simple computation that does not need the load. For example
196/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
197///
198/// If AndCst is non-null, then the loaded value is masked with that constant
199/// before doing the comparison. This handles cases like "A[i]&4 == 0".
200Instruction *InstCombiner::
201FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
202 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattnerd7f5a582010-01-04 18:57:15 +0000203 // We need TD information to know the pointer size unless this is inbounds.
204 if (!GEP->isInBounds() && TD == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000205
Chris Lattner02446fc2010-01-04 07:37:31 +0000206 ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer());
207 if (Init == 0 || Init->getNumOperands() > 1024) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000208
Chris Lattner02446fc2010-01-04 07:37:31 +0000209 // There are many forms of this optimization we can handle, for now, just do
210 // the simple index into a single-dimensional array.
211 //
212 // Require: GEP GV, 0, i {{, constant indices}}
213 if (GEP->getNumOperands() < 3 ||
214 !isa<ConstantInt>(GEP->getOperand(1)) ||
215 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
216 isa<Constant>(GEP->getOperand(2)))
217 return 0;
218
219 // Check that indices after the variable are constants and in-range for the
220 // type they index. Collect the indices. This is typically for arrays of
221 // structs.
222 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000223
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000224 Type *EltTy = cast<ArrayType>(Init->getType())->getElementType();
Chris Lattner02446fc2010-01-04 07:37:31 +0000225 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
226 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
227 if (Idx == 0) return 0; // Variable index.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000228
Chris Lattner02446fc2010-01-04 07:37:31 +0000229 uint64_t IdxVal = Idx->getZExtValue();
230 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000231
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000232 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner02446fc2010-01-04 07:37:31 +0000233 EltTy = STy->getElementType(IdxVal);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000234 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000235 if (IdxVal >= ATy->getNumElements()) return 0;
236 EltTy = ATy->getElementType();
237 } else {
238 return 0; // Unknown type.
239 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000240
Chris Lattner02446fc2010-01-04 07:37:31 +0000241 LaterIndices.push_back(IdxVal);
242 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000243
Chris Lattner02446fc2010-01-04 07:37:31 +0000244 enum { Overdefined = -3, Undefined = -2 };
245
246 // Variables for our state machines.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000247
Chris Lattner02446fc2010-01-04 07:37:31 +0000248 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
249 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
250 // and 87 is the second (and last) index. FirstTrueElement is -2 when
251 // undefined, otherwise set to the first true element. SecondTrueElement is
252 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
253 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
254
255 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
256 // form "i != 47 & i != 87". Same state transitions as for true elements.
257 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000258
Chris Lattner02446fc2010-01-04 07:37:31 +0000259 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
260 /// define a state machine that triggers for ranges of values that the index
261 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
262 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
263 /// index in the range (inclusive). We use -2 for undefined here because we
264 /// use relative comparisons and don't want 0-1 to match -1.
265 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000266
Chris Lattner02446fc2010-01-04 07:37:31 +0000267 // MagicBitvector - This is a magic bitvector where we set a bit if the
268 // comparison is true for element 'i'. If there are 64 elements or less in
269 // the array, this will fully represent all the comparison results.
270 uint64_t MagicBitvector = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000271
272
Chris Lattner02446fc2010-01-04 07:37:31 +0000273 // Scan the array and see if one of our patterns matches.
274 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
275 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
276 Constant *Elt = Init->getOperand(i);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000277
Chris Lattner02446fc2010-01-04 07:37:31 +0000278 // If this is indexing an array of structures, get the structure element.
279 if (!LaterIndices.empty())
Jay Foadfc6d3a42011-07-13 10:26:04 +0000280 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000281
Chris Lattner02446fc2010-01-04 07:37:31 +0000282 // If the element is masked, handle it.
283 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000284
Chris Lattner02446fc2010-01-04 07:37:31 +0000285 // Find out if the comparison would be true or false for the i'th element.
286 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
287 CompareRHS, TD);
288 // If the result is undef for this element, ignore it.
289 if (isa<UndefValue>(C)) {
290 // Extend range state machines to cover this element in case there is an
291 // undef in the middle of the range.
292 if (TrueRangeEnd == (int)i-1)
293 TrueRangeEnd = i;
294 if (FalseRangeEnd == (int)i-1)
295 FalseRangeEnd = i;
296 continue;
297 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000298
Chris Lattner02446fc2010-01-04 07:37:31 +0000299 // If we can't compute the result for any of the elements, we have to give
300 // up evaluating the entire conditional.
301 if (!isa<ConstantInt>(C)) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000302
Chris Lattner02446fc2010-01-04 07:37:31 +0000303 // Otherwise, we know if the comparison is true or false for this element,
304 // update our state machines.
305 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000306
Chris Lattner02446fc2010-01-04 07:37:31 +0000307 // State machine for single/double/range index comparison.
308 if (IsTrueForElt) {
309 // Update the TrueElement state machine.
310 if (FirstTrueElement == Undefined)
311 FirstTrueElement = TrueRangeEnd = i; // First true element.
312 else {
313 // Update double-compare state machine.
314 if (SecondTrueElement == Undefined)
315 SecondTrueElement = i;
316 else
317 SecondTrueElement = Overdefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000318
Chris Lattner02446fc2010-01-04 07:37:31 +0000319 // Update range state machine.
320 if (TrueRangeEnd == (int)i-1)
321 TrueRangeEnd = i;
322 else
323 TrueRangeEnd = Overdefined;
324 }
325 } else {
326 // Update the FalseElement state machine.
327 if (FirstFalseElement == Undefined)
328 FirstFalseElement = FalseRangeEnd = i; // First false element.
329 else {
330 // Update double-compare state machine.
331 if (SecondFalseElement == Undefined)
332 SecondFalseElement = i;
333 else
334 SecondFalseElement = Overdefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000335
Chris Lattner02446fc2010-01-04 07:37:31 +0000336 // Update range state machine.
337 if (FalseRangeEnd == (int)i-1)
338 FalseRangeEnd = i;
339 else
340 FalseRangeEnd = Overdefined;
341 }
342 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000343
344
Chris Lattner02446fc2010-01-04 07:37:31 +0000345 // If this element is in range, update our magic bitvector.
346 if (i < 64 && IsTrueForElt)
347 MagicBitvector |= 1ULL << i;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000348
Chris Lattner02446fc2010-01-04 07:37:31 +0000349 // If all of our states become overdefined, bail out early. Since the
350 // predicate is expensive, only check it every 8 elements. This is only
351 // really useful for really huge arrays.
352 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
353 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
354 FalseRangeEnd == Overdefined)
355 return 0;
356 }
357
358 // Now that we've scanned the entire array, emit our new comparison(s). We
359 // order the state machines in complexity of the generated code.
360 Value *Idx = GEP->getOperand(2);
361
Chris Lattnerd7f5a582010-01-04 18:57:15 +0000362 // If the index is larger than the pointer size of the target, truncate the
363 // index down like the GEP would do implicitly. We don't have to do this for
364 // an inbounds GEP because the index can't be out of range.
365 if (!GEP->isInBounds() &&
366 Idx->getType()->getPrimitiveSizeInBits() > TD->getPointerSizeInBits())
367 Idx = Builder->CreateTrunc(Idx, TD->getIntPtrType(Idx->getContext()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000368
Chris Lattner02446fc2010-01-04 07:37:31 +0000369 // If the comparison is only true for one or two elements, emit direct
370 // comparisons.
371 if (SecondTrueElement != Overdefined) {
372 // None true -> false.
373 if (FirstTrueElement == Undefined)
374 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(GEP->getContext()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000375
Chris Lattner02446fc2010-01-04 07:37:31 +0000376 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000377
Chris Lattner02446fc2010-01-04 07:37:31 +0000378 // True for one element -> 'i == 47'.
379 if (SecondTrueElement == Undefined)
380 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000381
Chris Lattner02446fc2010-01-04 07:37:31 +0000382 // True for two elements -> 'i == 47 | i == 72'.
383 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
384 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
385 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
386 return BinaryOperator::CreateOr(C1, C2);
387 }
388
389 // If the comparison is only false for one or two elements, emit direct
390 // comparisons.
391 if (SecondFalseElement != Overdefined) {
392 // None false -> true.
393 if (FirstFalseElement == Undefined)
394 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(GEP->getContext()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000395
Chris Lattner02446fc2010-01-04 07:37:31 +0000396 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
397
398 // False for one element -> 'i != 47'.
399 if (SecondFalseElement == Undefined)
400 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000401
Chris Lattner02446fc2010-01-04 07:37:31 +0000402 // False for two elements -> 'i != 47 & i != 72'.
403 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
404 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
405 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
406 return BinaryOperator::CreateAnd(C1, C2);
407 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000408
Chris Lattner02446fc2010-01-04 07:37:31 +0000409 // If the comparison can be replaced with a range comparison for the elements
410 // where it is true, emit the range check.
411 if (TrueRangeEnd != Overdefined) {
412 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000413
Chris Lattner02446fc2010-01-04 07:37:31 +0000414 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
415 if (FirstTrueElement) {
416 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
417 Idx = Builder->CreateAdd(Idx, Offs);
418 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000419
Chris Lattner02446fc2010-01-04 07:37:31 +0000420 Value *End = ConstantInt::get(Idx->getType(),
421 TrueRangeEnd-FirstTrueElement+1);
422 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
423 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000424
Chris Lattner02446fc2010-01-04 07:37:31 +0000425 // False range check.
426 if (FalseRangeEnd != Overdefined) {
427 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
428 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
429 if (FirstFalseElement) {
430 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
431 Idx = Builder->CreateAdd(Idx, Offs);
432 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000433
Chris Lattner02446fc2010-01-04 07:37:31 +0000434 Value *End = ConstantInt::get(Idx->getType(),
435 FalseRangeEnd-FirstFalseElement);
436 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
437 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000438
439
Chris Lattner02446fc2010-01-04 07:37:31 +0000440 // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
441 // of this load, replace it with computation that does:
442 // ((magic_cst >> i) & 1) != 0
443 if (Init->getNumOperands() <= 32 ||
444 (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000445 Type *Ty;
Chris Lattner02446fc2010-01-04 07:37:31 +0000446 if (Init->getNumOperands() <= 32)
447 Ty = Type::getInt32Ty(Init->getContext());
448 else
449 Ty = Type::getInt64Ty(Init->getContext());
450 Value *V = Builder->CreateIntCast(Idx, Ty, false);
451 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
452 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
453 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
454 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000455
Chris Lattner02446fc2010-01-04 07:37:31 +0000456 return 0;
457}
458
459
460/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
461/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
462/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
463/// be complex, and scales are involved. The above expression would also be
464/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
465/// This later form is less amenable to optimization though, and we are allowed
466/// to generate the first by knowing that pointer arithmetic doesn't overflow.
467///
468/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000469///
Eli Friedman107ffd52011-05-18 23:11:30 +0000470static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000471 TargetData &TD = *IC.getTargetData();
472 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000473
Chris Lattner02446fc2010-01-04 07:37:31 +0000474 // Check to see if this gep only has a single variable index. If so, and if
475 // any constant indices are a multiple of its scale, then we can compute this
476 // in terms of the scale of the variable index. For example, if the GEP
477 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
478 // because the expression will cross zero at the same point.
479 unsigned i, e = GEP->getNumOperands();
480 int64_t Offset = 0;
481 for (i = 1; i != e; ++i, ++GTI) {
482 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
483 // Compute the aggregate offset of constant indices.
484 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000485
Chris Lattner02446fc2010-01-04 07:37:31 +0000486 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000487 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000488 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
489 } else {
490 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
491 Offset += Size*CI->getSExtValue();
492 }
493 } else {
494 // Found our variable index.
495 break;
496 }
497 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000498
Chris Lattner02446fc2010-01-04 07:37:31 +0000499 // If there are no variable indices, we must have a constant offset, just
500 // evaluate it the general way.
501 if (i == e) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000502
Chris Lattner02446fc2010-01-04 07:37:31 +0000503 Value *VariableIdx = GEP->getOperand(i);
504 // Determine the scale factor of the variable element. For example, this is
505 // 4 if the variable index is into an array of i32.
506 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000507
Chris Lattner02446fc2010-01-04 07:37:31 +0000508 // Verify that there are no other variable indices. If so, emit the hard way.
509 for (++i, ++GTI; i != e; ++i, ++GTI) {
510 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
511 if (!CI) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000512
Chris Lattner02446fc2010-01-04 07:37:31 +0000513 // Compute the aggregate offset of constant indices.
514 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000515
Chris Lattner02446fc2010-01-04 07:37:31 +0000516 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000517 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000518 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
519 } else {
520 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
521 Offset += Size*CI->getSExtValue();
522 }
523 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000524
Chris Lattner02446fc2010-01-04 07:37:31 +0000525 // Okay, we know we have a single variable index, which must be a
526 // pointer/array/vector index. If there is no offset, life is simple, return
527 // the index.
528 unsigned IntPtrWidth = TD.getPointerSizeInBits();
529 if (Offset == 0) {
530 // Cast to intptrty in case a truncation occurs. If an extension is needed,
531 // we don't need to bother extending: the extension won't affect where the
532 // computation crosses zero.
Eli Friedman107ffd52011-05-18 23:11:30 +0000533 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000534 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Eli Friedman107ffd52011-05-18 23:11:30 +0000535 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
536 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000537 return VariableIdx;
538 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000539
Chris Lattner02446fc2010-01-04 07:37:31 +0000540 // Otherwise, there is an index. The computation we will do will be modulo
541 // the pointer size, so get it.
542 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000543
Chris Lattner02446fc2010-01-04 07:37:31 +0000544 Offset &= PtrSizeMask;
545 VariableScale &= PtrSizeMask;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000546
Chris Lattner02446fc2010-01-04 07:37:31 +0000547 // To do this transformation, any constant index must be a multiple of the
548 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
549 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
550 // multiple of the variable scale.
551 int64_t NewOffs = Offset / (int64_t)VariableScale;
552 if (Offset != NewOffs*(int64_t)VariableScale)
553 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000554
Chris Lattner02446fc2010-01-04 07:37:31 +0000555 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000556 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner02446fc2010-01-04 07:37:31 +0000557 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman107ffd52011-05-18 23:11:30 +0000558 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
559 true /*Signed*/);
Chris Lattner02446fc2010-01-04 07:37:31 +0000560 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman107ffd52011-05-18 23:11:30 +0000561 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner02446fc2010-01-04 07:37:31 +0000562}
563
564/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
565/// else. At this point we know that the GEP is on the LHS of the comparison.
566Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
567 ICmpInst::Predicate Cond,
568 Instruction &I) {
569 // Look through bitcasts.
570 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
571 RHS = BCI->getOperand(0);
572
573 Value *PtrBase = GEPLHS->getOperand(0);
574 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
575 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
576 // This transformation (ignoring the base and scales) is valid because we
577 // know pointers can't overflow since the gep is inbounds. See if we can
578 // output an optimized form.
Eli Friedman107ffd52011-05-18 23:11:30 +0000579 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000580
Chris Lattner02446fc2010-01-04 07:37:31 +0000581 // If not, synthesize the offset the hard way.
582 if (Offset == 0)
583 Offset = EmitGEPOffset(GEPLHS);
584 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
585 Constant::getNullValue(Offset->getType()));
586 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
587 // If the base pointers are different, but the indices are the same, just
588 // compare the base pointer.
589 if (PtrBase != GEPRHS->getOperand(0)) {
590 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
591 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
592 GEPRHS->getOperand(0)->getType();
593 if (IndicesTheSame)
594 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
595 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
596 IndicesTheSame = false;
597 break;
598 }
599
600 // If all indices are the same, just compare the base pointers.
601 if (IndicesTheSame)
602 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
603 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
604
605 // Otherwise, the base pointers are different and the indices are
606 // different, bail out.
607 return 0;
608 }
609
610 // If one of the GEPs has all zero indices, recurse.
611 bool AllZeros = true;
612 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
613 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
614 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
615 AllZeros = false;
616 break;
617 }
618 if (AllZeros)
619 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
620 ICmpInst::getSwappedPredicate(Cond), I);
621
622 // If the other GEP has all zero indices, recurse.
623 AllZeros = true;
624 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
625 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
626 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
627 AllZeros = false;
628 break;
629 }
630 if (AllZeros)
631 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
632
Stuart Hastings67f071e2011-05-14 05:55:10 +0000633 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner02446fc2010-01-04 07:37:31 +0000634 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
635 // If the GEPs only differ by one index, compare it.
636 unsigned NumDifferences = 0; // Keep track of # differences.
637 unsigned DiffOperand = 0; // The operand that differs.
638 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
639 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
640 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
641 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
642 // Irreconcilable differences.
643 NumDifferences = 2;
644 break;
645 } else {
646 if (NumDifferences++) break;
647 DiffOperand = i;
648 }
649 }
650
651 if (NumDifferences == 0) // SAME GEP?
652 return ReplaceInstUsesWith(I, // No comparison is needed here.
653 ConstantInt::get(Type::getInt1Ty(I.getContext()),
654 ICmpInst::isTrueWhenEqual(Cond)));
655
Stuart Hastings67f071e2011-05-14 05:55:10 +0000656 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000657 Value *LHSV = GEPLHS->getOperand(DiffOperand);
658 Value *RHSV = GEPRHS->getOperand(DiffOperand);
659 // Make sure we do a signed comparison here.
660 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
661 }
662 }
663
664 // Only lower this if the icmp is the only user of the GEP or if we expect
665 // the result to fold to a constant!
666 if (TD &&
Stuart Hastings67f071e2011-05-14 05:55:10 +0000667 GEPsInBounds &&
Chris Lattner02446fc2010-01-04 07:37:31 +0000668 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
669 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
670 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
671 Value *L = EmitGEPOffset(GEPLHS);
672 Value *R = EmitGEPOffset(GEPRHS);
673 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
674 }
675 }
676 return 0;
677}
678
679/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
680Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
681 Value *X, ConstantInt *CI,
682 ICmpInst::Predicate Pred,
683 Value *TheAdd) {
684 // If we have X+0, exit early (simplifying logic below) and let it get folded
685 // elsewhere. icmp X+0, X -> icmp X, X
686 if (CI->isZero()) {
687 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
688 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
689 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000690
Chris Lattner02446fc2010-01-04 07:37:31 +0000691 // (X+4) == X -> false.
692 if (Pred == ICmpInst::ICMP_EQ)
693 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
694
695 // (X+4) != X -> true.
696 if (Pred == ICmpInst::ICMP_NE)
697 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
698
Chris Lattner02446fc2010-01-04 07:37:31 +0000699 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000700 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner02446fc2010-01-04 07:37:31 +0000701 // operators.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000702
Chris Lattner9aa1e242010-01-08 17:48:19 +0000703 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner02446fc2010-01-04 07:37:31 +0000704 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
705 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
706 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000707 Value *R =
Chris Lattner9aa1e242010-01-08 17:48:19 +0000708 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner02446fc2010-01-04 07:37:31 +0000709 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
710 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000711
Chris Lattner02446fc2010-01-04 07:37:31 +0000712 // (X+1) >u X --> X <u (0-1) --> X != 255
713 // (X+2) >u X --> X <u (0-2) --> X <u 254
714 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandsa7724332011-02-17 07:46:37 +0000715 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000716 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000717
Chris Lattner02446fc2010-01-04 07:37:31 +0000718 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
719 ConstantInt *SMax = ConstantInt::get(X->getContext(),
720 APInt::getSignedMaxValue(BitWidth));
721
722 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
723 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
724 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
725 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
726 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
727 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandsa7724332011-02-17 07:46:37 +0000728 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000729 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000730
Chris Lattner02446fc2010-01-04 07:37:31 +0000731 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
732 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
733 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
734 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
735 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
736 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000737
Chris Lattner02446fc2010-01-04 07:37:31 +0000738 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
739 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
740 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
741}
742
743/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
744/// and CmpRHS are both known to be integer constants.
745Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
746 ConstantInt *DivRHS) {
747 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
748 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000749
750 // FIXME: If the operand types don't match the type of the divide
Chris Lattner02446fc2010-01-04 07:37:31 +0000751 // then don't attempt this transform. The code below doesn't have the
752 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000753 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner02446fc2010-01-04 07:37:31 +0000754 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000755 // (x /u C1) <u C2. Simply casting the operands and result won't
756 // work. :( The if statement below tests that condition and bails
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000757 // if it finds it.
Chris Lattner02446fc2010-01-04 07:37:31 +0000758 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
759 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
760 return 0;
761 if (DivRHS->isZero())
762 return 0; // The ProdOV computation fails on divide by zero.
763 if (DivIsSigned && DivRHS->isAllOnesValue())
764 return 0; // The overflow computation also screws up here
Chris Lattnerbb75d332011-02-13 08:07:21 +0000765 if (DivRHS->isOne()) {
766 // This eliminates some funny cases with INT_MIN.
767 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
768 return &ICI;
769 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000770
771 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000772 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
773 // C2 (CI). By solving for X we can turn this into a range check
774 // instead of computing a divide.
Chris Lattner02446fc2010-01-04 07:37:31 +0000775 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
776
777 // Determine if the product overflows by seeing if the product is
778 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000779 // as in the LHS instruction that we're folding.
Chris Lattner02446fc2010-01-04 07:37:31 +0000780 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
781 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
782
783 // Get the ICmp opcode
784 ICmpInst::Predicate Pred = ICI.getPredicate();
785
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000786 /// If the division is known to be exact, then there is no remainder from the
787 /// divide, so the covered range size is unit, otherwise it is the divisor.
788 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000789
Chris Lattner02446fc2010-01-04 07:37:31 +0000790 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000791 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner02446fc2010-01-04 07:37:31 +0000792 // Compute this interval based on the constants involved and the signedness of
793 // the compare/divide. This computes a half-open interval, keeping track of
794 // whether either value in the interval overflows. After analysis each
795 // overflow variable is set to 0 if it's corresponding bound variable is valid
796 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
797 int LoOverflow = 0, HiOverflow = 0;
798 Constant *LoBound = 0, *HiBound = 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000799
Chris Lattner02446fc2010-01-04 07:37:31 +0000800 if (!DivIsSigned) { // udiv
801 // e.g. X/5 op 3 --> [15, 20)
802 LoBound = Prod;
803 HiOverflow = LoOverflow = ProdOV;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000804 if (!HiOverflow) {
805 // If this is not an exact divide, then many values in the range collapse
806 // to the same result value.
807 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
808 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000809
Chris Lattner02446fc2010-01-04 07:37:31 +0000810 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
811 if (CmpRHSV == 0) { // (X / pos) op 0
812 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000813 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
814 HiBound = RangeSize;
Chris Lattner02446fc2010-01-04 07:37:31 +0000815 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
816 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
817 HiOverflow = LoOverflow = ProdOV;
818 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000819 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000820 } else { // (X / pos) op neg
821 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
822 HiBound = AddOne(Prod);
823 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
824 if (!LoOverflow) {
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000825 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000826 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000827 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000828 }
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000829 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000830 if (DivI->isExact())
831 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000832 if (CmpRHSV == 0) { // (X / neg) op 0
833 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000834 LoBound = AddOne(RangeSize);
835 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000836 if (HiBound == DivRHS) { // -INTMIN = INTMIN
837 HiOverflow = 1; // [INTMIN+1, overflow)
838 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
839 }
840 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
841 // e.g. X/-5 op 3 --> [-19, -14)
842 HiBound = AddOne(Prod);
843 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
844 if (!LoOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000845 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner02446fc2010-01-04 07:37:31 +0000846 } else { // (X / neg) op neg
847 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
848 LoOverflow = HiOverflow = ProdOV;
849 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000850 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000851 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000852
Chris Lattner02446fc2010-01-04 07:37:31 +0000853 // Dividing by a negative swaps the condition. LT <-> GT
854 Pred = ICmpInst::getSwappedPredicate(Pred);
855 }
856
857 Value *X = DivI->getOperand(0);
858 switch (Pred) {
859 default: llvm_unreachable("Unhandled icmp opcode!");
860 case ICmpInst::ICMP_EQ:
861 if (LoOverflow && HiOverflow)
862 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000863 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000864 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
865 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000866 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000867 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
868 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000869 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
870 DivIsSigned, true));
Chris Lattner02446fc2010-01-04 07:37:31 +0000871 case ICmpInst::ICMP_NE:
872 if (LoOverflow && HiOverflow)
873 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000874 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000875 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
876 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000877 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000878 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
879 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000880 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
881 DivIsSigned, false));
Chris Lattner02446fc2010-01-04 07:37:31 +0000882 case ICmpInst::ICMP_ULT:
883 case ICmpInst::ICMP_SLT:
884 if (LoOverflow == +1) // Low bound is greater than input range.
885 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
886 if (LoOverflow == -1) // Low bound is less than input range.
887 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
888 return new ICmpInst(Pred, X, LoBound);
889 case ICmpInst::ICMP_UGT:
890 case ICmpInst::ICMP_SGT:
891 if (HiOverflow == +1) // High bound greater than input range.
892 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000893 if (HiOverflow == -1) // High bound less than input range.
Chris Lattner02446fc2010-01-04 07:37:31 +0000894 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
895 if (Pred == ICmpInst::ICMP_UGT)
896 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000897 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner02446fc2010-01-04 07:37:31 +0000898 }
899}
900
Chris Lattner74542aa2011-02-13 07:43:07 +0000901/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
902Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
903 ConstantInt *ShAmt) {
Chris Lattner74542aa2011-02-13 07:43:07 +0000904 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000905
Chris Lattner74542aa2011-02-13 07:43:07 +0000906 // Check that the shift amount is in range. If not, don't perform
907 // undefined shifts. When the shift is visited it will be
908 // simplified.
909 uint32_t TypeBits = CmpRHSV.getBitWidth();
910 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnerbb75d332011-02-13 08:07:21 +0000911 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Chris Lattner74542aa2011-02-13 07:43:07 +0000912 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000913
Chris Lattnerbb75d332011-02-13 08:07:21 +0000914 if (!ICI.isEquality()) {
915 // If we have an unsigned comparison and an ashr, we can't simplify this.
916 // Similarly for signed comparisons with lshr.
917 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
918 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000919
Eli Friedmana831a9b2011-05-25 23:26:20 +0000920 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
921 // by a power of 2. Since we already have logic to simplify these,
922 // transform to div and then simplify the resultant comparison.
Chris Lattnerbb75d332011-02-13 08:07:21 +0000923 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedmana831a9b2011-05-25 23:26:20 +0000924 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Chris Lattnerbb75d332011-02-13 08:07:21 +0000925 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000926
Chris Lattnerbb75d332011-02-13 08:07:21 +0000927 // Revisit the shift (to delete it).
928 Worklist.Add(Shr);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000929
Chris Lattnerbb75d332011-02-13 08:07:21 +0000930 Constant *DivCst =
931 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000932
Chris Lattnerbb75d332011-02-13 08:07:21 +0000933 Value *Tmp =
934 Shr->getOpcode() == Instruction::AShr ?
935 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
936 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000937
Chris Lattnerbb75d332011-02-13 08:07:21 +0000938 ICI.setOperand(0, Tmp);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000939
Chris Lattnerbb75d332011-02-13 08:07:21 +0000940 // If the builder folded the binop, just return it.
941 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
942 if (TheDiv == 0)
943 return &ICI;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000944
Chris Lattnerbb75d332011-02-13 08:07:21 +0000945 // Otherwise, fold this div/compare.
946 assert(TheDiv->getOpcode() == Instruction::SDiv ||
947 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000948
Chris Lattnerbb75d332011-02-13 08:07:21 +0000949 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
950 assert(Res && "This div/cst should have folded!");
951 return Res;
952 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000953
954
Chris Lattner74542aa2011-02-13 07:43:07 +0000955 // If we are comparing against bits always shifted out, the
956 // comparison cannot succeed.
957 APInt Comp = CmpRHSV << ShAmtVal;
958 ConstantInt *ShiftedCmpRHS = ConstantInt::get(ICI.getContext(), Comp);
959 if (Shr->getOpcode() == Instruction::LShr)
960 Comp = Comp.lshr(ShAmtVal);
961 else
962 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000963
Chris Lattner74542aa2011-02-13 07:43:07 +0000964 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
965 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
966 Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
967 IsICMP_NE);
968 return ReplaceInstUsesWith(ICI, Cst);
969 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000970
Chris Lattner74542aa2011-02-13 07:43:07 +0000971 // Otherwise, check to see if the bits shifted out are known to be zero.
972 // If so, we can compare against the unshifted value:
973 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattnere5116f82011-02-13 18:30:09 +0000974 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattner74542aa2011-02-13 07:43:07 +0000975 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000976
Chris Lattner74542aa2011-02-13 07:43:07 +0000977 if (Shr->hasOneUse()) {
978 // Otherwise strength reduce the shift into an and.
979 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
980 Constant *Mask = ConstantInt::get(ICI.getContext(), Val);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000981
Chris Lattner74542aa2011-02-13 07:43:07 +0000982 Value *And = Builder->CreateAnd(Shr->getOperand(0),
983 Mask, Shr->getName()+".mask");
984 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
985 }
986 return 0;
987}
988
Chris Lattner02446fc2010-01-04 07:37:31 +0000989
990/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
991///
992Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
993 Instruction *LHSI,
994 ConstantInt *RHS) {
995 const APInt &RHSV = RHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000996
Chris Lattner02446fc2010-01-04 07:37:31 +0000997 switch (LHSI->getOpcode()) {
998 case Instruction::Trunc:
999 if (ICI.isEquality() && LHSI->hasOneUse()) {
1000 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1001 // of the high bits truncated out of x are known.
1002 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1003 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
1004 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
1005 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
1006 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001007
Chris Lattner02446fc2010-01-04 07:37:31 +00001008 // If all the high bits are known, we can do this xform.
1009 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1010 // Pull in the high bits from known-ones set.
Jay Foad40f8f622010-12-07 08:25:19 +00001011 APInt NewRHS = RHS->getValue().zext(SrcBits);
Chris Lattner02446fc2010-01-04 07:37:31 +00001012 NewRHS |= KnownOne;
1013 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1014 ConstantInt::get(ICI.getContext(), NewRHS));
1015 }
1016 }
1017 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001018
Chris Lattner02446fc2010-01-04 07:37:31 +00001019 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
1020 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1021 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1022 // fold the xor.
1023 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1024 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1025 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001026
Chris Lattner02446fc2010-01-04 07:37:31 +00001027 // If the sign bit of the XorCST is not set, there is no change to
1028 // the operation, just stop using the Xor.
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001029 if (!XorCST->isNegative()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001030 ICI.setOperand(0, CompareVal);
1031 Worklist.Add(LHSI);
1032 return &ICI;
1033 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001034
Chris Lattner02446fc2010-01-04 07:37:31 +00001035 // Was the old condition true if the operand is positive?
1036 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001037
Chris Lattner02446fc2010-01-04 07:37:31 +00001038 // If so, the new one isn't.
1039 isTrueIfPositive ^= true;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001040
Chris Lattner02446fc2010-01-04 07:37:31 +00001041 if (isTrueIfPositive)
1042 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1043 SubOne(RHS));
1044 else
1045 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1046 AddOne(RHS));
1047 }
1048
1049 if (LHSI->hasOneUse()) {
1050 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1051 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
1052 const APInt &SignBit = XorCST->getValue();
1053 ICmpInst::Predicate Pred = ICI.isSigned()
1054 ? ICI.getUnsignedPredicate()
1055 : ICI.getSignedPredicate();
1056 return new ICmpInst(Pred, LHSI->getOperand(0),
1057 ConstantInt::get(ICI.getContext(),
1058 RHSV ^ SignBit));
1059 }
1060
1061 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001062 if (!ICI.isEquality() && XorCST->isMaxValue(true)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001063 const APInt &NotSignBit = XorCST->getValue();
1064 ICmpInst::Predicate Pred = ICI.isSigned()
1065 ? ICI.getUnsignedPredicate()
1066 : ICI.getSignedPredicate();
1067 Pred = ICI.getSwappedPredicate(Pred);
1068 return new ICmpInst(Pred, LHSI->getOperand(0),
1069 ConstantInt::get(ICI.getContext(),
1070 RHSV ^ NotSignBit));
1071 }
1072 }
1073 }
1074 break;
1075 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
1076 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1077 LHSI->getOperand(0)->hasOneUse()) {
1078 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001079
Chris Lattner02446fc2010-01-04 07:37:31 +00001080 // If the LHS is an AND of a truncating cast, we can widen the
1081 // and/compare to be the input width without changing the value
1082 // produced, eliminating a cast.
1083 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1084 // We can do this transformation if either the AND constant does not
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001085 // have its sign bit set or if it is an equality comparison.
Chris Lattner02446fc2010-01-04 07:37:31 +00001086 // Extending a relational comparison when we're checking the sign
1087 // bit would not work.
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001088 if (ICI.isEquality() ||
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001089 (!AndCST->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001090 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001091 Builder->CreateAnd(Cast->getOperand(0),
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001092 ConstantExpr::getZExt(AndCST, Cast->getSrcTy()));
1093 NewAnd->takeName(LHSI);
Chris Lattner02446fc2010-01-04 07:37:31 +00001094 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001095 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001096 }
1097 }
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001098
1099 // If the LHS is an AND of a zext, and we have an equality compare, we can
1100 // shrink the and/compare to the smaller type, eliminating the cast.
1101 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001102 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001103 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1104 // should fold the icmp to true/false in that case.
1105 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1106 Value *NewAnd =
1107 Builder->CreateAnd(Cast->getOperand(0),
1108 ConstantExpr::getTrunc(AndCST, Ty));
1109 NewAnd->takeName(LHSI);
1110 return new ICmpInst(ICI.getPredicate(), NewAnd,
1111 ConstantExpr::getTrunc(RHS, Ty));
1112 }
1113 }
1114
Chris Lattner02446fc2010-01-04 07:37:31 +00001115 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1116 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1117 // happens a LOT in code produced by the C front-end, for bitfield
1118 // access.
1119 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1120 if (Shift && !Shift->isShift())
1121 Shift = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001122
Chris Lattner02446fc2010-01-04 07:37:31 +00001123 ConstantInt *ShAmt;
1124 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001125 Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
1126 Type *AndTy = AndCST->getType(); // Type of the and.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001127
Chris Lattner02446fc2010-01-04 07:37:31 +00001128 // We can fold this as long as we can't shift unknown bits
1129 // into the mask. This can only happen with signed shift
1130 // rights, as they sign-extend.
1131 if (ShAmt) {
1132 bool CanFold = Shift->isLogicalShift();
1133 if (!CanFold) {
1134 // To test for the bad case of the signed shr, see if any
1135 // of the bits shifted in could be tested after the mask.
1136 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1137 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001138
Chris Lattner02446fc2010-01-04 07:37:31 +00001139 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001140 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
Chris Lattner02446fc2010-01-04 07:37:31 +00001141 AndCST->getValue()) == 0)
1142 CanFold = true;
1143 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001144
Chris Lattner02446fc2010-01-04 07:37:31 +00001145 if (CanFold) {
1146 Constant *NewCst;
1147 if (Shift->getOpcode() == Instruction::Shl)
1148 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1149 else
1150 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001151
Chris Lattner02446fc2010-01-04 07:37:31 +00001152 // Check to see if we are shifting out any of the bits being
1153 // compared.
1154 if (ConstantExpr::get(Shift->getOpcode(),
1155 NewCst, ShAmt) != RHS) {
1156 // If we shifted bits out, the fold is not going to work out.
1157 // As a special case, check to see if this means that the
1158 // result is always true or false now.
1159 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1160 return ReplaceInstUsesWith(ICI,
1161 ConstantInt::getFalse(ICI.getContext()));
1162 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1163 return ReplaceInstUsesWith(ICI,
1164 ConstantInt::getTrue(ICI.getContext()));
1165 } else {
1166 ICI.setOperand(1, NewCst);
1167 Constant *NewAndCST;
1168 if (Shift->getOpcode() == Instruction::Shl)
1169 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1170 else
1171 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1172 LHSI->setOperand(1, NewAndCST);
1173 LHSI->setOperand(0, Shift->getOperand(0));
1174 Worklist.Add(Shift); // Shift is dead.
1175 return &ICI;
1176 }
1177 }
1178 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001179
Chris Lattner02446fc2010-01-04 07:37:31 +00001180 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1181 // preferable because it allows the C<<Y expression to be hoisted out
1182 // of a loop if Y is invariant and X is not.
1183 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1184 ICI.isEquality() && !Shift->isArithmeticShift() &&
1185 !isa<Constant>(Shift->getOperand(0))) {
1186 // Compute C << Y.
1187 Value *NS;
1188 if (Shift->getOpcode() == Instruction::LShr) {
Benjamin Kramera9390a42011-09-27 20:39:19 +00001189 NS = Builder->CreateShl(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001190 } else {
1191 // Insert a logical shift.
Benjamin Kramera9390a42011-09-27 20:39:19 +00001192 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001193 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001194
Chris Lattner02446fc2010-01-04 07:37:31 +00001195 // Compute X & (C << Y).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001196 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001197 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001198
Chris Lattner02446fc2010-01-04 07:37:31 +00001199 ICI.setOperand(0, NewAnd);
1200 return &ICI;
1201 }
1202 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001203
Chris Lattner02446fc2010-01-04 07:37:31 +00001204 // Try to optimize things like "A[i]&42 == 0" to index computations.
1205 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1206 if (GetElementPtrInst *GEP =
1207 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1208 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1209 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1210 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1211 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1212 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1213 return Res;
1214 }
1215 }
1216 break;
1217
1218 case Instruction::Or: {
1219 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1220 break;
1221 Value *P, *Q;
1222 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1223 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1224 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner02446fc2010-01-04 07:37:31 +00001225 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1226 Constant::getNullValue(P->getType()));
1227 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1228 Constant::getNullValue(Q->getType()));
1229 Instruction *Op;
1230 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1231 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1232 else
1233 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1234 return Op;
1235 }
1236 break;
1237 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001238
Chris Lattner02446fc2010-01-04 07:37:31 +00001239 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
1240 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1241 if (!ShAmt) break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001242
Chris Lattner02446fc2010-01-04 07:37:31 +00001243 uint32_t TypeBits = RHSV.getBitWidth();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001244
Chris Lattner02446fc2010-01-04 07:37:31 +00001245 // Check that the shift amount is in range. If not, don't perform
1246 // undefined shifts. When the shift is visited it will be
1247 // simplified.
1248 if (ShAmt->uge(TypeBits))
1249 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001250
Chris Lattner02446fc2010-01-04 07:37:31 +00001251 if (ICI.isEquality()) {
1252 // If we are comparing against bits always shifted out, the
1253 // comparison cannot succeed.
1254 Constant *Comp =
1255 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1256 ShAmt);
1257 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1258 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1259 Constant *Cst =
1260 ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE);
1261 return ReplaceInstUsesWith(ICI, Cst);
1262 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001263
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001264 // If the shift is NUW, then it is just shifting out zeros, no need for an
1265 // AND.
1266 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1267 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1268 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001269
Chris Lattner02446fc2010-01-04 07:37:31 +00001270 if (LHSI->hasOneUse()) {
1271 // Otherwise strength reduce the shift into an and.
1272 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1273 Constant *Mask =
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001274 ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits,
Chris Lattner02446fc2010-01-04 07:37:31 +00001275 TypeBits-ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001276
Chris Lattner02446fc2010-01-04 07:37:31 +00001277 Value *And =
1278 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1279 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001280 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner02446fc2010-01-04 07:37:31 +00001281 }
1282 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001283
Chris Lattner02446fc2010-01-04 07:37:31 +00001284 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1285 bool TrueIfSigned = false;
1286 if (LHSI->hasOneUse() &&
1287 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1288 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattnerbb75d332011-02-13 08:07:21 +00001289 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001290 APInt::getOneBitSet(TypeBits,
Chris Lattnerbb75d332011-02-13 08:07:21 +00001291 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001292 Value *And =
1293 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1294 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1295 And, Constant::getNullValue(And->getType()));
1296 }
1297 break;
1298 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001299
Chris Lattner02446fc2010-01-04 07:37:31 +00001300 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001301 case Instruction::AShr: {
1302 // Handle equality comparisons of shift-by-constant.
1303 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1304 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1305 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattner74542aa2011-02-13 07:43:07 +00001306 return Res;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001307 }
1308
1309 // Handle exact shr's.
1310 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1311 if (RHSV.isMinValue())
1312 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1313 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001314 break;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001315 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001316
Chris Lattner02446fc2010-01-04 07:37:31 +00001317 case Instruction::SDiv:
1318 case Instruction::UDiv:
1319 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001320 // Fold this div into the comparison, producing a range check.
1321 // Determine, based on the divide type, what the range is being
1322 // checked. If there is an overflow on the low or high side, remember
Chris Lattner02446fc2010-01-04 07:37:31 +00001323 // it, otherwise compute the range [low, hi) bounding the new value.
1324 // See: InsertRangeTest above for the kinds of replacements possible.
1325 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1326 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1327 DivRHS))
1328 return R;
1329 break;
1330
1331 case Instruction::Add:
1332 // Fold: icmp pred (add X, C1), C2
1333 if (!ICI.isEquality()) {
1334 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1335 if (!LHSC) break;
1336 const APInt &LHSV = LHSC->getValue();
1337
1338 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1339 .subtract(LHSV);
1340
1341 if (ICI.isSigned()) {
1342 if (CR.getLower().isSignBit()) {
1343 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1344 ConstantInt::get(ICI.getContext(),CR.getUpper()));
1345 } else if (CR.getUpper().isSignBit()) {
1346 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1347 ConstantInt::get(ICI.getContext(),CR.getLower()));
1348 }
1349 } else {
1350 if (CR.getLower().isMinValue()) {
1351 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1352 ConstantInt::get(ICI.getContext(),CR.getUpper()));
1353 } else if (CR.getUpper().isMinValue()) {
1354 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1355 ConstantInt::get(ICI.getContext(),CR.getLower()));
1356 }
1357 }
1358 }
1359 break;
1360 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001361
Chris Lattner02446fc2010-01-04 07:37:31 +00001362 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1363 if (ICI.isEquality()) {
1364 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001365
1366 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner02446fc2010-01-04 07:37:31 +00001367 // the second operand is a constant, simplify a bit.
1368 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1369 switch (BO->getOpcode()) {
1370 case Instruction::SRem:
1371 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1372 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1373 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohmane0567812010-04-08 23:03:40 +00001374 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001375 Value *NewRem =
1376 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1377 BO->getName());
1378 return new ICmpInst(ICI.getPredicate(), NewRem,
1379 Constant::getNullValue(BO->getType()));
1380 }
1381 }
1382 break;
1383 case Instruction::Add:
1384 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1385 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1386 if (BO->hasOneUse())
1387 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1388 ConstantExpr::getSub(RHS, BOp1C));
1389 } else if (RHSV == 0) {
1390 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1391 // efficiently invertible, or if the add has just this one use.
1392 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001393
Chris Lattner02446fc2010-01-04 07:37:31 +00001394 if (Value *NegVal = dyn_castNegVal(BOp1))
1395 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner5036ce42011-04-26 20:02:45 +00001396 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner02446fc2010-01-04 07:37:31 +00001397 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner5036ce42011-04-26 20:02:45 +00001398 if (BO->hasOneUse()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001399 Value *Neg = Builder->CreateNeg(BOp1);
1400 Neg->takeName(BO);
1401 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1402 }
1403 }
1404 break;
1405 case Instruction::Xor:
1406 // For the xor case, we can xor two constants together, eliminating
1407 // the explicit xor.
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001408 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1409 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner02446fc2010-01-04 07:37:31 +00001410 ConstantExpr::getXor(RHS, BOC));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001411 } else if (RHSV == 0) {
1412 // Replace ((xor A, B) != 0) with (A != B)
Chris Lattner02446fc2010-01-04 07:37:31 +00001413 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1414 BO->getOperand(1));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001415 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001416 break;
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001417 case Instruction::Sub:
1418 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1419 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1420 if (BO->hasOneUse())
1421 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1422 ConstantExpr::getSub(BOp0C, RHS));
1423 } else if (RHSV == 0) {
1424 // Replace ((sub A, B) != 0) with (A != B)
1425 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1426 BO->getOperand(1));
1427 }
1428 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001429 case Instruction::Or:
1430 // If bits are being or'd in that are not present in the constant we
1431 // are comparing against, then the comparison could never succeed!
Eli Friedman618898e2010-07-29 18:03:33 +00001432 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001433 Constant *NotCI = ConstantExpr::getNot(RHS);
1434 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1435 return ReplaceInstUsesWith(ICI,
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001436 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
Chris Lattner02446fc2010-01-04 07:37:31 +00001437 isICMP_NE));
1438 }
1439 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001440
Chris Lattner02446fc2010-01-04 07:37:31 +00001441 case Instruction::And:
1442 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1443 // If bits are being compared against that are and'd out, then the
1444 // comparison can never succeed!
1445 if ((RHSV & ~BOC->getValue()) != 0)
1446 return ReplaceInstUsesWith(ICI,
1447 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1448 isICMP_NE));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001449
Chris Lattner02446fc2010-01-04 07:37:31 +00001450 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1451 if (RHS == BOC && RHSV.isPowerOf2())
1452 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1453 ICmpInst::ICMP_NE, LHSI,
1454 Constant::getNullValue(RHS->getType()));
Benjamin Kramerfc87cdc2011-07-04 20:16:36 +00001455
1456 // Don't perform the following transforms if the AND has multiple uses
1457 if (!BO->hasOneUse())
1458 break;
1459
Chris Lattner02446fc2010-01-04 07:37:31 +00001460 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1461 if (BOC->getValue().isSignBit()) {
1462 Value *X = BO->getOperand(0);
1463 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001464 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001465 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1466 return new ICmpInst(pred, X, Zero);
1467 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001468
Chris Lattner02446fc2010-01-04 07:37:31 +00001469 // ((X & ~7) == 0) --> X < 8
1470 if (RHSV == 0 && isHighOnes(BOC)) {
1471 Value *X = BO->getOperand(0);
1472 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001473 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001474 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1475 return new ICmpInst(pred, X, NegX);
1476 }
1477 }
1478 default: break;
1479 }
1480 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1481 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner03357402010-01-05 18:09:56 +00001482 switch (II->getIntrinsicID()) {
1483 case Intrinsic::bswap:
Chris Lattner02446fc2010-01-04 07:37:31 +00001484 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001485 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00001486 ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
1487 return &ICI;
Chris Lattner03357402010-01-05 18:09:56 +00001488 case Intrinsic::ctlz:
1489 case Intrinsic::cttz:
1490 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1491 if (RHSV == RHS->getType()->getBitWidth()) {
1492 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001493 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001494 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1495 return &ICI;
1496 }
1497 break;
1498 case Intrinsic::ctpop:
1499 // popcount(A) == 0 -> A == 0 and likewise for !=
1500 if (RHS->isZero()) {
1501 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001502 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001503 ICI.setOperand(1, RHS);
1504 return &ICI;
1505 }
1506 break;
1507 default:
Duncan Sands34727662010-07-12 08:16:59 +00001508 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001509 }
1510 }
1511 }
1512 return 0;
1513}
1514
1515/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1516/// We only handle extending casts so far.
1517///
1518Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1519 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1520 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001521 Type *SrcTy = LHSCIOp->getType();
1522 Type *DestTy = LHSCI->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00001523 Value *RHSCIOp;
1524
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001525 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner02446fc2010-01-04 07:37:31 +00001526 // integer type is the same size as the pointer type.
1527 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
1528 TD->getPointerSizeInBits() ==
1529 cast<IntegerType>(DestTy)->getBitWidth()) {
1530 Value *RHSOp = 0;
1531 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1532 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1533 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1534 RHSOp = RHSC->getOperand(0);
1535 // If the pointer types don't match, insert a bitcast.
1536 if (LHSCIOp->getType() != RHSOp->getType())
1537 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1538 }
1539
1540 if (RHSOp)
1541 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1542 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001543
Chris Lattner02446fc2010-01-04 07:37:31 +00001544 // The code below only handles extension cast instructions, so far.
1545 // Enforce this.
1546 if (LHSCI->getOpcode() != Instruction::ZExt &&
1547 LHSCI->getOpcode() != Instruction::SExt)
1548 return 0;
1549
1550 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1551 bool isSignedCmp = ICI.isSigned();
1552
1553 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1554 // Not an extension from the same type?
1555 RHSCIOp = CI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001556 if (RHSCIOp->getType() != LHSCIOp->getType())
Chris Lattner02446fc2010-01-04 07:37:31 +00001557 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001558
Chris Lattner02446fc2010-01-04 07:37:31 +00001559 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1560 // and the other is a zext), then we can't handle this.
1561 if (CI->getOpcode() != LHSCI->getOpcode())
1562 return 0;
1563
1564 // Deal with equality cases early.
1565 if (ICI.isEquality())
1566 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1567
1568 // A signed comparison of sign extended values simplifies into a
1569 // signed comparison.
1570 if (isSignedCmp && isSignedExt)
1571 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1572
1573 // The other three cases all fold into an unsigned comparison.
1574 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1575 }
1576
1577 // If we aren't dealing with a constant on the RHS, exit early
1578 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1579 if (!CI)
1580 return 0;
1581
1582 // Compute the constant that would happen if we truncated to SrcTy then
1583 // reextended to DestTy.
1584 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1585 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1586 Res1, DestTy);
1587
1588 // If the re-extended constant didn't change...
1589 if (Res2 == CI) {
1590 // Deal with equality cases early.
1591 if (ICI.isEquality())
1592 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1593
1594 // A signed comparison of sign extended values simplifies into a
1595 // signed comparison.
1596 if (isSignedExt && isSignedCmp)
1597 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1598
1599 // The other three cases all fold into an unsigned comparison.
1600 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1601 }
1602
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001603 // The re-extended constant changed so the constant cannot be represented
Chris Lattner02446fc2010-01-04 07:37:31 +00001604 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands9d32f602011-01-20 13:21:55 +00001605 // All the cases that fold to true or false will have already been handled
1606 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner02446fc2010-01-04 07:37:31 +00001607
Duncan Sands9d32f602011-01-20 13:21:55 +00001608 if (isSignedCmp || !isSignedExt)
1609 return 0;
Chris Lattner02446fc2010-01-04 07:37:31 +00001610
1611 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1612 // should have been folded away previously and not enter in here.
Duncan Sands9d32f602011-01-20 13:21:55 +00001613
1614 // We're performing an unsigned comp with a sign extended value.
1615 // This is true if the input is >= 0. [aka >s -1]
1616 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1617 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner02446fc2010-01-04 07:37:31 +00001618
1619 // Finally, return the value computed.
Duncan Sands9d32f602011-01-20 13:21:55 +00001620 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner02446fc2010-01-04 07:37:31 +00001621 return ReplaceInstUsesWith(ICI, Result);
1622
Duncan Sands9d32f602011-01-20 13:21:55 +00001623 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner02446fc2010-01-04 07:37:31 +00001624 return BinaryOperator::CreateNot(Result);
1625}
1626
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001627/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1628/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001629/// If this is of the form:
1630/// sum = a + b
1631/// if (sum+128 >u 255)
1632/// Then replace it with llvm.sadd.with.overflow.i8.
1633///
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001634static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1635 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001636 InstCombiner &IC) {
Chris Lattner368397b2010-12-19 17:59:02 +00001637 // The transformation we're trying to do here is to transform this into an
1638 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1639 // with a narrower add, and discard the add-with-constant that is part of the
1640 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001641
Chris Lattner368397b2010-12-19 17:59:02 +00001642 // In order to eliminate the add-with-constant, the compare can be its only
1643 // use.
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001644 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Chris Lattner368397b2010-12-19 17:59:02 +00001645 if (!AddWithCst->hasOneUse()) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001646
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001647 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1648 if (!CI2->getValue().isPowerOf2()) return 0;
1649 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1650 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001651
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001652 // The width of the new add formed is 1 more than the bias.
1653 ++NewWidth;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001654
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001655 // Check to see that CI1 is an all-ones value with NewWidth bits.
1656 if (CI1->getBitWidth() == NewWidth ||
1657 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1658 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001659
Eli Friedman54b92112011-11-28 23:32:19 +00001660 // This is only really a signed overflow check if the inputs have been
1661 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1662 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1663 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1664 if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1665 IC.ComputeNumSignBits(B) < NeededSignBits)
1666 return 0;
1667
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001668 // In order to replace the original add with a narrower
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001669 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1670 // and truncates that discard the high bits of the add. Verify that this is
1671 // the case.
1672 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1673 for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1674 UI != E; ++UI) {
1675 if (*UI == AddWithCst) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001676
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001677 // Only accept truncates for now. We would really like a nice recursive
1678 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1679 // chain to see which bits of a value are actually demanded. If the
1680 // original add had another add which was then immediately truncated, we
1681 // could still do the transformation.
1682 TruncInst *TI = dyn_cast<TruncInst>(*UI);
1683 if (TI == 0 ||
1684 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1685 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001686
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001687 // If the pattern matches, truncate the inputs to the narrower type and
1688 // use the sadd_with_overflow intrinsic to efficiently compute both the
1689 // result and the overflow bit.
Chris Lattner0a624742010-12-19 18:35:09 +00001690 Module *M = I.getParent()->getParent()->getParent();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001691
Jay Foad5fdd6c82011-07-12 14:06:48 +00001692 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Chris Lattner0a624742010-12-19 18:35:09 +00001693 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001694 NewType);
Chris Lattner0a624742010-12-19 18:35:09 +00001695
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001696 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001697
Chris Lattner0a624742010-12-19 18:35:09 +00001698 // Put the new code above the original add, in case there are any uses of the
1699 // add between the add and the compare.
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001700 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001701
Chris Lattner0a624742010-12-19 18:35:09 +00001702 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1703 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1704 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1705 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1706 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001707
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001708 // The inner add was the result of the narrow add, zero extended to the
1709 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001710 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001711
Chris Lattner0a624742010-12-19 18:35:09 +00001712 // The original icmp gets replaced with the overflow value.
1713 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001714}
Chris Lattner02446fc2010-01-04 07:37:31 +00001715
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001716static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1717 InstCombiner &IC) {
1718 // Don't bother doing this transformation for pointers, don't do it for
1719 // vectors.
1720 if (!isa<IntegerType>(OrigAddV->getType())) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001721
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001722 // If the add is a constant expr, then we don't bother transforming it.
1723 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1724 if (OrigAdd == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001725
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001726 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001727
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001728 // Put the new code above the original add, in case there are any uses of the
1729 // add between the add and the compare.
1730 InstCombiner::BuilderTy *Builder = IC.Builder;
1731 Builder->SetInsertPoint(OrigAdd);
1732
1733 Module *M = I.getParent()->getParent()->getParent();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001734 Type *Ty = LHS->getType();
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001735 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001736 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1737 Value *Add = Builder->CreateExtractValue(Call, 0);
1738
1739 IC.ReplaceInstUsesWith(*OrigAdd, Add);
1740
1741 // The original icmp gets replaced with the overflow value.
1742 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
1743}
1744
Owen Andersonda1c1222011-01-11 00:36:45 +00001745// DemandedBitsLHSMask - When performing a comparison against a constant,
1746// it is possible that not all the bits in the LHS are demanded. This helper
1747// method computes the mask that IS demanded.
1748static APInt DemandedBitsLHSMask(ICmpInst &I,
1749 unsigned BitWidth, bool isSignCheck) {
1750 if (isSignCheck)
1751 return APInt::getSignBit(BitWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001752
Owen Andersonda1c1222011-01-11 00:36:45 +00001753 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
1754 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Andersona33b6252011-01-11 18:26:37 +00001755 const APInt &RHS = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001756
Owen Andersonda1c1222011-01-11 00:36:45 +00001757 switch (I.getPredicate()) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001758 // For a UGT comparison, we don't care about any bits that
Owen Andersonda1c1222011-01-11 00:36:45 +00001759 // correspond to the trailing ones of the comparand. The value of these
1760 // bits doesn't impact the outcome of the comparison, because any value
1761 // greater than the RHS must differ in a bit higher than these due to carry.
1762 case ICmpInst::ICMP_UGT: {
1763 unsigned trailingOnes = RHS.countTrailingOnes();
1764 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
1765 return ~lowBitsSet;
1766 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001767
Owen Andersonda1c1222011-01-11 00:36:45 +00001768 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
1769 // Any value less than the RHS must differ in a higher bit because of carries.
1770 case ICmpInst::ICMP_ULT: {
1771 unsigned trailingZeros = RHS.countTrailingZeros();
1772 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
1773 return ~lowBitsSet;
1774 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001775
Owen Andersonda1c1222011-01-11 00:36:45 +00001776 default:
1777 return APInt::getAllOnesValue(BitWidth);
1778 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001779
Owen Andersonda1c1222011-01-11 00:36:45 +00001780}
Chris Lattner02446fc2010-01-04 07:37:31 +00001781
1782Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
1783 bool Changed = false;
Chris Lattner5f670d42010-02-01 19:54:45 +00001784 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001785
Chris Lattner02446fc2010-01-04 07:37:31 +00001786 /// Orders the operands of the compare so that they are listed from most
1787 /// complex to least complex. This puts constants before unary operators,
1788 /// before binary operators.
Chris Lattner5f670d42010-02-01 19:54:45 +00001789 if (getComplexity(Op0) < getComplexity(Op1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001790 I.swapOperands();
Chris Lattner5f670d42010-02-01 19:54:45 +00001791 std::swap(Op0, Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00001792 Changed = true;
1793 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001794
Chris Lattner02446fc2010-01-04 07:37:31 +00001795 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
1796 return ReplaceInstUsesWith(I, V);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001797
Pete Cooper65a6b572011-12-01 03:58:40 +00001798 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooper165695d2011-12-01 19:13:26 +00001799 // ie, abs(val) != 0 -> val != 0
Pete Cooper65a6b572011-12-01 03:58:40 +00001800 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
1801 {
Pete Cooper165695d2011-12-01 19:13:26 +00001802 Value *Cond, *SelectTrue, *SelectFalse;
1803 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooper65a6b572011-12-01 03:58:40 +00001804 m_Value(SelectFalse)))) {
Pete Cooper165695d2011-12-01 19:13:26 +00001805 if (Value *V = dyn_castNegVal(SelectTrue)) {
1806 if (V == SelectFalse)
1807 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
1808 }
1809 else if (Value *V = dyn_castNegVal(SelectFalse)) {
1810 if (V == SelectTrue)
1811 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooper65a6b572011-12-01 03:58:40 +00001812 }
1813 }
1814 }
1815
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001816 Type *Ty = Op0->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00001817
1818 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001819 if (Ty->isIntegerTy(1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001820 switch (I.getPredicate()) {
1821 default: llvm_unreachable("Invalid icmp instruction!");
1822 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
1823 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
1824 return BinaryOperator::CreateNot(Xor);
1825 }
1826 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
1827 return BinaryOperator::CreateXor(Op0, Op1);
1828
1829 case ICmpInst::ICMP_UGT:
1830 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
1831 // FALL THROUGH
1832 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
1833 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1834 return BinaryOperator::CreateAnd(Not, Op1);
1835 }
1836 case ICmpInst::ICMP_SGT:
1837 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
1838 // FALL THROUGH
1839 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
1840 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1841 return BinaryOperator::CreateAnd(Not, Op0);
1842 }
1843 case ICmpInst::ICMP_UGE:
1844 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
1845 // FALL THROUGH
1846 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
1847 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1848 return BinaryOperator::CreateOr(Not, Op1);
1849 }
1850 case ICmpInst::ICMP_SGE:
1851 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
1852 // FALL THROUGH
1853 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
1854 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1855 return BinaryOperator::CreateOr(Not, Op0);
1856 }
1857 }
1858 }
1859
1860 unsigned BitWidth = 0;
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001861 if (Ty->isIntOrIntVectorTy())
Chris Lattner02446fc2010-01-04 07:37:31 +00001862 BitWidth = Ty->getScalarSizeInBits();
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001863 else if (TD) // Pointers require TD info to get their size.
1864 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001865
Chris Lattner02446fc2010-01-04 07:37:31 +00001866 bool isSignBit = false;
1867
1868 // See if we are doing a comparison with a constant.
1869 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1870 Value *A = 0, *B = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001871
Owen Andersone63dda52010-12-17 18:08:00 +00001872 // Match the following pattern, which is a common idiom when writing
1873 // overflow-safe integer arithmetic function. The source performs an
1874 // addition in wider type, and explicitly checks for overflow using
1875 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
1876 // sadd_with_overflow intrinsic.
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001877 //
1878 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001879 // operations if we worked out the formulas to compute the appropriate
Owen Andersone63dda52010-12-17 18:08:00 +00001880 // magic constants.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001881 //
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001882 // sum = a + b
1883 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Andersone63dda52010-12-17 18:08:00 +00001884 {
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001885 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Andersone63dda52010-12-17 18:08:00 +00001886 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001887 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001888 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001889 return Res;
Owen Andersone63dda52010-12-17 18:08:00 +00001890 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001891
Chris Lattner02446fc2010-01-04 07:37:31 +00001892 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
1893 if (I.isEquality() && CI->isZero() &&
1894 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
1895 // (icmp cond A B) if cond is equality
1896 return new ICmpInst(I.getPredicate(), A, B);
1897 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001898
Chris Lattner02446fc2010-01-04 07:37:31 +00001899 // If we have an icmp le or icmp ge instruction, turn it into the
1900 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
1901 // them being folded in the code below. The SimplifyICmpInst code has
1902 // already handled the edge cases for us, so we just assert on them.
1903 switch (I.getPredicate()) {
1904 default: break;
1905 case ICmpInst::ICMP_ULE:
1906 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
1907 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
1908 ConstantInt::get(CI->getContext(), CI->getValue()+1));
1909 case ICmpInst::ICMP_SLE:
1910 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
1911 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
1912 ConstantInt::get(CI->getContext(), CI->getValue()+1));
1913 case ICmpInst::ICMP_UGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001914 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00001915 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
1916 ConstantInt::get(CI->getContext(), CI->getValue()-1));
1917 case ICmpInst::ICMP_SGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001918 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00001919 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
1920 ConstantInt::get(CI->getContext(), CI->getValue()-1));
1921 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001922
Chris Lattner02446fc2010-01-04 07:37:31 +00001923 // If this comparison is a normal comparison, it demands all
1924 // bits, if it is a sign bit comparison, it only demands the sign bit.
1925 bool UnusedBit;
1926 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
1927 }
1928
1929 // See if we can fold the comparison based on range information we can get
1930 // by checking whether bits are known to be zero or one in the input.
1931 if (BitWidth != 0) {
1932 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
1933 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
1934
1935 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersonda1c1222011-01-11 00:36:45 +00001936 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner02446fc2010-01-04 07:37:31 +00001937 Op0KnownZero, Op0KnownOne, 0))
1938 return &I;
1939 if (SimplifyDemandedBits(I.getOperandUse(1),
1940 APInt::getAllOnesValue(BitWidth),
1941 Op1KnownZero, Op1KnownOne, 0))
1942 return &I;
1943
1944 // Given the known and unknown bits, compute a range that the LHS could be
1945 // in. Compute the Min, Max and RHS values based on the known bits. For the
1946 // EQ and NE we use unsigned values.
1947 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
1948 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
1949 if (I.isSigned()) {
1950 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1951 Op0Min, Op0Max);
1952 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1953 Op1Min, Op1Max);
1954 } else {
1955 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1956 Op0Min, Op0Max);
1957 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1958 Op1Min, Op1Max);
1959 }
1960
1961 // If Min and Max are known to be the same, then SimplifyDemandedBits
1962 // figured out that the LHS is a constant. Just constant fold this now so
1963 // that code below can assume that Min != Max.
1964 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
1965 return new ICmpInst(I.getPredicate(),
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00001966 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00001967 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
1968 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00001969 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner02446fc2010-01-04 07:37:31 +00001970
1971 // Based on the range information we know about the LHS, see if we can
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001972 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner02446fc2010-01-04 07:37:31 +00001973 switch (I.getPredicate()) {
1974 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner75d8f592010-11-21 06:44:42 +00001975 case ICmpInst::ICMP_EQ: {
Chris Lattner02446fc2010-01-04 07:37:31 +00001976 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00001977 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001978
Chris Lattner75d8f592010-11-21 06:44:42 +00001979 // If all bits are known zero except for one, then we know at most one
1980 // bit is set. If the comparison is against zero, then this is a check
1981 // to see if *that* bit is set.
1982 APInt Op0KnownZeroInverted = ~Op0KnownZero;
1983 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
1984 // If the LHS is an AND with the same constant, look through it.
1985 Value *LHS = 0;
1986 ConstantInt *LHSC = 0;
1987 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
1988 LHSC->getValue() != Op0KnownZeroInverted)
1989 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001990
Chris Lattner75d8f592010-11-21 06:44:42 +00001991 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattner79b967b2010-11-23 02:42:04 +00001992 // then turn "((1 << x)&8) == 0" into "x != 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00001993 Value *X = 0;
1994 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
1995 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00001996 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00001997 ConstantInt::get(X->getType(), CmpVal));
1998 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001999
Chris Lattner75d8f592010-11-21 06:44:42 +00002000 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattner79b967b2010-11-23 02:42:04 +00002001 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002002 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002003 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002004 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002005 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002006 ConstantInt::get(X->getType(),
2007 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002008 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002009
Chris Lattner02446fc2010-01-04 07:37:31 +00002010 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002011 }
2012 case ICmpInst::ICMP_NE: {
Chris Lattner02446fc2010-01-04 07:37:31 +00002013 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002014 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002015
Chris Lattner75d8f592010-11-21 06:44:42 +00002016 // If all bits are known zero except for one, then we know at most one
2017 // bit is set. If the comparison is against zero, then this is a check
2018 // to see if *that* bit is set.
2019 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2020 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2021 // If the LHS is an AND with the same constant, look through it.
2022 Value *LHS = 0;
2023 ConstantInt *LHSC = 0;
2024 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2025 LHSC->getValue() != Op0KnownZeroInverted)
2026 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002027
Chris Lattner75d8f592010-11-21 06:44:42 +00002028 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattner79b967b2010-11-23 02:42:04 +00002029 // then turn "((1 << x)&8) != 0" into "x == 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002030 Value *X = 0;
2031 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2032 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002033 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002034 ConstantInt::get(X->getType(), CmpVal));
2035 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002036
Chris Lattner75d8f592010-11-21 06:44:42 +00002037 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattner79b967b2010-11-23 02:42:04 +00002038 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002039 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002040 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002041 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002042 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002043 ConstantInt::get(X->getType(),
2044 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002045 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002046
Chris Lattner02446fc2010-01-04 07:37:31 +00002047 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002048 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002049 case ICmpInst::ICMP_ULT:
2050 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002051 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002052 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002053 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002054 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2055 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2056 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2057 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2058 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2059 ConstantInt::get(CI->getContext(), CI->getValue()-1));
2060
2061 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2062 if (CI->isMinValue(true))
2063 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2064 Constant::getAllOnesValue(Op0->getType()));
2065 }
2066 break;
2067 case ICmpInst::ICMP_UGT:
2068 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002069 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002070 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002071 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002072
2073 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2074 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2075 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2076 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2077 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2078 ConstantInt::get(CI->getContext(), CI->getValue()+1));
2079
2080 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2081 if (CI->isMaxValue(true))
2082 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2083 Constant::getNullValue(Op0->getType()));
2084 }
2085 break;
2086 case ICmpInst::ICMP_SLT:
2087 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002088 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002089 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002090 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002091 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2092 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2093 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2094 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2095 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2096 ConstantInt::get(CI->getContext(), CI->getValue()-1));
2097 }
2098 break;
2099 case ICmpInst::ICMP_SGT:
2100 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002101 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002102 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002103 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002104
2105 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2106 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2107 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2108 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2109 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2110 ConstantInt::get(CI->getContext(), CI->getValue()+1));
2111 }
2112 break;
2113 case ICmpInst::ICMP_SGE:
2114 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2115 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002116 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002117 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002118 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002119 break;
2120 case ICmpInst::ICMP_SLE:
2121 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2122 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002123 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002124 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002125 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002126 break;
2127 case ICmpInst::ICMP_UGE:
2128 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2129 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002130 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002131 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002132 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002133 break;
2134 case ICmpInst::ICMP_ULE:
2135 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2136 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002137 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002138 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002139 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002140 break;
2141 }
2142
2143 // Turn a signed comparison into an unsigned one if both operands
2144 // are known to have the same sign.
2145 if (I.isSigned() &&
2146 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2147 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2148 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2149 }
2150
2151 // Test if the ICmpInst instruction is used exclusively by a select as
2152 // part of a minimum or maximum operation. If so, refrain from doing
2153 // any other folding. This helps out other analyses which understand
2154 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2155 // and CodeGen. And in this case, at least one of the comparison
2156 // operands has at least one user besides the compare (the select),
2157 // which would often largely negate the benefit of folding anyway.
2158 if (I.hasOneUse())
2159 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2160 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2161 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2162 return 0;
2163
2164 // See if we are doing a comparison between a constant and an instruction that
2165 // can be folded into the comparison.
2166 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002167 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2168 // instruction, see if that instruction also has constants so that the
2169 // instruction can be folded into the icmp
Chris Lattner02446fc2010-01-04 07:37:31 +00002170 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2171 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2172 return Res;
2173 }
2174
2175 // Handle icmp with constant (but not simple integer constant) RHS
2176 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2177 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2178 switch (LHSI->getOpcode()) {
2179 case Instruction::GetElementPtr:
2180 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2181 if (RHSC->isNullValue() &&
2182 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2183 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2184 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2185 break;
2186 case Instruction::PHI:
2187 // Only fold icmp into the PHI if the phi and icmp are in the same
2188 // block. If in the same block, we're encouraging jump threading. If
2189 // not, we are just pessimizing the code by making an i1 phi.
2190 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002191 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002192 return NV;
2193 break;
2194 case Instruction::Select: {
2195 // If either operand of the select is a constant, we can fold the
2196 // comparison into the select arms, which will cause one to be
2197 // constant folded and the select turned into a bitwise or.
2198 Value *Op1 = 0, *Op2 = 0;
2199 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2200 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2201 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2202 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2203
2204 // We only want to perform this transformation if it will not lead to
2205 // additional code. This is true if either both sides of the select
2206 // fold to a constant (in which case the icmp is replaced with a select
2207 // which will usually simplify) or this is the only user of the
2208 // select (in which case we are trading a select+icmp for a simpler
2209 // select+icmp).
2210 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2211 if (!Op1)
2212 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2213 RHSC, I.getName());
2214 if (!Op2)
2215 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2216 RHSC, I.getName());
2217 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2218 }
2219 break;
2220 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002221 case Instruction::IntToPtr:
2222 // icmp pred inttoptr(X), null -> icmp pred X, 0
2223 if (RHSC->isNullValue() && TD &&
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002224 TD->getIntPtrType(RHSC->getContext()) ==
Chris Lattner02446fc2010-01-04 07:37:31 +00002225 LHSI->getOperand(0)->getType())
2226 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2227 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2228 break;
2229
2230 case Instruction::Load:
2231 // Try to optimize things like "A[i] > 4" to index computations.
2232 if (GetElementPtrInst *GEP =
2233 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2234 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2235 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2236 !cast<LoadInst>(LHSI)->isVolatile())
2237 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2238 return Res;
2239 }
2240 break;
2241 }
2242 }
2243
2244 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2245 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2246 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2247 return NI;
2248 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2249 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2250 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2251 return NI;
2252
2253 // Test to see if the operands of the icmp are casted versions of other
2254 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
2255 // now.
2256 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002257 if (Op0->getType()->isPointerTy() &&
2258 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002259 // We keep moving the cast from the left operand over to the right
2260 // operand, where it can often be eliminated completely.
2261 Op0 = CI->getOperand(0);
2262
2263 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2264 // so eliminate it as well.
2265 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2266 Op1 = CI2->getOperand(0);
2267
2268 // If Op1 is a constant, we can fold the cast into the constant.
2269 if (Op0->getType() != Op1->getType()) {
2270 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2271 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2272 } else {
2273 // Otherwise, cast the RHS right before the icmp
2274 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2275 }
2276 }
2277 return new ICmpInst(I.getPredicate(), Op0, Op1);
2278 }
2279 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002280
Chris Lattner02446fc2010-01-04 07:37:31 +00002281 if (isa<CastInst>(Op0)) {
2282 // Handle the special case of: icmp (cast bool to X), <cst>
2283 // This comes up when you have code like
2284 // int X = A < B;
2285 // if (X) ...
2286 // For generality, we handle any zero-extension of any operand comparison
2287 // with a constant or another cast from the same type.
2288 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2289 if (Instruction *R = visitICmpInstWithCastAndCast(I))
2290 return R;
2291 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002292
Duncan Sandsa7724332011-02-17 07:46:37 +00002293 // Special logic for binary operators.
2294 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2295 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2296 if (BO0 || BO1) {
2297 CmpInst::Predicate Pred = I.getPredicate();
2298 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2299 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2300 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2301 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2302 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2303 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2304 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2305 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2306 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2307
2308 // Analyze the case when either Op0 or Op1 is an add instruction.
2309 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2310 Value *A = 0, *B = 0, *C = 0, *D = 0;
2311 if (BO0 && BO0->getOpcode() == Instruction::Add)
2312 A = BO0->getOperand(0), B = BO0->getOperand(1);
2313 if (BO1 && BO1->getOpcode() == Instruction::Add)
2314 C = BO1->getOperand(0), D = BO1->getOperand(1);
2315
2316 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2317 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2318 return new ICmpInst(Pred, A == Op1 ? B : A,
2319 Constant::getNullValue(Op1->getType()));
2320
2321 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2322 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2323 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2324 C == Op0 ? D : C);
2325
Duncan Sands39a7de72011-02-18 16:25:37 +00002326 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002327 if (A && C && (A == C || A == D || B == C || B == D) &&
2328 NoOp0WrapProblem && NoOp1WrapProblem &&
2329 // Try not to increase register pressure.
2330 BO0->hasOneUse() && BO1->hasOneUse()) {
2331 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2332 Value *Y = (A == C || A == D) ? B : A;
2333 Value *Z = (C == A || C == B) ? D : C;
2334 return new ICmpInst(Pred, Y, Z);
2335 }
2336
2337 // Analyze the case when either Op0 or Op1 is a sub instruction.
2338 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2339 A = 0; B = 0; C = 0; D = 0;
2340 if (BO0 && BO0->getOpcode() == Instruction::Sub)
2341 A = BO0->getOperand(0), B = BO0->getOperand(1);
2342 if (BO1 && BO1->getOpcode() == Instruction::Sub)
2343 C = BO1->getOperand(0), D = BO1->getOperand(1);
2344
Duncan Sands39a7de72011-02-18 16:25:37 +00002345 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2346 if (A == Op1 && NoOp0WrapProblem)
2347 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2348
2349 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2350 if (C == Op0 && NoOp1WrapProblem)
2351 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2352
2353 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002354 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2355 // Try not to increase register pressure.
2356 BO0->hasOneUse() && BO1->hasOneUse())
2357 return new ICmpInst(Pred, A, C);
2358
Duncan Sands39a7de72011-02-18 16:25:37 +00002359 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2360 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2361 // Try not to increase register pressure.
2362 BO0->hasOneUse() && BO1->hasOneUse())
2363 return new ICmpInst(Pred, D, B);
2364
Nick Lewycky9feda172011-03-05 04:28:48 +00002365 BinaryOperator *SRem = NULL;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002366 // icmp (srem X, Y), Y
Nick Lewycky9feda172011-03-05 04:28:48 +00002367 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2368 Op1 == BO0->getOperand(1))
2369 SRem = BO0;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002370 // icmp Y, (srem X, Y)
Nick Lewycky9feda172011-03-05 04:28:48 +00002371 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2372 Op0 == BO1->getOperand(1))
2373 SRem = BO1;
2374 if (SRem) {
2375 // We don't check hasOneUse to avoid increasing register pressure because
2376 // the value we use is the same value this instruction was already using.
2377 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2378 default: break;
2379 case ICmpInst::ICMP_EQ:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002380 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002381 case ICmpInst::ICMP_NE:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002382 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002383 case ICmpInst::ICMP_SGT:
2384 case ICmpInst::ICMP_SGE:
2385 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2386 Constant::getAllOnesValue(SRem->getType()));
2387 case ICmpInst::ICMP_SLT:
2388 case ICmpInst::ICMP_SLE:
2389 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2390 Constant::getNullValue(SRem->getType()));
2391 }
2392 }
2393
Duncan Sandsa7724332011-02-17 07:46:37 +00002394 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2395 BO0->hasOneUse() && BO1->hasOneUse() &&
2396 BO0->getOperand(1) == BO1->getOperand(1)) {
2397 switch (BO0->getOpcode()) {
2398 default: break;
2399 case Instruction::Add:
2400 case Instruction::Sub:
2401 case Instruction::Xor:
2402 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
2403 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2404 BO1->getOperand(0));
2405 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2406 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2407 if (CI->getValue().isSignBit()) {
2408 ICmpInst::Predicate Pred = I.isSigned()
2409 ? I.getUnsignedPredicate()
2410 : I.getSignedPredicate();
2411 return new ICmpInst(Pred, BO0->getOperand(0),
2412 BO1->getOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00002413 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002414
Chris Lattnerc73b24d2011-07-15 06:08:15 +00002415 if (CI->isMaxValue(true)) {
Duncan Sandsa7724332011-02-17 07:46:37 +00002416 ICmpInst::Predicate Pred = I.isSigned()
2417 ? I.getUnsignedPredicate()
2418 : I.getSignedPredicate();
2419 Pred = I.getSwappedPredicate(Pred);
2420 return new ICmpInst(Pred, BO0->getOperand(0),
2421 BO1->getOperand(0));
2422 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002423 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002424 break;
2425 case Instruction::Mul:
2426 if (!I.isEquality())
2427 break;
2428
2429 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2430 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2431 // Mask = -1 >> count-trailing-zeros(Cst).
2432 if (!CI->isZero() && !CI->isOne()) {
2433 const APInt &AP = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002434 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandsa7724332011-02-17 07:46:37 +00002435 APInt::getLowBitsSet(AP.getBitWidth(),
2436 AP.getBitWidth() -
2437 AP.countTrailingZeros()));
2438 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2439 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2440 return new ICmpInst(I.getPredicate(), And1, And2);
2441 }
2442 }
2443 break;
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002444 case Instruction::UDiv:
2445 case Instruction::LShr:
2446 if (I.isSigned())
2447 break;
2448 // fall-through
2449 case Instruction::SDiv:
2450 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002451 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002452 break;
2453 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2454 BO1->getOperand(0));
2455 case Instruction::Shl: {
2456 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2457 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2458 if (!NUW && !NSW)
2459 break;
2460 if (!NSW && I.isSigned())
2461 break;
2462 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2463 BO1->getOperand(0));
2464 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002465 }
2466 }
2467 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002468
Chris Lattner02446fc2010-01-04 07:37:31 +00002469 { Value *A, *B;
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002470 // ~x < ~y --> y < x
2471 // ~x < cst --> ~cst < x
2472 if (match(Op0, m_Not(m_Value(A)))) {
2473 if (match(Op1, m_Not(m_Value(B))))
2474 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner27a98482011-01-15 05:42:47 +00002475 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002476 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2477 }
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002478
2479 // (a+b) <u a --> llvm.uadd.with.overflow.
2480 // (a+b) <u b --> llvm.uadd.with.overflow.
2481 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002482 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002483 (Op1 == A || Op1 == B))
2484 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2485 return R;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002486
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002487 // a >u (a+b) --> llvm.uadd.with.overflow.
2488 // b >u (a+b) --> llvm.uadd.with.overflow.
2489 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2490 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2491 (Op0 == A || Op0 == B))
2492 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2493 return R;
Chris Lattner02446fc2010-01-04 07:37:31 +00002494 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002495
Chris Lattner02446fc2010-01-04 07:37:31 +00002496 if (I.isEquality()) {
2497 Value *A, *B, *C, *D;
Duncan Sands39a7de72011-02-18 16:25:37 +00002498
Chris Lattner02446fc2010-01-04 07:37:31 +00002499 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2500 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
2501 Value *OtherVal = A == Op1 ? B : A;
2502 return new ICmpInst(I.getPredicate(), OtherVal,
2503 Constant::getNullValue(A->getType()));
2504 }
2505
2506 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2507 // A^c1 == C^c2 --> A == C^(c1^c2)
2508 ConstantInt *C1, *C2;
2509 if (match(B, m_ConstantInt(C1)) &&
2510 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2511 Constant *NC = ConstantInt::get(I.getContext(),
2512 C1->getValue() ^ C2->getValue());
Benjamin Kramera9390a42011-09-27 20:39:19 +00002513 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner02446fc2010-01-04 07:37:31 +00002514 return new ICmpInst(I.getPredicate(), A, Xor);
2515 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002516
Chris Lattner02446fc2010-01-04 07:37:31 +00002517 // A^B == A^D -> B == D
2518 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2519 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2520 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2521 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2522 }
2523 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002524
Chris Lattner02446fc2010-01-04 07:37:31 +00002525 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2526 (A == Op0 || B == Op0)) {
2527 // A == (A^B) -> B == 0
2528 Value *OtherVal = A == Op0 ? B : A;
2529 return new ICmpInst(I.getPredicate(), OtherVal,
2530 Constant::getNullValue(A->getType()));
2531 }
2532
Chris Lattner02446fc2010-01-04 07:37:31 +00002533 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002534 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner5036ce42011-04-26 20:02:45 +00002535 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002536 Value *X = 0, *Y = 0, *Z = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002537
Chris Lattner02446fc2010-01-04 07:37:31 +00002538 if (A == C) {
2539 X = B; Y = D; Z = A;
2540 } else if (A == D) {
2541 X = B; Y = C; Z = A;
2542 } else if (B == C) {
2543 X = A; Y = D; Z = B;
2544 } else if (B == D) {
2545 X = A; Y = C; Z = B;
2546 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002547
Chris Lattner02446fc2010-01-04 07:37:31 +00002548 if (X) { // Build (X^Y) & Z
Benjamin Kramera9390a42011-09-27 20:39:19 +00002549 Op1 = Builder->CreateXor(X, Y);
2550 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner02446fc2010-01-04 07:37:31 +00002551 I.setOperand(0, Op1);
2552 I.setOperand(1, Constant::getNullValue(Op1->getType()));
2553 return &I;
2554 }
2555 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002556
Chris Lattner325eeb12011-04-26 20:18:20 +00002557 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2558 // "icmp (and X, mask), cst"
2559 uint64_t ShAmt = 0;
2560 ConstantInt *Cst1;
2561 if (Op0->hasOneUse() &&
2562 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2563 m_ConstantInt(ShAmt))))) &&
2564 match(Op1, m_ConstantInt(Cst1)) &&
2565 // Only do this when A has multiple uses. This is most important to do
2566 // when it exposes other optimizations.
2567 !A->hasOneUse()) {
2568 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002569
Chris Lattner325eeb12011-04-26 20:18:20 +00002570 if (ShAmt < ASize) {
2571 APInt MaskV =
2572 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2573 MaskV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002574
Chris Lattner325eeb12011-04-26 20:18:20 +00002575 APInt CmpV = Cst1->getValue().zext(ASize);
2576 CmpV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002577
Chris Lattner325eeb12011-04-26 20:18:20 +00002578 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2579 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2580 }
2581 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002582 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002583
Chris Lattner02446fc2010-01-04 07:37:31 +00002584 {
2585 Value *X; ConstantInt *Cst;
2586 // icmp X+Cst, X
2587 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
2588 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
2589
2590 // icmp X, X+Cst
2591 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
2592 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
2593 }
2594 return Changed ? &I : 0;
2595}
2596
2597
2598
2599
2600
2601
2602/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2603///
2604Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2605 Instruction *LHSI,
2606 Constant *RHSC) {
2607 if (!isa<ConstantFP>(RHSC)) return 0;
2608 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002609
Chris Lattner02446fc2010-01-04 07:37:31 +00002610 // Get the width of the mantissa. We don't want to hack on conversions that
2611 // might lose information from the integer, e.g. "i64 -> float"
2612 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2613 if (MantissaWidth == -1) return 0; // Unknown.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002614
Chris Lattner02446fc2010-01-04 07:37:31 +00002615 // Check to see that the input is converted from an integer type that is small
2616 // enough that preserves all bits. TODO: check here for "known" sign bits.
2617 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
2618 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002619
Chris Lattner02446fc2010-01-04 07:37:31 +00002620 // If this is a uitofp instruction, we need an extra bit to hold the sign.
2621 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
2622 if (LHSUnsigned)
2623 ++InputSize;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002624
Chris Lattner02446fc2010-01-04 07:37:31 +00002625 // If the conversion would lose info, don't hack on this.
2626 if ((int)InputSize > MantissaWidth)
2627 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002628
Chris Lattner02446fc2010-01-04 07:37:31 +00002629 // Otherwise, we can potentially simplify the comparison. We know that it
2630 // will always come through as an integer value and we know the constant is
2631 // not a NAN (it would have been previously simplified).
2632 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002633
Chris Lattner02446fc2010-01-04 07:37:31 +00002634 ICmpInst::Predicate Pred;
2635 switch (I.getPredicate()) {
2636 default: llvm_unreachable("Unexpected predicate!");
2637 case FCmpInst::FCMP_UEQ:
2638 case FCmpInst::FCMP_OEQ:
2639 Pred = ICmpInst::ICMP_EQ;
2640 break;
2641 case FCmpInst::FCMP_UGT:
2642 case FCmpInst::FCMP_OGT:
2643 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
2644 break;
2645 case FCmpInst::FCMP_UGE:
2646 case FCmpInst::FCMP_OGE:
2647 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
2648 break;
2649 case FCmpInst::FCMP_ULT:
2650 case FCmpInst::FCMP_OLT:
2651 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
2652 break;
2653 case FCmpInst::FCMP_ULE:
2654 case FCmpInst::FCMP_OLE:
2655 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
2656 break;
2657 case FCmpInst::FCMP_UNE:
2658 case FCmpInst::FCMP_ONE:
2659 Pred = ICmpInst::ICMP_NE;
2660 break;
2661 case FCmpInst::FCMP_ORD:
2662 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2663 case FCmpInst::FCMP_UNO:
2664 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2665 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002666
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002667 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002668
Chris Lattner02446fc2010-01-04 07:37:31 +00002669 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002670
Chris Lattner02446fc2010-01-04 07:37:31 +00002671 // See if the FP constant is too large for the integer. For example,
2672 // comparing an i8 to 300.0.
2673 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002674
Chris Lattner02446fc2010-01-04 07:37:31 +00002675 if (!LHSUnsigned) {
2676 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
2677 // and large values.
2678 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
2679 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
2680 APFloat::rmNearestTiesToEven);
2681 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
2682 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
2683 Pred == ICmpInst::ICMP_SLE)
2684 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2685 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2686 }
2687 } else {
2688 // If the RHS value is > UnsignedMax, fold the comparison. This handles
2689 // +INF and large values.
2690 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
2691 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
2692 APFloat::rmNearestTiesToEven);
2693 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
2694 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
2695 Pred == ICmpInst::ICMP_ULE)
2696 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2697 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2698 }
2699 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002700
Chris Lattner02446fc2010-01-04 07:37:31 +00002701 if (!LHSUnsigned) {
2702 // See if the RHS value is < SignedMin.
2703 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2704 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
2705 APFloat::rmNearestTiesToEven);
2706 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
2707 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
2708 Pred == ICmpInst::ICMP_SGE)
2709 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2710 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2711 }
2712 }
2713
2714 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
2715 // [0, UMAX], but it may still be fractional. See if it is fractional by
2716 // casting the FP value to the integer value and back, checking for equality.
2717 // Don't do this for zero, because -0.0 is not fractional.
2718 Constant *RHSInt = LHSUnsigned
2719 ? ConstantExpr::getFPToUI(RHSC, IntTy)
2720 : ConstantExpr::getFPToSI(RHSC, IntTy);
2721 if (!RHS.isZero()) {
2722 bool Equal = LHSUnsigned
2723 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
2724 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
2725 if (!Equal) {
2726 // If we had a comparison against a fractional value, we have to adjust
2727 // the compare predicate and sometimes the value. RHSC is rounded towards
2728 // zero at this point.
2729 switch (Pred) {
2730 default: llvm_unreachable("Unexpected integer comparison!");
2731 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
2732 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2733 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
2734 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2735 case ICmpInst::ICMP_ULE:
2736 // (float)int <= 4.4 --> int <= 4
2737 // (float)int <= -4.4 --> false
2738 if (RHS.isNegative())
2739 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2740 break;
2741 case ICmpInst::ICMP_SLE:
2742 // (float)int <= 4.4 --> int <= 4
2743 // (float)int <= -4.4 --> int < -4
2744 if (RHS.isNegative())
2745 Pred = ICmpInst::ICMP_SLT;
2746 break;
2747 case ICmpInst::ICMP_ULT:
2748 // (float)int < -4.4 --> false
2749 // (float)int < 4.4 --> int <= 4
2750 if (RHS.isNegative())
2751 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2752 Pred = ICmpInst::ICMP_ULE;
2753 break;
2754 case ICmpInst::ICMP_SLT:
2755 // (float)int < -4.4 --> int < -4
2756 // (float)int < 4.4 --> int <= 4
2757 if (!RHS.isNegative())
2758 Pred = ICmpInst::ICMP_SLE;
2759 break;
2760 case ICmpInst::ICMP_UGT:
2761 // (float)int > 4.4 --> int > 4
2762 // (float)int > -4.4 --> true
2763 if (RHS.isNegative())
2764 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2765 break;
2766 case ICmpInst::ICMP_SGT:
2767 // (float)int > 4.4 --> int > 4
2768 // (float)int > -4.4 --> int >= -4
2769 if (RHS.isNegative())
2770 Pred = ICmpInst::ICMP_SGE;
2771 break;
2772 case ICmpInst::ICMP_UGE:
2773 // (float)int >= -4.4 --> true
2774 // (float)int >= 4.4 --> int > 4
2775 if (!RHS.isNegative())
2776 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2777 Pred = ICmpInst::ICMP_UGT;
2778 break;
2779 case ICmpInst::ICMP_SGE:
2780 // (float)int >= -4.4 --> int >= -4
2781 // (float)int >= 4.4 --> int > 4
2782 if (!RHS.isNegative())
2783 Pred = ICmpInst::ICMP_SGT;
2784 break;
2785 }
2786 }
2787 }
2788
2789 // Lower this FP comparison into an appropriate integer version of the
2790 // comparison.
2791 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
2792}
2793
2794Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
2795 bool Changed = false;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002796
Chris Lattner02446fc2010-01-04 07:37:31 +00002797 /// Orders the operands of the compare so that they are listed from most
2798 /// complex to least complex. This puts constants before unary operators,
2799 /// before binary operators.
2800 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
2801 I.swapOperands();
2802 Changed = true;
2803 }
2804
2805 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002806
Chris Lattner02446fc2010-01-04 07:37:31 +00002807 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
2808 return ReplaceInstUsesWith(I, V);
2809
2810 // Simplify 'fcmp pred X, X'
2811 if (Op0 == Op1) {
2812 switch (I.getPredicate()) {
2813 default: llvm_unreachable("Unknown predicate!");
2814 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
2815 case FCmpInst::FCMP_ULT: // True if unordered or less than
2816 case FCmpInst::FCMP_UGT: // True if unordered or greater than
2817 case FCmpInst::FCMP_UNE: // True if unordered or not equal
2818 // Canonicalize these to be 'fcmp uno %X, 0.0'.
2819 I.setPredicate(FCmpInst::FCMP_UNO);
2820 I.setOperand(1, Constant::getNullValue(Op0->getType()));
2821 return &I;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002822
Chris Lattner02446fc2010-01-04 07:37:31 +00002823 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
2824 case FCmpInst::FCMP_OEQ: // True if ordered and equal
2825 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
2826 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
2827 // Canonicalize these to be 'fcmp ord %X, 0.0'.
2828 I.setPredicate(FCmpInst::FCMP_ORD);
2829 I.setOperand(1, Constant::getNullValue(Op0->getType()));
2830 return &I;
2831 }
2832 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002833
Chris Lattner02446fc2010-01-04 07:37:31 +00002834 // Handle fcmp with constant RHS
2835 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2836 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2837 switch (LHSI->getOpcode()) {
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002838 case Instruction::FPExt: {
2839 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
2840 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
2841 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
2842 if (!RHSF)
2843 break;
2844
Benjamin Kramer7ebdc372011-03-31 21:35:49 +00002845 // We can't convert a PPC double double.
2846 if (RHSF->getType()->isPPC_FP128Ty())
2847 break;
2848
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002849 const fltSemantics *Sem;
2850 // FIXME: This shouldn't be here.
2851 if (LHSExt->getSrcTy()->isFloatTy())
2852 Sem = &APFloat::IEEEsingle;
2853 else if (LHSExt->getSrcTy()->isDoubleTy())
2854 Sem = &APFloat::IEEEdouble;
2855 else if (LHSExt->getSrcTy()->isFP128Ty())
2856 Sem = &APFloat::IEEEquad;
2857 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
2858 Sem = &APFloat::x87DoubleExtended;
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002859 else
2860 break;
2861
2862 bool Lossy;
2863 APFloat F = RHSF->getValueAPF();
2864 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
2865
Jim Grosbachcbf676b2011-09-30 18:45:50 +00002866 // Avoid lossy conversions and denormals. Zero is a special case
2867 // that's OK to convert.
Jim Grosbach68e05fb2011-09-30 19:58:46 +00002868 APFloat Fabs = F;
2869 Fabs.clearSign();
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002870 if (!Lossy &&
Jim Grosbach68e05fb2011-09-30 19:58:46 +00002871 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
2872 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbachcbf676b2011-09-30 18:45:50 +00002873
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002874 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
2875 ConstantFP::get(RHSC->getContext(), F));
2876 break;
2877 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002878 case Instruction::PHI:
2879 // Only fold fcmp into the PHI if the phi and fcmp are in the same
2880 // block. If in the same block, we're encouraging jump threading. If
2881 // not, we are just pessimizing the code by making an i1 phi.
2882 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002883 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002884 return NV;
2885 break;
2886 case Instruction::SIToFP:
2887 case Instruction::UIToFP:
2888 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
2889 return NV;
2890 break;
2891 case Instruction::Select: {
2892 // If either operand of the select is a constant, we can fold the
2893 // comparison into the select arms, which will cause one to be
2894 // constant folded and the select turned into a bitwise or.
2895 Value *Op1 = 0, *Op2 = 0;
2896 if (LHSI->hasOneUse()) {
2897 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2898 // Fold the known value into the constant operand.
2899 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2900 // Insert a new FCmp of the other select operand.
2901 Op2 = Builder->CreateFCmp(I.getPredicate(),
2902 LHSI->getOperand(2), RHSC, I.getName());
2903 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2904 // Fold the known value into the constant operand.
2905 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2906 // Insert a new FCmp of the other select operand.
2907 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
2908 RHSC, I.getName());
2909 }
2910 }
2911
2912 if (Op1)
2913 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2914 break;
2915 }
Benjamin Kramer0db50182011-03-31 10:12:15 +00002916 case Instruction::FSub: {
2917 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
2918 Value *Op;
2919 if (match(LHSI, m_FNeg(m_Value(Op))))
2920 return new FCmpInst(I.getSwappedPredicate(), Op,
2921 ConstantExpr::getFNeg(RHSC));
2922 break;
2923 }
Dan Gohman39516a62010-02-24 06:46:09 +00002924 case Instruction::Load:
2925 if (GetElementPtrInst *GEP =
2926 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2927 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2928 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2929 !cast<LoadInst>(LHSI)->isVolatile())
2930 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2931 return Res;
2932 }
2933 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00002934 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002935 }
2936
Benjamin Kramer00e00d62011-03-31 10:46:03 +00002937 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00002938 Value *X, *Y;
2939 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramer00e00d62011-03-31 10:46:03 +00002940 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00002941
Benjamin Kramercd0274c2011-03-31 10:11:58 +00002942 // fcmp (fpext x), (fpext y) -> fcmp x, y
2943 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
2944 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
2945 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
2946 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
2947 RHSExt->getOperand(0));
2948
Chris Lattner02446fc2010-01-04 07:37:31 +00002949 return Changed ? &I : 0;
2950}