blob: 055c3b15147448d46f9187339f80cc98e7042051 [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"
Micah Villmow3574eca2012-10-08 16:38:25 +000019#include "llvm/DataLayout.h"
Benjamin Kramer00abcd32012-08-18 20:06:47 +000020#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner02446fc2010-01-04 07:37:31 +000021#include "llvm/Support/ConstantRange.h"
22#include "llvm/Support/GetElementPtrTypeIterator.h"
23#include "llvm/Support/PatternMatch.h"
24using namespace llvm;
25using namespace PatternMatch;
26
Chris Lattnerb20c0b52011-02-10 05:23:05 +000027static ConstantInt *getOne(Constant *C) {
28 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
29}
30
Chris Lattner02446fc2010-01-04 07:37:31 +000031/// AddOne - Add one to a ConstantInt
32static Constant *AddOne(Constant *C) {
33 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
34}
35/// SubOne - Subtract one from a ConstantInt
Chris Lattnerb20c0b52011-02-10 05:23:05 +000036static Constant *SubOne(Constant *C) {
37 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner02446fc2010-01-04 07:37:31 +000038}
39
40static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
41 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
42}
43
44static bool HasAddOverflow(ConstantInt *Result,
45 ConstantInt *In1, ConstantInt *In2,
46 bool IsSigned) {
Chris Lattnerc73b24d2011-07-15 06:08:15 +000047 if (!IsSigned)
Chris Lattner02446fc2010-01-04 07:37:31 +000048 return Result->getValue().ult(In1->getValue());
Chris Lattnerc73b24d2011-07-15 06:08:15 +000049
50 if (In2->isNegative())
51 return Result->getValue().sgt(In1->getValue());
52 return Result->getValue().slt(In1->getValue());
Chris Lattner02446fc2010-01-04 07:37:31 +000053}
54
55/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
56/// overflowed for this type.
57static bool AddWithOverflow(Constant *&Result, Constant *In1,
58 Constant *In2, bool IsSigned = false) {
59 Result = ConstantExpr::getAdd(In1, In2);
60
Chris Lattnerdb125cf2011-07-18 04:54:35 +000061 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner02446fc2010-01-04 07:37:31 +000062 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
63 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
64 if (HasAddOverflow(ExtractElement(Result, Idx),
65 ExtractElement(In1, Idx),
66 ExtractElement(In2, Idx),
67 IsSigned))
68 return true;
69 }
70 return false;
71 }
72
73 return HasAddOverflow(cast<ConstantInt>(Result),
74 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
75 IsSigned);
76}
77
78static bool HasSubOverflow(ConstantInt *Result,
79 ConstantInt *In1, ConstantInt *In2,
80 bool IsSigned) {
Chris Lattnerc73b24d2011-07-15 06:08:15 +000081 if (!IsSigned)
Chris Lattner02446fc2010-01-04 07:37:31 +000082 return Result->getValue().ugt(In1->getValue());
Jim Grosbach0cc4a952011-09-30 18:09:53 +000083
Chris Lattnerc73b24d2011-07-15 06:08:15 +000084 if (In2->isNegative())
85 return Result->getValue().slt(In1->getValue());
86
87 return Result->getValue().sgt(In1->getValue());
Chris Lattner02446fc2010-01-04 07:37:31 +000088}
89
90/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
91/// overflowed for this type.
92static bool SubWithOverflow(Constant *&Result, Constant *In1,
93 Constant *In2, bool IsSigned = false) {
94 Result = ConstantExpr::getSub(In1, In2);
95
Chris Lattnerdb125cf2011-07-18 04:54:35 +000096 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner02446fc2010-01-04 07:37:31 +000097 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
98 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
99 if (HasSubOverflow(ExtractElement(Result, Idx),
100 ExtractElement(In1, Idx),
101 ExtractElement(In2, Idx),
102 IsSigned))
103 return true;
104 }
105 return false;
106 }
107
108 return HasSubOverflow(cast<ConstantInt>(Result),
109 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
110 IsSigned);
111}
112
113/// isSignBitCheck - Given an exploded icmp instruction, return true if the
114/// comparison only checks the sign bit. If it only checks the sign bit, set
115/// TrueIfSigned if the result of the comparison is true when the input value is
116/// signed.
117static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
118 bool &TrueIfSigned) {
119 switch (pred) {
120 case ICmpInst::ICMP_SLT: // True if LHS s< 0
121 TrueIfSigned = true;
122 return RHS->isZero();
123 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
124 TrueIfSigned = true;
125 return RHS->isAllOnesValue();
126 case ICmpInst::ICMP_SGT: // True if LHS s> -1
127 TrueIfSigned = false;
128 return RHS->isAllOnesValue();
129 case ICmpInst::ICMP_UGT:
130 // True if LHS u> RHS and RHS == high-bit-mask - 1
131 TrueIfSigned = true;
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000132 return RHS->isMaxValue(true);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000133 case ICmpInst::ICMP_UGE:
Chris Lattner02446fc2010-01-04 07:37:31 +0000134 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
135 TrueIfSigned = true;
136 return RHS->getValue().isSignBit();
137 default:
138 return false;
139 }
140}
141
142// isHighOnes - Return true if the constant is of the form 1+0+.
143// This is the same as lowones(~X).
144static bool isHighOnes(const ConstantInt *CI) {
145 return (~CI->getValue() + 1).isPowerOf2();
146}
147
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000148/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
Chris Lattner02446fc2010-01-04 07:37:31 +0000149/// set of known zero and one bits, compute the maximum and minimum values that
150/// could have the specified known zero and known one bits, returning them in
151/// min/max.
152static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
153 const APInt& KnownOne,
154 APInt& Min, APInt& Max) {
155 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
156 KnownZero.getBitWidth() == Min.getBitWidth() &&
157 KnownZero.getBitWidth() == Max.getBitWidth() &&
158 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
159 APInt UnknownBits = ~(KnownZero|KnownOne);
160
161 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
162 // bit if it is unknown.
163 Min = KnownOne;
164 Max = KnownOne|UnknownBits;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000165
Chris Lattner02446fc2010-01-04 07:37:31 +0000166 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad7a874dd2010-12-01 08:53:58 +0000167 Min.setBit(Min.getBitWidth()-1);
168 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner02446fc2010-01-04 07:37:31 +0000169 }
170}
171
172// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
173// a set of known zero and one bits, compute the maximum and minimum values that
174// could have the specified known zero and known one bits, returning them in
175// min/max.
176static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
177 const APInt &KnownOne,
178 APInt &Min, APInt &Max) {
179 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
180 KnownZero.getBitWidth() == Min.getBitWidth() &&
181 KnownZero.getBitWidth() == Max.getBitWidth() &&
182 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
183 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000184
Chris Lattner02446fc2010-01-04 07:37:31 +0000185 // The minimum value is when the unknown bits are all zeros.
186 Min = KnownOne;
187 // The maximum value is when the unknown bits are all ones.
188 Max = KnownOne|UnknownBits;
189}
190
191
192
193/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
194/// cmp pred (load (gep GV, ...)), cmpcst
195/// where GV is a global variable with a constant initializer. Try to simplify
196/// this into some simple computation that does not need the load. For example
197/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
198///
199/// If AndCst is non-null, then the loaded value is masked with that constant
200/// before doing the comparison. This handles cases like "A[i]&4 == 0".
201Instruction *InstCombiner::
202FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
203 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattnerd7f5a582010-01-04 18:57:15 +0000204 // We need TD information to know the pointer size unless this is inbounds.
205 if (!GEP->isInBounds() && TD == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000206
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000207 Constant *Init = GV->getInitializer();
208 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
209 return 0;
210
211 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
212 if (ArrayElementCount > 1024) return 0; // Don't blow up on huge arrays.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000213
Chris Lattner02446fc2010-01-04 07:37:31 +0000214 // There are many forms of this optimization we can handle, for now, just do
215 // the simple index into a single-dimensional array.
216 //
217 // Require: GEP GV, 0, i {{, constant indices}}
218 if (GEP->getNumOperands() < 3 ||
219 !isa<ConstantInt>(GEP->getOperand(1)) ||
220 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
221 isa<Constant>(GEP->getOperand(2)))
222 return 0;
223
224 // Check that indices after the variable are constants and in-range for the
225 // type they index. Collect the indices. This is typically for arrays of
226 // structs.
227 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000228
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000229 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner02446fc2010-01-04 07:37:31 +0000230 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
231 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
232 if (Idx == 0) return 0; // Variable index.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000233
Chris Lattner02446fc2010-01-04 07:37:31 +0000234 uint64_t IdxVal = Idx->getZExtValue();
235 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000236
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000237 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner02446fc2010-01-04 07:37:31 +0000238 EltTy = STy->getElementType(IdxVal);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000239 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000240 if (IdxVal >= ATy->getNumElements()) return 0;
241 EltTy = ATy->getElementType();
242 } else {
243 return 0; // Unknown type.
244 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000245
Chris Lattner02446fc2010-01-04 07:37:31 +0000246 LaterIndices.push_back(IdxVal);
247 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000248
Chris Lattner02446fc2010-01-04 07:37:31 +0000249 enum { Overdefined = -3, Undefined = -2 };
250
251 // Variables for our state machines.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000252
Chris Lattner02446fc2010-01-04 07:37:31 +0000253 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
254 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
255 // and 87 is the second (and last) index. FirstTrueElement is -2 when
256 // undefined, otherwise set to the first true element. SecondTrueElement is
257 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
258 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
259
260 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
261 // form "i != 47 & i != 87". Same state transitions as for true elements.
262 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000263
Chris Lattner02446fc2010-01-04 07:37:31 +0000264 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
265 /// define a state machine that triggers for ranges of values that the index
266 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
267 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
268 /// index in the range (inclusive). We use -2 for undefined here because we
269 /// use relative comparisons and don't want 0-1 to match -1.
270 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000271
Chris Lattner02446fc2010-01-04 07:37:31 +0000272 // MagicBitvector - This is a magic bitvector where we set a bit if the
273 // comparison is true for element 'i'. If there are 64 elements or less in
274 // the array, this will fully represent all the comparison results.
275 uint64_t MagicBitvector = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000276
277
Chris Lattner02446fc2010-01-04 07:37:31 +0000278 // Scan the array and see if one of our patterns matches.
279 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000280 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
281 Constant *Elt = Init->getAggregateElement(i);
282 if (Elt == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000283
Chris Lattner02446fc2010-01-04 07:37:31 +0000284 // If this is indexing an array of structures, get the structure element.
285 if (!LaterIndices.empty())
Jay Foadfc6d3a42011-07-13 10:26:04 +0000286 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000287
Chris Lattner02446fc2010-01-04 07:37:31 +0000288 // If the element is masked, handle it.
289 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000290
Chris Lattner02446fc2010-01-04 07:37:31 +0000291 // Find out if the comparison would be true or false for the i'th element.
292 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Chad Rosieraab8e282011-12-02 01:26:24 +0000293 CompareRHS, TD, TLI);
Chris Lattner02446fc2010-01-04 07:37:31 +0000294 // If the result is undef for this element, ignore it.
295 if (isa<UndefValue>(C)) {
296 // Extend range state machines to cover this element in case there is an
297 // undef in the middle of the range.
298 if (TrueRangeEnd == (int)i-1)
299 TrueRangeEnd = i;
300 if (FalseRangeEnd == (int)i-1)
301 FalseRangeEnd = i;
302 continue;
303 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000304
Chris Lattner02446fc2010-01-04 07:37:31 +0000305 // If we can't compute the result for any of the elements, we have to give
306 // up evaluating the entire conditional.
307 if (!isa<ConstantInt>(C)) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000308
Chris Lattner02446fc2010-01-04 07:37:31 +0000309 // Otherwise, we know if the comparison is true or false for this element,
310 // update our state machines.
311 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000312
Chris Lattner02446fc2010-01-04 07:37:31 +0000313 // State machine for single/double/range index comparison.
314 if (IsTrueForElt) {
315 // Update the TrueElement state machine.
316 if (FirstTrueElement == Undefined)
317 FirstTrueElement = TrueRangeEnd = i; // First true element.
318 else {
319 // Update double-compare state machine.
320 if (SecondTrueElement == Undefined)
321 SecondTrueElement = i;
322 else
323 SecondTrueElement = Overdefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000324
Chris Lattner02446fc2010-01-04 07:37:31 +0000325 // Update range state machine.
326 if (TrueRangeEnd == (int)i-1)
327 TrueRangeEnd = i;
328 else
329 TrueRangeEnd = Overdefined;
330 }
331 } else {
332 // Update the FalseElement state machine.
333 if (FirstFalseElement == Undefined)
334 FirstFalseElement = FalseRangeEnd = i; // First false element.
335 else {
336 // Update double-compare state machine.
337 if (SecondFalseElement == Undefined)
338 SecondFalseElement = i;
339 else
340 SecondFalseElement = Overdefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000341
Chris Lattner02446fc2010-01-04 07:37:31 +0000342 // Update range state machine.
343 if (FalseRangeEnd == (int)i-1)
344 FalseRangeEnd = i;
345 else
346 FalseRangeEnd = Overdefined;
347 }
348 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000349
350
Chris Lattner02446fc2010-01-04 07:37:31 +0000351 // If this element is in range, update our magic bitvector.
352 if (i < 64 && IsTrueForElt)
353 MagicBitvector |= 1ULL << i;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000354
Chris Lattner02446fc2010-01-04 07:37:31 +0000355 // If all of our states become overdefined, bail out early. Since the
356 // predicate is expensive, only check it every 8 elements. This is only
357 // really useful for really huge arrays.
358 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
359 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
360 FalseRangeEnd == Overdefined)
361 return 0;
362 }
363
364 // Now that we've scanned the entire array, emit our new comparison(s). We
365 // order the state machines in complexity of the generated code.
366 Value *Idx = GEP->getOperand(2);
367
Micah Villmow2c39b152012-10-15 16:24:29 +0000368 unsigned AS = GEP->getPointerAddressSpace();
Chris Lattnerd7f5a582010-01-04 18:57:15 +0000369 // If the index is larger than the pointer size of the target, truncate the
370 // index down like the GEP would do implicitly. We don't have to do this for
371 // an inbounds GEP because the index can't be out of range.
372 if (!GEP->isInBounds() &&
Micah Villmow2c39b152012-10-15 16:24:29 +0000373 Idx->getType()->getPrimitiveSizeInBits() > TD->getPointerSizeInBits(AS))
Micah Villmowaa76e9e2012-10-24 15:52:52 +0000374 Idx = Builder->CreateTrunc(Idx, TD->getIntPtrType(Idx->getContext(), AS));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000375
Chris Lattner02446fc2010-01-04 07:37:31 +0000376 // If the comparison is only true for one or two elements, emit direct
377 // comparisons.
378 if (SecondTrueElement != Overdefined) {
379 // None true -> false.
380 if (FirstTrueElement == Undefined)
381 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(GEP->getContext()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000382
Chris Lattner02446fc2010-01-04 07:37:31 +0000383 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000384
Chris Lattner02446fc2010-01-04 07:37:31 +0000385 // True for one element -> 'i == 47'.
386 if (SecondTrueElement == Undefined)
387 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000388
Chris Lattner02446fc2010-01-04 07:37:31 +0000389 // True for two elements -> 'i == 47 | i == 72'.
390 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
391 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
392 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
393 return BinaryOperator::CreateOr(C1, C2);
394 }
395
396 // If the comparison is only false for one or two elements, emit direct
397 // comparisons.
398 if (SecondFalseElement != Overdefined) {
399 // None false -> true.
400 if (FirstFalseElement == Undefined)
401 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(GEP->getContext()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000402
Chris Lattner02446fc2010-01-04 07:37:31 +0000403 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
404
405 // False for one element -> 'i != 47'.
406 if (SecondFalseElement == Undefined)
407 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000408
Chris Lattner02446fc2010-01-04 07:37:31 +0000409 // False for two elements -> 'i != 47 & i != 72'.
410 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
411 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
412 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
413 return BinaryOperator::CreateAnd(C1, C2);
414 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000415
Chris Lattner02446fc2010-01-04 07:37:31 +0000416 // If the comparison can be replaced with a range comparison for the elements
417 // where it is true, emit the range check.
418 if (TrueRangeEnd != Overdefined) {
419 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000420
Chris Lattner02446fc2010-01-04 07:37:31 +0000421 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
422 if (FirstTrueElement) {
423 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
424 Idx = Builder->CreateAdd(Idx, Offs);
425 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000426
Chris Lattner02446fc2010-01-04 07:37:31 +0000427 Value *End = ConstantInt::get(Idx->getType(),
428 TrueRangeEnd-FirstTrueElement+1);
429 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
430 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000431
Chris Lattner02446fc2010-01-04 07:37:31 +0000432 // False range check.
433 if (FalseRangeEnd != Overdefined) {
434 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
435 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
436 if (FirstFalseElement) {
437 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
438 Idx = Builder->CreateAdd(Idx, Offs);
439 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000440
Chris Lattner02446fc2010-01-04 07:37:31 +0000441 Value *End = ConstantInt::get(Idx->getType(),
442 FalseRangeEnd-FirstFalseElement);
443 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
444 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000445
446
Chris Lattner02446fc2010-01-04 07:37:31 +0000447 // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
448 // of this load, replace it with computation that does:
449 // ((magic_cst >> i) & 1) != 0
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000450 if (ArrayElementCount <= 32 ||
451 (TD && ArrayElementCount <= 64 && TD->isLegalInteger(64))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000452 Type *Ty;
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000453 if (ArrayElementCount <= 32)
Chris Lattner02446fc2010-01-04 07:37:31 +0000454 Ty = Type::getInt32Ty(Init->getContext());
455 else
456 Ty = Type::getInt64Ty(Init->getContext());
457 Value *V = Builder->CreateIntCast(Idx, Ty, false);
458 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
459 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
460 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
461 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000462
Chris Lattner02446fc2010-01-04 07:37:31 +0000463 return 0;
464}
465
466
467/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
468/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
469/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
470/// be complex, and scales are involved. The above expression would also be
471/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
472/// This later form is less amenable to optimization though, and we are allowed
473/// to generate the first by knowing that pointer arithmetic doesn't overflow.
474///
475/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000476///
Eli Friedman107ffd52011-05-18 23:11:30 +0000477static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000478 DataLayout &TD = *IC.getDataLayout();
Chris Lattner02446fc2010-01-04 07:37:31 +0000479 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000480
Chris Lattner02446fc2010-01-04 07:37:31 +0000481 // Check to see if this gep only has a single variable index. If so, and if
482 // any constant indices are a multiple of its scale, then we can compute this
483 // in terms of the scale of the variable index. For example, if the GEP
484 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
485 // because the expression will cross zero at the same point.
486 unsigned i, e = GEP->getNumOperands();
487 int64_t Offset = 0;
488 for (i = 1; i != e; ++i, ++GTI) {
489 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
490 // Compute the aggregate offset of constant indices.
491 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000492
Chris Lattner02446fc2010-01-04 07:37:31 +0000493 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000494 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000495 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
496 } else {
497 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
498 Offset += Size*CI->getSExtValue();
499 }
500 } else {
501 // Found our variable index.
502 break;
503 }
504 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000505
Chris Lattner02446fc2010-01-04 07:37:31 +0000506 // If there are no variable indices, we must have a constant offset, just
507 // evaluate it the general way.
508 if (i == e) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000509
Chris Lattner02446fc2010-01-04 07:37:31 +0000510 Value *VariableIdx = GEP->getOperand(i);
511 // Determine the scale factor of the variable element. For example, this is
512 // 4 if the variable index is into an array of i32.
513 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000514
Chris Lattner02446fc2010-01-04 07:37:31 +0000515 // Verify that there are no other variable indices. If so, emit the hard way.
516 for (++i, ++GTI; i != e; ++i, ++GTI) {
517 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
518 if (!CI) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000519
Chris Lattner02446fc2010-01-04 07:37:31 +0000520 // Compute the aggregate offset of constant indices.
521 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000522
Chris Lattner02446fc2010-01-04 07:37:31 +0000523 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000524 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000525 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
526 } else {
527 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
528 Offset += Size*CI->getSExtValue();
529 }
530 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000531
Micah Villmow2c39b152012-10-15 16:24:29 +0000532 unsigned AS = cast<GetElementPtrInst>(GEP)->getPointerAddressSpace();
Chris Lattner02446fc2010-01-04 07:37:31 +0000533 // Okay, we know we have a single variable index, which must be a
534 // pointer/array/vector index. If there is no offset, life is simple, return
535 // the index.
Micah Villmow2c39b152012-10-15 16:24:29 +0000536 unsigned IntPtrWidth = TD.getPointerSizeInBits(AS);
Chris Lattner02446fc2010-01-04 07:37:31 +0000537 if (Offset == 0) {
538 // Cast to intptrty in case a truncation occurs. If an extension is needed,
539 // we don't need to bother extending: the extension won't affect where the
540 // computation crosses zero.
Eli Friedman107ffd52011-05-18 23:11:30 +0000541 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Micah Villmowaa76e9e2012-10-24 15:52:52 +0000542 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext(), AS);
Eli Friedman107ffd52011-05-18 23:11:30 +0000543 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
544 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000545 return VariableIdx;
546 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000547
Chris Lattner02446fc2010-01-04 07:37:31 +0000548 // Otherwise, there is an index. The computation we will do will be modulo
549 // the pointer size, so get it.
550 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000551
Chris Lattner02446fc2010-01-04 07:37:31 +0000552 Offset &= PtrSizeMask;
553 VariableScale &= PtrSizeMask;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000554
Chris Lattner02446fc2010-01-04 07:37:31 +0000555 // To do this transformation, any constant index must be a multiple of the
556 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
557 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
558 // multiple of the variable scale.
559 int64_t NewOffs = Offset / (int64_t)VariableScale;
560 if (Offset != NewOffs*(int64_t)VariableScale)
561 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000562
Chris Lattner02446fc2010-01-04 07:37:31 +0000563 // Okay, we can do this evaluation. Start by converting the index to intptr.
Micah Villmowaa76e9e2012-10-24 15:52:52 +0000564 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext(), AS);
Chris Lattner02446fc2010-01-04 07:37:31 +0000565 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman107ffd52011-05-18 23:11:30 +0000566 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
567 true /*Signed*/);
Chris Lattner02446fc2010-01-04 07:37:31 +0000568 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman107ffd52011-05-18 23:11:30 +0000569 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner02446fc2010-01-04 07:37:31 +0000570}
571
572/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
573/// else. At this point we know that the GEP is on the LHS of the comparison.
574Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
575 ICmpInst::Predicate Cond,
576 Instruction &I) {
Benjamin Kramer8294eb52012-02-21 13:31:09 +0000577 // Don't transform signed compares of GEPs into index compares. Even if the
578 // GEP is inbounds, the final add of the base pointer can have signed overflow
579 // and would change the result of the icmp.
580 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramera42d5c42012-02-21 13:40:06 +0000581 // the maximum signed value for the pointer type.
Benjamin Kramer8294eb52012-02-21 13:31:09 +0000582 if (ICmpInst::isSigned(Cond))
583 return 0;
584
Chris Lattner02446fc2010-01-04 07:37:31 +0000585 // Look through bitcasts.
586 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
587 RHS = BCI->getOperand(0);
588
589 Value *PtrBase = GEPLHS->getOperand(0);
590 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
591 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
592 // This transformation (ignoring the base and scales) is valid because we
593 // know pointers can't overflow since the gep is inbounds. See if we can
594 // output an optimized form.
Eli Friedman107ffd52011-05-18 23:11:30 +0000595 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000596
Chris Lattner02446fc2010-01-04 07:37:31 +0000597 // If not, synthesize the offset the hard way.
598 if (Offset == 0)
599 Offset = EmitGEPOffset(GEPLHS);
600 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
601 Constant::getNullValue(Offset->getType()));
602 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
603 // If the base pointers are different, but the indices are the same, just
604 // compare the base pointer.
605 if (PtrBase != GEPRHS->getOperand(0)) {
606 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
607 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
608 GEPRHS->getOperand(0)->getType();
609 if (IndicesTheSame)
610 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
611 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
612 IndicesTheSame = false;
613 break;
614 }
615
616 // If all indices are the same, just compare the base pointers.
617 if (IndicesTheSame)
618 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
619 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
620
Benjamin Kramer9bb40852012-02-20 15:07:47 +0000621 // If we're comparing GEPs with two base pointers that only differ in type
622 // and both GEPs have only constant indices or just one use, then fold
623 // the compare with the adjusted indices.
Benjamin Kramer6ad48f42012-02-20 18:45:10 +0000624 if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer9bb40852012-02-20 15:07:47 +0000625 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
626 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
627 PtrBase->stripPointerCasts() ==
628 GEPRHS->getOperand(0)->stripPointerCasts()) {
629 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
630 EmitGEPOffset(GEPLHS),
631 EmitGEPOffset(GEPRHS));
632 return ReplaceInstUsesWith(I, Cmp);
633 }
634
Chris Lattner02446fc2010-01-04 07:37:31 +0000635 // Otherwise, the base pointers are different and the indices are
636 // different, bail out.
637 return 0;
638 }
639
640 // If one of the GEPs has all zero indices, recurse.
641 bool AllZeros = true;
642 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
643 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
644 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
645 AllZeros = false;
646 break;
647 }
648 if (AllZeros)
649 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
650 ICmpInst::getSwappedPredicate(Cond), I);
651
652 // If the other GEP has all zero indices, recurse.
653 AllZeros = true;
654 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
655 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
656 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
657 AllZeros = false;
658 break;
659 }
660 if (AllZeros)
661 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
662
Stuart Hastings67f071e2011-05-14 05:55:10 +0000663 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner02446fc2010-01-04 07:37:31 +0000664 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
665 // If the GEPs only differ by one index, compare it.
666 unsigned NumDifferences = 0; // Keep track of # differences.
667 unsigned DiffOperand = 0; // The operand that differs.
668 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
669 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
670 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
671 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
672 // Irreconcilable differences.
673 NumDifferences = 2;
674 break;
675 } else {
676 if (NumDifferences++) break;
677 DiffOperand = i;
678 }
679 }
680
681 if (NumDifferences == 0) // SAME GEP?
682 return ReplaceInstUsesWith(I, // No comparison is needed here.
683 ConstantInt::get(Type::getInt1Ty(I.getContext()),
684 ICmpInst::isTrueWhenEqual(Cond)));
685
Stuart Hastings67f071e2011-05-14 05:55:10 +0000686 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000687 Value *LHSV = GEPLHS->getOperand(DiffOperand);
688 Value *RHSV = GEPRHS->getOperand(DiffOperand);
689 // Make sure we do a signed comparison here.
690 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
691 }
692 }
693
694 // Only lower this if the icmp is the only user of the GEP or if we expect
695 // the result to fold to a constant!
696 if (TD &&
Stuart Hastings67f071e2011-05-14 05:55:10 +0000697 GEPsInBounds &&
Chris Lattner02446fc2010-01-04 07:37:31 +0000698 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
699 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
700 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
701 Value *L = EmitGEPOffset(GEPLHS);
702 Value *R = EmitGEPOffset(GEPRHS);
703 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
704 }
705 }
706 return 0;
707}
708
709/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
710Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
711 Value *X, ConstantInt *CI,
712 ICmpInst::Predicate Pred,
713 Value *TheAdd) {
714 // If we have X+0, exit early (simplifying logic below) and let it get folded
715 // elsewhere. icmp X+0, X -> icmp X, X
716 if (CI->isZero()) {
717 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
718 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
719 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000720
Chris Lattner02446fc2010-01-04 07:37:31 +0000721 // (X+4) == X -> false.
722 if (Pred == ICmpInst::ICMP_EQ)
723 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
724
725 // (X+4) != X -> true.
726 if (Pred == ICmpInst::ICMP_NE)
727 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
728
Chris Lattner02446fc2010-01-04 07:37:31 +0000729 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000730 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner02446fc2010-01-04 07:37:31 +0000731 // operators.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000732
Chris Lattner9aa1e242010-01-08 17:48:19 +0000733 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner02446fc2010-01-04 07:37:31 +0000734 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
735 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
736 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000737 Value *R =
Chris Lattner9aa1e242010-01-08 17:48:19 +0000738 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner02446fc2010-01-04 07:37:31 +0000739 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
740 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000741
Chris Lattner02446fc2010-01-04 07:37:31 +0000742 // (X+1) >u X --> X <u (0-1) --> X != 255
743 // (X+2) >u X --> X <u (0-2) --> X <u 254
744 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandsa7724332011-02-17 07:46:37 +0000745 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000746 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000747
Chris Lattner02446fc2010-01-04 07:37:31 +0000748 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
749 ConstantInt *SMax = ConstantInt::get(X->getContext(),
750 APInt::getSignedMaxValue(BitWidth));
751
752 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
753 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
754 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
755 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
756 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
757 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandsa7724332011-02-17 07:46:37 +0000758 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000759 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000760
Chris Lattner02446fc2010-01-04 07:37:31 +0000761 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
762 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
763 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
764 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
765 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
766 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000767
Chris Lattner02446fc2010-01-04 07:37:31 +0000768 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
769 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
770 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
771}
772
773/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
774/// and CmpRHS are both known to be integer constants.
775Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
776 ConstantInt *DivRHS) {
777 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
778 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000779
780 // FIXME: If the operand types don't match the type of the divide
Chris Lattner02446fc2010-01-04 07:37:31 +0000781 // then don't attempt this transform. The code below doesn't have the
782 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000783 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner02446fc2010-01-04 07:37:31 +0000784 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000785 // (x /u C1) <u C2. Simply casting the operands and result won't
786 // work. :( The if statement below tests that condition and bails
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000787 // if it finds it.
Chris Lattner02446fc2010-01-04 07:37:31 +0000788 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
789 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
790 return 0;
791 if (DivRHS->isZero())
792 return 0; // The ProdOV computation fails on divide by zero.
793 if (DivIsSigned && DivRHS->isAllOnesValue())
794 return 0; // The overflow computation also screws up here
Chris Lattnerbb75d332011-02-13 08:07:21 +0000795 if (DivRHS->isOne()) {
796 // This eliminates some funny cases with INT_MIN.
797 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
798 return &ICI;
799 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000800
801 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000802 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
803 // C2 (CI). By solving for X we can turn this into a range check
804 // instead of computing a divide.
Chris Lattner02446fc2010-01-04 07:37:31 +0000805 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
806
807 // Determine if the product overflows by seeing if the product is
808 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000809 // as in the LHS instruction that we're folding.
Chris Lattner02446fc2010-01-04 07:37:31 +0000810 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
811 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
812
813 // Get the ICmp opcode
814 ICmpInst::Predicate Pred = ICI.getPredicate();
815
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000816 /// If the division is known to be exact, then there is no remainder from the
817 /// divide, so the covered range size is unit, otherwise it is the divisor.
818 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000819
Chris Lattner02446fc2010-01-04 07:37:31 +0000820 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000821 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner02446fc2010-01-04 07:37:31 +0000822 // Compute this interval based on the constants involved and the signedness of
823 // the compare/divide. This computes a half-open interval, keeping track of
824 // whether either value in the interval overflows. After analysis each
825 // overflow variable is set to 0 if it's corresponding bound variable is valid
826 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
827 int LoOverflow = 0, HiOverflow = 0;
828 Constant *LoBound = 0, *HiBound = 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000829
Chris Lattner02446fc2010-01-04 07:37:31 +0000830 if (!DivIsSigned) { // udiv
831 // e.g. X/5 op 3 --> [15, 20)
832 LoBound = Prod;
833 HiOverflow = LoOverflow = ProdOV;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000834 if (!HiOverflow) {
835 // If this is not an exact divide, then many values in the range collapse
836 // to the same result value.
837 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
838 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000839
Chris Lattner02446fc2010-01-04 07:37:31 +0000840 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
841 if (CmpRHSV == 0) { // (X / pos) op 0
842 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000843 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
844 HiBound = RangeSize;
Chris Lattner02446fc2010-01-04 07:37:31 +0000845 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
846 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
847 HiOverflow = LoOverflow = ProdOV;
848 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000849 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000850 } else { // (X / pos) op neg
851 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
852 HiBound = AddOne(Prod);
853 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
854 if (!LoOverflow) {
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000855 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000856 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000857 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000858 }
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000859 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000860 if (DivI->isExact())
861 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000862 if (CmpRHSV == 0) { // (X / neg) op 0
863 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000864 LoBound = AddOne(RangeSize);
865 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000866 if (HiBound == DivRHS) { // -INTMIN = INTMIN
867 HiOverflow = 1; // [INTMIN+1, overflow)
868 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
869 }
870 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
871 // e.g. X/-5 op 3 --> [-19, -14)
872 HiBound = AddOne(Prod);
873 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
874 if (!LoOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000875 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner02446fc2010-01-04 07:37:31 +0000876 } else { // (X / neg) op neg
877 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
878 LoOverflow = HiOverflow = ProdOV;
879 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000880 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000881 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000882
Chris Lattner02446fc2010-01-04 07:37:31 +0000883 // Dividing by a negative swaps the condition. LT <-> GT
884 Pred = ICmpInst::getSwappedPredicate(Pred);
885 }
886
887 Value *X = DivI->getOperand(0);
888 switch (Pred) {
889 default: llvm_unreachable("Unhandled icmp opcode!");
890 case ICmpInst::ICMP_EQ:
891 if (LoOverflow && HiOverflow)
892 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000893 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000894 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
895 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000896 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000897 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
898 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000899 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
900 DivIsSigned, true));
Chris Lattner02446fc2010-01-04 07:37:31 +0000901 case ICmpInst::ICMP_NE:
902 if (LoOverflow && HiOverflow)
903 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000904 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000905 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
906 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000907 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000908 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
909 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000910 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
911 DivIsSigned, false));
Chris Lattner02446fc2010-01-04 07:37:31 +0000912 case ICmpInst::ICMP_ULT:
913 case ICmpInst::ICMP_SLT:
914 if (LoOverflow == +1) // Low bound is greater than input range.
915 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
916 if (LoOverflow == -1) // Low bound is less than input range.
917 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
918 return new ICmpInst(Pred, X, LoBound);
919 case ICmpInst::ICMP_UGT:
920 case ICmpInst::ICMP_SGT:
921 if (HiOverflow == +1) // High bound greater than input range.
922 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000923 if (HiOverflow == -1) // High bound less than input range.
Chris Lattner02446fc2010-01-04 07:37:31 +0000924 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
925 if (Pred == ICmpInst::ICMP_UGT)
926 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000927 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner02446fc2010-01-04 07:37:31 +0000928 }
929}
930
Chris Lattner74542aa2011-02-13 07:43:07 +0000931/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
932Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
933 ConstantInt *ShAmt) {
Chris Lattner74542aa2011-02-13 07:43:07 +0000934 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000935
Chris Lattner74542aa2011-02-13 07:43:07 +0000936 // Check that the shift amount is in range. If not, don't perform
937 // undefined shifts. When the shift is visited it will be
938 // simplified.
939 uint32_t TypeBits = CmpRHSV.getBitWidth();
940 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnerbb75d332011-02-13 08:07:21 +0000941 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Chris Lattner74542aa2011-02-13 07:43:07 +0000942 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000943
Chris Lattnerbb75d332011-02-13 08:07:21 +0000944 if (!ICI.isEquality()) {
945 // If we have an unsigned comparison and an ashr, we can't simplify this.
946 // Similarly for signed comparisons with lshr.
947 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
948 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000949
Eli Friedmana831a9b2011-05-25 23:26:20 +0000950 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
951 // by a power of 2. Since we already have logic to simplify these,
952 // transform to div and then simplify the resultant comparison.
Chris Lattnerbb75d332011-02-13 08:07:21 +0000953 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedmana831a9b2011-05-25 23:26:20 +0000954 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Chris Lattnerbb75d332011-02-13 08:07:21 +0000955 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000956
Chris Lattnerbb75d332011-02-13 08:07:21 +0000957 // Revisit the shift (to delete it).
958 Worklist.Add(Shr);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000959
Chris Lattnerbb75d332011-02-13 08:07:21 +0000960 Constant *DivCst =
961 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000962
Chris Lattnerbb75d332011-02-13 08:07:21 +0000963 Value *Tmp =
964 Shr->getOpcode() == Instruction::AShr ?
965 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
966 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000967
Chris Lattnerbb75d332011-02-13 08:07:21 +0000968 ICI.setOperand(0, Tmp);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000969
Chris Lattnerbb75d332011-02-13 08:07:21 +0000970 // If the builder folded the binop, just return it.
971 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
972 if (TheDiv == 0)
973 return &ICI;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000974
Chris Lattnerbb75d332011-02-13 08:07:21 +0000975 // Otherwise, fold this div/compare.
976 assert(TheDiv->getOpcode() == Instruction::SDiv ||
977 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000978
Chris Lattnerbb75d332011-02-13 08:07:21 +0000979 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
980 assert(Res && "This div/cst should have folded!");
981 return Res;
982 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000983
984
Chris Lattner74542aa2011-02-13 07:43:07 +0000985 // If we are comparing against bits always shifted out, the
986 // comparison cannot succeed.
987 APInt Comp = CmpRHSV << ShAmtVal;
988 ConstantInt *ShiftedCmpRHS = ConstantInt::get(ICI.getContext(), Comp);
989 if (Shr->getOpcode() == Instruction::LShr)
990 Comp = Comp.lshr(ShAmtVal);
991 else
992 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000993
Chris Lattner74542aa2011-02-13 07:43:07 +0000994 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
995 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
996 Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
997 IsICMP_NE);
998 return ReplaceInstUsesWith(ICI, Cst);
999 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001000
Chris Lattner74542aa2011-02-13 07:43:07 +00001001 // Otherwise, check to see if the bits shifted out are known to be zero.
1002 // If so, we can compare against the unshifted value:
1003 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattnere5116f82011-02-13 18:30:09 +00001004 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattner74542aa2011-02-13 07:43:07 +00001005 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001006
Chris Lattner74542aa2011-02-13 07:43:07 +00001007 if (Shr->hasOneUse()) {
1008 // Otherwise strength reduce the shift into an and.
1009 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1010 Constant *Mask = ConstantInt::get(ICI.getContext(), Val);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001011
Chris Lattner74542aa2011-02-13 07:43:07 +00001012 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1013 Mask, Shr->getName()+".mask");
1014 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1015 }
1016 return 0;
1017}
1018
Chris Lattner02446fc2010-01-04 07:37:31 +00001019
1020/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1021///
1022Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1023 Instruction *LHSI,
1024 ConstantInt *RHS) {
1025 const APInt &RHSV = RHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001026
Chris Lattner02446fc2010-01-04 07:37:31 +00001027 switch (LHSI->getOpcode()) {
1028 case Instruction::Trunc:
1029 if (ICI.isEquality() && LHSI->hasOneUse()) {
1030 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1031 // of the high bits truncated out of x are known.
1032 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1033 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner02446fc2010-01-04 07:37:31 +00001034 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001035 ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001036
Chris Lattner02446fc2010-01-04 07:37:31 +00001037 // If all the high bits are known, we can do this xform.
1038 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1039 // Pull in the high bits from known-ones set.
Jay Foad40f8f622010-12-07 08:25:19 +00001040 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedman5b6dfee2012-05-11 01:32:59 +00001041 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner02446fc2010-01-04 07:37:31 +00001042 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1043 ConstantInt::get(ICI.getContext(), NewRHS));
1044 }
1045 }
1046 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001047
Chris Lattner02446fc2010-01-04 07:37:31 +00001048 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
1049 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1050 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1051 // fold the xor.
1052 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1053 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1054 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001055
Chris Lattner02446fc2010-01-04 07:37:31 +00001056 // If the sign bit of the XorCST is not set, there is no change to
1057 // the operation, just stop using the Xor.
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001058 if (!XorCST->isNegative()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001059 ICI.setOperand(0, CompareVal);
1060 Worklist.Add(LHSI);
1061 return &ICI;
1062 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001063
Chris Lattner02446fc2010-01-04 07:37:31 +00001064 // Was the old condition true if the operand is positive?
1065 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001066
Chris Lattner02446fc2010-01-04 07:37:31 +00001067 // If so, the new one isn't.
1068 isTrueIfPositive ^= true;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001069
Chris Lattner02446fc2010-01-04 07:37:31 +00001070 if (isTrueIfPositive)
1071 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1072 SubOne(RHS));
1073 else
1074 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1075 AddOne(RHS));
1076 }
1077
1078 if (LHSI->hasOneUse()) {
1079 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1080 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
1081 const APInt &SignBit = XorCST->getValue();
1082 ICmpInst::Predicate Pred = ICI.isSigned()
1083 ? ICI.getUnsignedPredicate()
1084 : ICI.getSignedPredicate();
1085 return new ICmpInst(Pred, LHSI->getOperand(0),
1086 ConstantInt::get(ICI.getContext(),
1087 RHSV ^ SignBit));
1088 }
1089
1090 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001091 if (!ICI.isEquality() && XorCST->isMaxValue(true)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001092 const APInt &NotSignBit = XorCST->getValue();
1093 ICmpInst::Predicate Pred = ICI.isSigned()
1094 ? ICI.getUnsignedPredicate()
1095 : ICI.getSignedPredicate();
1096 Pred = ICI.getSwappedPredicate(Pred);
1097 return new ICmpInst(Pred, LHSI->getOperand(0),
1098 ConstantInt::get(ICI.getContext(),
1099 RHSV ^ NotSignBit));
1100 }
1101 }
1102 }
1103 break;
1104 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
1105 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1106 LHSI->getOperand(0)->hasOneUse()) {
1107 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001108
Chris Lattner02446fc2010-01-04 07:37:31 +00001109 // If the LHS is an AND of a truncating cast, we can widen the
1110 // and/compare to be the input width without changing the value
1111 // produced, eliminating a cast.
1112 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1113 // We can do this transformation if either the AND constant does not
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001114 // have its sign bit set or if it is an equality comparison.
Chris Lattner02446fc2010-01-04 07:37:31 +00001115 // Extending a relational comparison when we're checking the sign
1116 // bit would not work.
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001117 if (ICI.isEquality() ||
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001118 (!AndCST->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001119 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001120 Builder->CreateAnd(Cast->getOperand(0),
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001121 ConstantExpr::getZExt(AndCST, Cast->getSrcTy()));
1122 NewAnd->takeName(LHSI);
Chris Lattner02446fc2010-01-04 07:37:31 +00001123 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001124 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001125 }
1126 }
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001127
1128 // If the LHS is an AND of a zext, and we have an equality compare, we can
1129 // shrink the and/compare to the smaller type, eliminating the cast.
1130 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001131 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001132 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1133 // should fold the icmp to true/false in that case.
1134 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1135 Value *NewAnd =
1136 Builder->CreateAnd(Cast->getOperand(0),
1137 ConstantExpr::getTrunc(AndCST, Ty));
1138 NewAnd->takeName(LHSI);
1139 return new ICmpInst(ICI.getPredicate(), NewAnd,
1140 ConstantExpr::getTrunc(RHS, Ty));
1141 }
1142 }
1143
Chris Lattner02446fc2010-01-04 07:37:31 +00001144 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1145 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1146 // happens a LOT in code produced by the C front-end, for bitfield
1147 // access.
1148 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1149 if (Shift && !Shift->isShift())
1150 Shift = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001151
Chris Lattner02446fc2010-01-04 07:37:31 +00001152 ConstantInt *ShAmt;
1153 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001154 Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
1155 Type *AndTy = AndCST->getType(); // Type of the and.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001156
Chris Lattner02446fc2010-01-04 07:37:31 +00001157 // We can fold this as long as we can't shift unknown bits
1158 // into the mask. This can only happen with signed shift
1159 // rights, as they sign-extend.
1160 if (ShAmt) {
1161 bool CanFold = Shift->isLogicalShift();
1162 if (!CanFold) {
1163 // To test for the bad case of the signed shr, see if any
1164 // of the bits shifted in could be tested after the mask.
1165 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1166 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001167
Chris Lattner02446fc2010-01-04 07:37:31 +00001168 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001169 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
Chris Lattner02446fc2010-01-04 07:37:31 +00001170 AndCST->getValue()) == 0)
1171 CanFold = true;
1172 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001173
Chris Lattner02446fc2010-01-04 07:37:31 +00001174 if (CanFold) {
1175 Constant *NewCst;
1176 if (Shift->getOpcode() == Instruction::Shl)
1177 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1178 else
1179 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001180
Chris Lattner02446fc2010-01-04 07:37:31 +00001181 // Check to see if we are shifting out any of the bits being
1182 // compared.
1183 if (ConstantExpr::get(Shift->getOpcode(),
1184 NewCst, ShAmt) != RHS) {
1185 // If we shifted bits out, the fold is not going to work out.
1186 // As a special case, check to see if this means that the
1187 // result is always true or false now.
1188 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1189 return ReplaceInstUsesWith(ICI,
1190 ConstantInt::getFalse(ICI.getContext()));
1191 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1192 return ReplaceInstUsesWith(ICI,
1193 ConstantInt::getTrue(ICI.getContext()));
1194 } else {
1195 ICI.setOperand(1, NewCst);
1196 Constant *NewAndCST;
1197 if (Shift->getOpcode() == Instruction::Shl)
1198 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1199 else
1200 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1201 LHSI->setOperand(1, NewAndCST);
1202 LHSI->setOperand(0, Shift->getOperand(0));
1203 Worklist.Add(Shift); // Shift is dead.
1204 return &ICI;
1205 }
1206 }
1207 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001208
Chris Lattner02446fc2010-01-04 07:37:31 +00001209 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1210 // preferable because it allows the C<<Y expression to be hoisted out
1211 // of a loop if Y is invariant and X is not.
1212 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1213 ICI.isEquality() && !Shift->isArithmeticShift() &&
1214 !isa<Constant>(Shift->getOperand(0))) {
1215 // Compute C << Y.
1216 Value *NS;
1217 if (Shift->getOpcode() == Instruction::LShr) {
Benjamin Kramera9390a42011-09-27 20:39:19 +00001218 NS = Builder->CreateShl(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001219 } else {
1220 // Insert a logical shift.
Benjamin Kramera9390a42011-09-27 20:39:19 +00001221 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001222 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001223
Chris Lattner02446fc2010-01-04 07:37:31 +00001224 // Compute X & (C << Y).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001225 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001226 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001227
Chris Lattner02446fc2010-01-04 07:37:31 +00001228 ICI.setOperand(0, NewAnd);
1229 return &ICI;
1230 }
1231 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001232
Chris Lattner02446fc2010-01-04 07:37:31 +00001233 // Try to optimize things like "A[i]&42 == 0" to index computations.
1234 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1235 if (GetElementPtrInst *GEP =
1236 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1237 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1238 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1239 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1240 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1241 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1242 return Res;
1243 }
1244 }
1245 break;
1246
1247 case Instruction::Or: {
1248 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1249 break;
1250 Value *P, *Q;
1251 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1252 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1253 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner02446fc2010-01-04 07:37:31 +00001254 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1255 Constant::getNullValue(P->getType()));
1256 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1257 Constant::getNullValue(Q->getType()));
1258 Instruction *Op;
1259 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1260 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1261 else
1262 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1263 return Op;
1264 }
1265 break;
1266 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001267
Chris Lattner02446fc2010-01-04 07:37:31 +00001268 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
1269 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1270 if (!ShAmt) break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001271
Chris Lattner02446fc2010-01-04 07:37:31 +00001272 uint32_t TypeBits = RHSV.getBitWidth();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001273
Chris Lattner02446fc2010-01-04 07:37:31 +00001274 // Check that the shift amount is in range. If not, don't perform
1275 // undefined shifts. When the shift is visited it will be
1276 // simplified.
1277 if (ShAmt->uge(TypeBits))
1278 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001279
Chris Lattner02446fc2010-01-04 07:37:31 +00001280 if (ICI.isEquality()) {
1281 // If we are comparing against bits always shifted out, the
1282 // comparison cannot succeed.
1283 Constant *Comp =
1284 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1285 ShAmt);
1286 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1287 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1288 Constant *Cst =
1289 ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE);
1290 return ReplaceInstUsesWith(ICI, Cst);
1291 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001292
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001293 // If the shift is NUW, then it is just shifting out zeros, no need for an
1294 // AND.
1295 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1296 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1297 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001298
Chris Lattner02446fc2010-01-04 07:37:31 +00001299 if (LHSI->hasOneUse()) {
1300 // Otherwise strength reduce the shift into an and.
1301 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1302 Constant *Mask =
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001303 ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits,
Chris Lattner02446fc2010-01-04 07:37:31 +00001304 TypeBits-ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001305
Chris Lattner02446fc2010-01-04 07:37:31 +00001306 Value *And =
1307 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1308 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001309 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner02446fc2010-01-04 07:37:31 +00001310 }
1311 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001312
Chris Lattner02446fc2010-01-04 07:37:31 +00001313 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1314 bool TrueIfSigned = false;
1315 if (LHSI->hasOneUse() &&
1316 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1317 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattnerbb75d332011-02-13 08:07:21 +00001318 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001319 APInt::getOneBitSet(TypeBits,
Chris Lattnerbb75d332011-02-13 08:07:21 +00001320 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001321 Value *And =
1322 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1323 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1324 And, Constant::getNullValue(And->getType()));
1325 }
1326 break;
1327 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001328
Chris Lattner02446fc2010-01-04 07:37:31 +00001329 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001330 case Instruction::AShr: {
1331 // Handle equality comparisons of shift-by-constant.
1332 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1333 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1334 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattner74542aa2011-02-13 07:43:07 +00001335 return Res;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001336 }
1337
1338 // Handle exact shr's.
1339 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1340 if (RHSV.isMinValue())
1341 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1342 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001343 break;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001344 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001345
Chris Lattner02446fc2010-01-04 07:37:31 +00001346 case Instruction::SDiv:
1347 case Instruction::UDiv:
1348 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001349 // Fold this div into the comparison, producing a range check.
1350 // Determine, based on the divide type, what the range is being
1351 // checked. If there is an overflow on the low or high side, remember
Chris Lattner02446fc2010-01-04 07:37:31 +00001352 // it, otherwise compute the range [low, hi) bounding the new value.
1353 // See: InsertRangeTest above for the kinds of replacements possible.
1354 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1355 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1356 DivRHS))
1357 return R;
1358 break;
1359
1360 case Instruction::Add:
1361 // Fold: icmp pred (add X, C1), C2
1362 if (!ICI.isEquality()) {
1363 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1364 if (!LHSC) break;
1365 const APInt &LHSV = LHSC->getValue();
1366
1367 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1368 .subtract(LHSV);
1369
1370 if (ICI.isSigned()) {
1371 if (CR.getLower().isSignBit()) {
1372 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1373 ConstantInt::get(ICI.getContext(),CR.getUpper()));
1374 } else if (CR.getUpper().isSignBit()) {
1375 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1376 ConstantInt::get(ICI.getContext(),CR.getLower()));
1377 }
1378 } else {
1379 if (CR.getLower().isMinValue()) {
1380 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1381 ConstantInt::get(ICI.getContext(),CR.getUpper()));
1382 } else if (CR.getUpper().isMinValue()) {
1383 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1384 ConstantInt::get(ICI.getContext(),CR.getLower()));
1385 }
1386 }
1387 }
1388 break;
1389 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001390
Chris Lattner02446fc2010-01-04 07:37:31 +00001391 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1392 if (ICI.isEquality()) {
1393 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001394
1395 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner02446fc2010-01-04 07:37:31 +00001396 // the second operand is a constant, simplify a bit.
1397 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1398 switch (BO->getOpcode()) {
1399 case Instruction::SRem:
1400 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1401 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1402 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohmane0567812010-04-08 23:03:40 +00001403 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001404 Value *NewRem =
1405 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1406 BO->getName());
1407 return new ICmpInst(ICI.getPredicate(), NewRem,
1408 Constant::getNullValue(BO->getType()));
1409 }
1410 }
1411 break;
1412 case Instruction::Add:
1413 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1414 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1415 if (BO->hasOneUse())
1416 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1417 ConstantExpr::getSub(RHS, BOp1C));
1418 } else if (RHSV == 0) {
1419 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1420 // efficiently invertible, or if the add has just this one use.
1421 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001422
Chris Lattner02446fc2010-01-04 07:37:31 +00001423 if (Value *NegVal = dyn_castNegVal(BOp1))
1424 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner5036ce42011-04-26 20:02:45 +00001425 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner02446fc2010-01-04 07:37:31 +00001426 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner5036ce42011-04-26 20:02:45 +00001427 if (BO->hasOneUse()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001428 Value *Neg = Builder->CreateNeg(BOp1);
1429 Neg->takeName(BO);
1430 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1431 }
1432 }
1433 break;
1434 case Instruction::Xor:
1435 // For the xor case, we can xor two constants together, eliminating
1436 // the explicit xor.
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001437 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1438 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner02446fc2010-01-04 07:37:31 +00001439 ConstantExpr::getXor(RHS, BOC));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001440 } else if (RHSV == 0) {
1441 // Replace ((xor A, B) != 0) with (A != B)
Chris Lattner02446fc2010-01-04 07:37:31 +00001442 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1443 BO->getOperand(1));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001444 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001445 break;
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001446 case Instruction::Sub:
1447 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1448 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1449 if (BO->hasOneUse())
1450 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1451 ConstantExpr::getSub(BOp0C, RHS));
1452 } else if (RHSV == 0) {
1453 // Replace ((sub A, B) != 0) with (A != B)
1454 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1455 BO->getOperand(1));
1456 }
1457 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001458 case Instruction::Or:
1459 // If bits are being or'd in that are not present in the constant we
1460 // are comparing against, then the comparison could never succeed!
Eli Friedman618898e2010-07-29 18:03:33 +00001461 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001462 Constant *NotCI = ConstantExpr::getNot(RHS);
1463 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1464 return ReplaceInstUsesWith(ICI,
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001465 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
Chris Lattner02446fc2010-01-04 07:37:31 +00001466 isICMP_NE));
1467 }
1468 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001469
Chris Lattner02446fc2010-01-04 07:37:31 +00001470 case Instruction::And:
1471 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1472 // If bits are being compared against that are and'd out, then the
1473 // comparison can never succeed!
1474 if ((RHSV & ~BOC->getValue()) != 0)
1475 return ReplaceInstUsesWith(ICI,
1476 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1477 isICMP_NE));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001478
Chris Lattner02446fc2010-01-04 07:37:31 +00001479 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1480 if (RHS == BOC && RHSV.isPowerOf2())
1481 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1482 ICmpInst::ICMP_NE, LHSI,
1483 Constant::getNullValue(RHS->getType()));
Benjamin Kramerfc87cdc2011-07-04 20:16:36 +00001484
1485 // Don't perform the following transforms if the AND has multiple uses
1486 if (!BO->hasOneUse())
1487 break;
1488
Chris Lattner02446fc2010-01-04 07:37:31 +00001489 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1490 if (BOC->getValue().isSignBit()) {
1491 Value *X = BO->getOperand(0);
1492 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001493 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001494 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1495 return new ICmpInst(pred, X, Zero);
1496 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001497
Chris Lattner02446fc2010-01-04 07:37:31 +00001498 // ((X & ~7) == 0) --> X < 8
1499 if (RHSV == 0 && isHighOnes(BOC)) {
1500 Value *X = BO->getOperand(0);
1501 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001502 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001503 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1504 return new ICmpInst(pred, X, NegX);
1505 }
1506 }
1507 default: break;
1508 }
1509 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1510 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner03357402010-01-05 18:09:56 +00001511 switch (II->getIntrinsicID()) {
1512 case Intrinsic::bswap:
Chris Lattner02446fc2010-01-04 07:37:31 +00001513 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001514 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00001515 ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
1516 return &ICI;
Chris Lattner03357402010-01-05 18:09:56 +00001517 case Intrinsic::ctlz:
1518 case Intrinsic::cttz:
1519 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1520 if (RHSV == RHS->getType()->getBitWidth()) {
1521 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001522 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001523 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1524 return &ICI;
1525 }
1526 break;
1527 case Intrinsic::ctpop:
1528 // popcount(A) == 0 -> A == 0 and likewise for !=
1529 if (RHS->isZero()) {
1530 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001531 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001532 ICI.setOperand(1, RHS);
1533 return &ICI;
1534 }
1535 break;
1536 default:
Duncan Sands34727662010-07-12 08:16:59 +00001537 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001538 }
1539 }
1540 }
1541 return 0;
1542}
1543
1544/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1545/// We only handle extending casts so far.
1546///
1547Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1548 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1549 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001550 Type *SrcTy = LHSCIOp->getType();
1551 Type *DestTy = LHSCI->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00001552 Value *RHSCIOp;
1553
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001554 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner02446fc2010-01-04 07:37:31 +00001555 // integer type is the same size as the pointer type.
1556 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
Micah Villmowb52fb872012-10-24 18:36:13 +00001557 TD->getTypeSizeInBits(DestTy) ==
Chris Lattner02446fc2010-01-04 07:37:31 +00001558 cast<IntegerType>(DestTy)->getBitWidth()) {
1559 Value *RHSOp = 0;
1560 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1561 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1562 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1563 RHSOp = RHSC->getOperand(0);
1564 // If the pointer types don't match, insert a bitcast.
1565 if (LHSCIOp->getType() != RHSOp->getType())
1566 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1567 }
1568
1569 if (RHSOp)
1570 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1571 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001572
Chris Lattner02446fc2010-01-04 07:37:31 +00001573 // The code below only handles extension cast instructions, so far.
1574 // Enforce this.
1575 if (LHSCI->getOpcode() != Instruction::ZExt &&
1576 LHSCI->getOpcode() != Instruction::SExt)
1577 return 0;
1578
1579 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1580 bool isSignedCmp = ICI.isSigned();
1581
1582 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1583 // Not an extension from the same type?
1584 RHSCIOp = CI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001585 if (RHSCIOp->getType() != LHSCIOp->getType())
Chris Lattner02446fc2010-01-04 07:37:31 +00001586 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001587
Chris Lattner02446fc2010-01-04 07:37:31 +00001588 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1589 // and the other is a zext), then we can't handle this.
1590 if (CI->getOpcode() != LHSCI->getOpcode())
1591 return 0;
1592
1593 // Deal with equality cases early.
1594 if (ICI.isEquality())
1595 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1596
1597 // A signed comparison of sign extended values simplifies into a
1598 // signed comparison.
1599 if (isSignedCmp && isSignedExt)
1600 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1601
1602 // The other three cases all fold into an unsigned comparison.
1603 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1604 }
1605
1606 // If we aren't dealing with a constant on the RHS, exit early
1607 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1608 if (!CI)
1609 return 0;
1610
1611 // Compute the constant that would happen if we truncated to SrcTy then
1612 // reextended to DestTy.
1613 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1614 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1615 Res1, DestTy);
1616
1617 // If the re-extended constant didn't change...
1618 if (Res2 == CI) {
1619 // Deal with equality cases early.
1620 if (ICI.isEquality())
1621 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1622
1623 // A signed comparison of sign extended values simplifies into a
1624 // signed comparison.
1625 if (isSignedExt && isSignedCmp)
1626 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1627
1628 // The other three cases all fold into an unsigned comparison.
1629 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1630 }
1631
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001632 // The re-extended constant changed so the constant cannot be represented
Chris Lattner02446fc2010-01-04 07:37:31 +00001633 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands9d32f602011-01-20 13:21:55 +00001634 // All the cases that fold to true or false will have already been handled
1635 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner02446fc2010-01-04 07:37:31 +00001636
Duncan Sands9d32f602011-01-20 13:21:55 +00001637 if (isSignedCmp || !isSignedExt)
1638 return 0;
Chris Lattner02446fc2010-01-04 07:37:31 +00001639
1640 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1641 // should have been folded away previously and not enter in here.
Duncan Sands9d32f602011-01-20 13:21:55 +00001642
1643 // We're performing an unsigned comp with a sign extended value.
1644 // This is true if the input is >= 0. [aka >s -1]
1645 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1646 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner02446fc2010-01-04 07:37:31 +00001647
1648 // Finally, return the value computed.
Duncan Sands9d32f602011-01-20 13:21:55 +00001649 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner02446fc2010-01-04 07:37:31 +00001650 return ReplaceInstUsesWith(ICI, Result);
1651
Duncan Sands9d32f602011-01-20 13:21:55 +00001652 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner02446fc2010-01-04 07:37:31 +00001653 return BinaryOperator::CreateNot(Result);
1654}
1655
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001656/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1657/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001658/// If this is of the form:
1659/// sum = a + b
1660/// if (sum+128 >u 255)
1661/// Then replace it with llvm.sadd.with.overflow.i8.
1662///
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001663static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1664 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001665 InstCombiner &IC) {
Chris Lattner368397b2010-12-19 17:59:02 +00001666 // The transformation we're trying to do here is to transform this into an
1667 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1668 // with a narrower add, and discard the add-with-constant that is part of the
1669 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001670
Chris Lattner368397b2010-12-19 17:59:02 +00001671 // In order to eliminate the add-with-constant, the compare can be its only
1672 // use.
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001673 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Chris Lattner368397b2010-12-19 17:59:02 +00001674 if (!AddWithCst->hasOneUse()) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001675
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001676 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1677 if (!CI2->getValue().isPowerOf2()) return 0;
1678 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1679 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001680
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001681 // The width of the new add formed is 1 more than the bias.
1682 ++NewWidth;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001683
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001684 // Check to see that CI1 is an all-ones value with NewWidth bits.
1685 if (CI1->getBitWidth() == NewWidth ||
1686 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1687 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001688
Eli Friedman54b92112011-11-28 23:32:19 +00001689 // This is only really a signed overflow check if the inputs have been
1690 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1691 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1692 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1693 if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1694 IC.ComputeNumSignBits(B) < NeededSignBits)
1695 return 0;
1696
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001697 // In order to replace the original add with a narrower
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001698 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1699 // and truncates that discard the high bits of the add. Verify that this is
1700 // the case.
1701 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1702 for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1703 UI != E; ++UI) {
1704 if (*UI == AddWithCst) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001705
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001706 // Only accept truncates for now. We would really like a nice recursive
1707 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1708 // chain to see which bits of a value are actually demanded. If the
1709 // original add had another add which was then immediately truncated, we
1710 // could still do the transformation.
1711 TruncInst *TI = dyn_cast<TruncInst>(*UI);
1712 if (TI == 0 ||
1713 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1714 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001715
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001716 // If the pattern matches, truncate the inputs to the narrower type and
1717 // use the sadd_with_overflow intrinsic to efficiently compute both the
1718 // result and the overflow bit.
Chris Lattner0a624742010-12-19 18:35:09 +00001719 Module *M = I.getParent()->getParent()->getParent();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001720
Jay Foad5fdd6c82011-07-12 14:06:48 +00001721 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Chris Lattner0a624742010-12-19 18:35:09 +00001722 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001723 NewType);
Chris Lattner0a624742010-12-19 18:35:09 +00001724
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001725 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001726
Chris Lattner0a624742010-12-19 18:35:09 +00001727 // Put the new code above the original add, in case there are any uses of the
1728 // add between the add and the compare.
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001729 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001730
Chris Lattner0a624742010-12-19 18:35:09 +00001731 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1732 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1733 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1734 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1735 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001736
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001737 // The inner add was the result of the narrow add, zero extended to the
1738 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001739 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001740
Chris Lattner0a624742010-12-19 18:35:09 +00001741 // The original icmp gets replaced with the overflow value.
1742 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001743}
Chris Lattner02446fc2010-01-04 07:37:31 +00001744
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001745static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1746 InstCombiner &IC) {
1747 // Don't bother doing this transformation for pointers, don't do it for
1748 // vectors.
1749 if (!isa<IntegerType>(OrigAddV->getType())) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001750
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001751 // If the add is a constant expr, then we don't bother transforming it.
1752 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1753 if (OrigAdd == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001754
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001755 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001756
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001757 // Put the new code above the original add, in case there are any uses of the
1758 // add between the add and the compare.
1759 InstCombiner::BuilderTy *Builder = IC.Builder;
1760 Builder->SetInsertPoint(OrigAdd);
1761
1762 Module *M = I.getParent()->getParent()->getParent();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001763 Type *Ty = LHS->getType();
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001764 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001765 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1766 Value *Add = Builder->CreateExtractValue(Call, 0);
1767
1768 IC.ReplaceInstUsesWith(*OrigAdd, Add);
1769
1770 // The original icmp gets replaced with the overflow value.
1771 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
1772}
1773
Owen Andersonda1c1222011-01-11 00:36:45 +00001774// DemandedBitsLHSMask - When performing a comparison against a constant,
1775// it is possible that not all the bits in the LHS are demanded. This helper
1776// method computes the mask that IS demanded.
1777static APInt DemandedBitsLHSMask(ICmpInst &I,
1778 unsigned BitWidth, bool isSignCheck) {
1779 if (isSignCheck)
1780 return APInt::getSignBit(BitWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001781
Owen Andersonda1c1222011-01-11 00:36:45 +00001782 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
1783 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Andersona33b6252011-01-11 18:26:37 +00001784 const APInt &RHS = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001785
Owen Andersonda1c1222011-01-11 00:36:45 +00001786 switch (I.getPredicate()) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001787 // For a UGT comparison, we don't care about any bits that
Owen Andersonda1c1222011-01-11 00:36:45 +00001788 // correspond to the trailing ones of the comparand. The value of these
1789 // bits doesn't impact the outcome of the comparison, because any value
1790 // greater than the RHS must differ in a bit higher than these due to carry.
1791 case ICmpInst::ICMP_UGT: {
1792 unsigned trailingOnes = RHS.countTrailingOnes();
1793 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
1794 return ~lowBitsSet;
1795 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001796
Owen Andersonda1c1222011-01-11 00:36:45 +00001797 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
1798 // Any value less than the RHS must differ in a higher bit because of carries.
1799 case ICmpInst::ICMP_ULT: {
1800 unsigned trailingZeros = RHS.countTrailingZeros();
1801 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
1802 return ~lowBitsSet;
1803 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001804
Owen Andersonda1c1222011-01-11 00:36:45 +00001805 default:
1806 return APInt::getAllOnesValue(BitWidth);
1807 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001808
Owen Andersonda1c1222011-01-11 00:36:45 +00001809}
Chris Lattner02446fc2010-01-04 07:37:31 +00001810
1811Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
1812 bool Changed = false;
Chris Lattner5f670d42010-02-01 19:54:45 +00001813 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001814
Chris Lattner02446fc2010-01-04 07:37:31 +00001815 /// Orders the operands of the compare so that they are listed from most
1816 /// complex to least complex. This puts constants before unary operators,
1817 /// before binary operators.
Chris Lattner5f670d42010-02-01 19:54:45 +00001818 if (getComplexity(Op0) < getComplexity(Op1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001819 I.swapOperands();
Chris Lattner5f670d42010-02-01 19:54:45 +00001820 std::swap(Op0, Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00001821 Changed = true;
1822 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001823
Chris Lattner02446fc2010-01-04 07:37:31 +00001824 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
1825 return ReplaceInstUsesWith(I, V);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001826
Pete Cooper65a6b572011-12-01 03:58:40 +00001827 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooper165695d2011-12-01 19:13:26 +00001828 // ie, abs(val) != 0 -> val != 0
Pete Cooper65a6b572011-12-01 03:58:40 +00001829 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
1830 {
Pete Cooper165695d2011-12-01 19:13:26 +00001831 Value *Cond, *SelectTrue, *SelectFalse;
1832 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooper65a6b572011-12-01 03:58:40 +00001833 m_Value(SelectFalse)))) {
Pete Cooper165695d2011-12-01 19:13:26 +00001834 if (Value *V = dyn_castNegVal(SelectTrue)) {
1835 if (V == SelectFalse)
1836 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
1837 }
1838 else if (Value *V = dyn_castNegVal(SelectFalse)) {
1839 if (V == SelectTrue)
1840 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooper65a6b572011-12-01 03:58:40 +00001841 }
1842 }
1843 }
1844
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001845 Type *Ty = Op0->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00001846
1847 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001848 if (Ty->isIntegerTy(1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001849 switch (I.getPredicate()) {
1850 default: llvm_unreachable("Invalid icmp instruction!");
1851 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
1852 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
1853 return BinaryOperator::CreateNot(Xor);
1854 }
1855 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
1856 return BinaryOperator::CreateXor(Op0, Op1);
1857
1858 case ICmpInst::ICMP_UGT:
1859 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
1860 // FALL THROUGH
1861 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
1862 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1863 return BinaryOperator::CreateAnd(Not, Op1);
1864 }
1865 case ICmpInst::ICMP_SGT:
1866 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
1867 // FALL THROUGH
1868 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
1869 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1870 return BinaryOperator::CreateAnd(Not, Op0);
1871 }
1872 case ICmpInst::ICMP_UGE:
1873 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
1874 // FALL THROUGH
1875 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
1876 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1877 return BinaryOperator::CreateOr(Not, Op1);
1878 }
1879 case ICmpInst::ICMP_SGE:
1880 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
1881 // FALL THROUGH
1882 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
1883 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1884 return BinaryOperator::CreateOr(Not, Op0);
1885 }
1886 }
1887 }
1888
1889 unsigned BitWidth = 0;
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001890 if (Ty->isIntOrIntVectorTy())
Chris Lattner02446fc2010-01-04 07:37:31 +00001891 BitWidth = Ty->getScalarSizeInBits();
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001892 else if (TD) // Pointers require TD info to get their size.
1893 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001894
Chris Lattner02446fc2010-01-04 07:37:31 +00001895 bool isSignBit = false;
1896
1897 // See if we are doing a comparison with a constant.
1898 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1899 Value *A = 0, *B = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001900
Owen Andersone63dda52010-12-17 18:08:00 +00001901 // Match the following pattern, which is a common idiom when writing
1902 // overflow-safe integer arithmetic function. The source performs an
1903 // addition in wider type, and explicitly checks for overflow using
1904 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
1905 // sadd_with_overflow intrinsic.
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001906 //
1907 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001908 // operations if we worked out the formulas to compute the appropriate
Owen Andersone63dda52010-12-17 18:08:00 +00001909 // magic constants.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001910 //
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001911 // sum = a + b
1912 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Andersone63dda52010-12-17 18:08:00 +00001913 {
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001914 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Andersone63dda52010-12-17 18:08:00 +00001915 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001916 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001917 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001918 return Res;
Owen Andersone63dda52010-12-17 18:08:00 +00001919 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001920
Chris Lattner02446fc2010-01-04 07:37:31 +00001921 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
1922 if (I.isEquality() && CI->isZero() &&
1923 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
1924 // (icmp cond A B) if cond is equality
1925 return new ICmpInst(I.getPredicate(), A, B);
1926 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001927
Chris Lattner02446fc2010-01-04 07:37:31 +00001928 // If we have an icmp le or icmp ge instruction, turn it into the
1929 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
1930 // them being folded in the code below. The SimplifyICmpInst code has
1931 // already handled the edge cases for us, so we just assert on them.
1932 switch (I.getPredicate()) {
1933 default: break;
1934 case ICmpInst::ICMP_ULE:
1935 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
1936 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
1937 ConstantInt::get(CI->getContext(), CI->getValue()+1));
1938 case ICmpInst::ICMP_SLE:
1939 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
1940 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
1941 ConstantInt::get(CI->getContext(), CI->getValue()+1));
1942 case ICmpInst::ICMP_UGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001943 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00001944 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
1945 ConstantInt::get(CI->getContext(), CI->getValue()-1));
1946 case ICmpInst::ICMP_SGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001947 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00001948 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
1949 ConstantInt::get(CI->getContext(), CI->getValue()-1));
1950 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001951
Chris Lattner02446fc2010-01-04 07:37:31 +00001952 // If this comparison is a normal comparison, it demands all
1953 // bits, if it is a sign bit comparison, it only demands the sign bit.
1954 bool UnusedBit;
1955 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
1956 }
1957
1958 // See if we can fold the comparison based on range information we can get
1959 // by checking whether bits are known to be zero or one in the input.
1960 if (BitWidth != 0) {
1961 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
1962 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
1963
1964 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersonda1c1222011-01-11 00:36:45 +00001965 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner02446fc2010-01-04 07:37:31 +00001966 Op0KnownZero, Op0KnownOne, 0))
1967 return &I;
1968 if (SimplifyDemandedBits(I.getOperandUse(1),
1969 APInt::getAllOnesValue(BitWidth),
1970 Op1KnownZero, Op1KnownOne, 0))
1971 return &I;
1972
1973 // Given the known and unknown bits, compute a range that the LHS could be
1974 // in. Compute the Min, Max and RHS values based on the known bits. For the
1975 // EQ and NE we use unsigned values.
1976 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
1977 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
1978 if (I.isSigned()) {
1979 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1980 Op0Min, Op0Max);
1981 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1982 Op1Min, Op1Max);
1983 } else {
1984 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1985 Op0Min, Op0Max);
1986 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1987 Op1Min, Op1Max);
1988 }
1989
1990 // If Min and Max are known to be the same, then SimplifyDemandedBits
1991 // figured out that the LHS is a constant. Just constant fold this now so
1992 // that code below can assume that Min != Max.
1993 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
1994 return new ICmpInst(I.getPredicate(),
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00001995 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00001996 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
1997 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00001998 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner02446fc2010-01-04 07:37:31 +00001999
2000 // Based on the range information we know about the LHS, see if we can
Nick Lewyckyd8d15842011-02-28 06:20:05 +00002001 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner02446fc2010-01-04 07:37:31 +00002002 switch (I.getPredicate()) {
2003 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner75d8f592010-11-21 06:44:42 +00002004 case ICmpInst::ICMP_EQ: {
Chris Lattner02446fc2010-01-04 07:37:31 +00002005 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002006 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002007
Chris Lattner75d8f592010-11-21 06:44:42 +00002008 // If all bits are known zero except for one, then we know at most one
2009 // bit is set. If the comparison is against zero, then this is a check
2010 // to see if *that* bit is set.
2011 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2012 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2013 // If the LHS is an AND with the same constant, look through it.
2014 Value *LHS = 0;
2015 ConstantInt *LHSC = 0;
2016 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2017 LHSC->getValue() != Op0KnownZeroInverted)
2018 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002019
Chris Lattner75d8f592010-11-21 06:44:42 +00002020 // 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 +00002021 // then turn "((1 << x)&8) == 0" into "x != 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002022 Value *X = 0;
2023 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2024 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002025 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002026 ConstantInt::get(X->getType(), CmpVal));
2027 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002028
Chris Lattner75d8f592010-11-21 06:44:42 +00002029 // 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 +00002030 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002031 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002032 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002033 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002034 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002035 ConstantInt::get(X->getType(),
2036 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002037 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002038
Chris Lattner02446fc2010-01-04 07:37:31 +00002039 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002040 }
2041 case ICmpInst::ICMP_NE: {
Chris Lattner02446fc2010-01-04 07:37:31 +00002042 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002043 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002044
Chris Lattner75d8f592010-11-21 06:44:42 +00002045 // If all bits are known zero except for one, then we know at most one
2046 // bit is set. If the comparison is against zero, then this is a check
2047 // to see if *that* bit is set.
2048 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2049 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2050 // If the LHS is an AND with the same constant, look through it.
2051 Value *LHS = 0;
2052 ConstantInt *LHSC = 0;
2053 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2054 LHSC->getValue() != Op0KnownZeroInverted)
2055 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002056
Chris Lattner75d8f592010-11-21 06:44:42 +00002057 // 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 +00002058 // then turn "((1 << x)&8) != 0" into "x == 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002059 Value *X = 0;
2060 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2061 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002062 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002063 ConstantInt::get(X->getType(), CmpVal));
2064 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002065
Chris Lattner75d8f592010-11-21 06:44:42 +00002066 // 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 +00002067 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002068 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002069 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002070 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002071 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002072 ConstantInt::get(X->getType(),
2073 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002074 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002075
Chris Lattner02446fc2010-01-04 07:37:31 +00002076 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002077 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002078 case ICmpInst::ICMP_ULT:
2079 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002080 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002081 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002082 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002083 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2084 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2085 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2086 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2087 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2088 ConstantInt::get(CI->getContext(), CI->getValue()-1));
2089
2090 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2091 if (CI->isMinValue(true))
2092 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2093 Constant::getAllOnesValue(Op0->getType()));
2094 }
2095 break;
2096 case ICmpInst::ICMP_UGT:
2097 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002098 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002099 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002100 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002101
2102 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2103 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2104 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2105 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2106 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2107 ConstantInt::get(CI->getContext(), CI->getValue()+1));
2108
2109 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2110 if (CI->isMaxValue(true))
2111 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2112 Constant::getNullValue(Op0->getType()));
2113 }
2114 break;
2115 case ICmpInst::ICMP_SLT:
2116 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002117 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002118 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002119 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002120 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2121 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2122 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2123 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2124 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2125 ConstantInt::get(CI->getContext(), CI->getValue()-1));
2126 }
2127 break;
2128 case ICmpInst::ICMP_SGT:
2129 if (Op0Min.sgt(Op1Max)) // A >s 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.sle(Op1Min)) // A >s 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
2134 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2135 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2136 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2137 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2138 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2139 ConstantInt::get(CI->getContext(), CI->getValue()+1));
2140 }
2141 break;
2142 case ICmpInst::ICMP_SGE:
2143 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2144 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002145 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002146 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002147 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002148 break;
2149 case ICmpInst::ICMP_SLE:
2150 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2151 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002152 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002153 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002154 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002155 break;
2156 case ICmpInst::ICMP_UGE:
2157 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2158 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002159 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002160 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002161 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002162 break;
2163 case ICmpInst::ICMP_ULE:
2164 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2165 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002166 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002167 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002168 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002169 break;
2170 }
2171
2172 // Turn a signed comparison into an unsigned one if both operands
2173 // are known to have the same sign.
2174 if (I.isSigned() &&
2175 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2176 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2177 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2178 }
2179
2180 // Test if the ICmpInst instruction is used exclusively by a select as
2181 // part of a minimum or maximum operation. If so, refrain from doing
2182 // any other folding. This helps out other analyses which understand
2183 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2184 // and CodeGen. And in this case, at least one of the comparison
2185 // operands has at least one user besides the compare (the select),
2186 // which would often largely negate the benefit of folding anyway.
2187 if (I.hasOneUse())
2188 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2189 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2190 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2191 return 0;
2192
2193 // See if we are doing a comparison between a constant and an instruction that
2194 // can be folded into the comparison.
2195 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002196 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2197 // instruction, see if that instruction also has constants so that the
2198 // instruction can be folded into the icmp
Chris Lattner02446fc2010-01-04 07:37:31 +00002199 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2200 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2201 return Res;
2202 }
2203
2204 // Handle icmp with constant (but not simple integer constant) RHS
2205 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2206 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2207 switch (LHSI->getOpcode()) {
2208 case Instruction::GetElementPtr:
2209 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2210 if (RHSC->isNullValue() &&
2211 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2212 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2213 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2214 break;
2215 case Instruction::PHI:
2216 // Only fold icmp into the PHI if the phi and icmp are in the same
2217 // block. If in the same block, we're encouraging jump threading. If
2218 // not, we are just pessimizing the code by making an i1 phi.
2219 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002220 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002221 return NV;
2222 break;
2223 case Instruction::Select: {
2224 // If either operand of the select is a constant, we can fold the
2225 // comparison into the select arms, which will cause one to be
2226 // constant folded and the select turned into a bitwise or.
2227 Value *Op1 = 0, *Op2 = 0;
2228 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2229 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2230 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2231 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2232
2233 // We only want to perform this transformation if it will not lead to
2234 // additional code. This is true if either both sides of the select
2235 // fold to a constant (in which case the icmp is replaced with a select
2236 // which will usually simplify) or this is the only user of the
2237 // select (in which case we are trading a select+icmp for a simpler
2238 // select+icmp).
2239 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2240 if (!Op1)
2241 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2242 RHSC, I.getName());
2243 if (!Op2)
2244 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2245 RHSC, I.getName());
2246 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2247 }
2248 break;
2249 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002250 case Instruction::IntToPtr:
2251 // icmp pred inttoptr(X), null -> icmp pred X, 0
2252 if (RHSC->isNullValue() && TD &&
Micah Villmowaa76e9e2012-10-24 15:52:52 +00002253 TD->getIntPtrType(LHSI->getType()) ==
Chris Lattner02446fc2010-01-04 07:37:31 +00002254 LHSI->getOperand(0)->getType())
2255 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2256 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2257 break;
2258
2259 case Instruction::Load:
2260 // Try to optimize things like "A[i] > 4" to index computations.
2261 if (GetElementPtrInst *GEP =
2262 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2263 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2264 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2265 !cast<LoadInst>(LHSI)->isVolatile())
2266 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2267 return Res;
2268 }
2269 break;
2270 }
2271 }
2272
2273 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2274 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2275 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2276 return NI;
2277 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2278 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2279 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2280 return NI;
2281
2282 // Test to see if the operands of the icmp are casted versions of other
2283 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
2284 // now.
2285 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002286 if (Op0->getType()->isPointerTy() &&
2287 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002288 // We keep moving the cast from the left operand over to the right
2289 // operand, where it can often be eliminated completely.
2290 Op0 = CI->getOperand(0);
2291
2292 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2293 // so eliminate it as well.
2294 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2295 Op1 = CI2->getOperand(0);
2296
2297 // If Op1 is a constant, we can fold the cast into the constant.
2298 if (Op0->getType() != Op1->getType()) {
2299 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2300 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2301 } else {
2302 // Otherwise, cast the RHS right before the icmp
2303 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2304 }
2305 }
2306 return new ICmpInst(I.getPredicate(), Op0, Op1);
2307 }
2308 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002309
Chris Lattner02446fc2010-01-04 07:37:31 +00002310 if (isa<CastInst>(Op0)) {
2311 // Handle the special case of: icmp (cast bool to X), <cst>
2312 // This comes up when you have code like
2313 // int X = A < B;
2314 // if (X) ...
2315 // For generality, we handle any zero-extension of any operand comparison
2316 // with a constant or another cast from the same type.
2317 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2318 if (Instruction *R = visitICmpInstWithCastAndCast(I))
2319 return R;
2320 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002321
Duncan Sandsa7724332011-02-17 07:46:37 +00002322 // Special logic for binary operators.
2323 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2324 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2325 if (BO0 || BO1) {
2326 CmpInst::Predicate Pred = I.getPredicate();
2327 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2328 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2329 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2330 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2331 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2332 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2333 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2334 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2335 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2336
2337 // Analyze the case when either Op0 or Op1 is an add instruction.
2338 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2339 Value *A = 0, *B = 0, *C = 0, *D = 0;
2340 if (BO0 && BO0->getOpcode() == Instruction::Add)
2341 A = BO0->getOperand(0), B = BO0->getOperand(1);
2342 if (BO1 && BO1->getOpcode() == Instruction::Add)
2343 C = BO1->getOperand(0), D = BO1->getOperand(1);
2344
2345 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2346 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2347 return new ICmpInst(Pred, A == Op1 ? B : A,
2348 Constant::getNullValue(Op1->getType()));
2349
2350 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2351 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2352 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2353 C == Op0 ? D : C);
2354
Duncan Sands39a7de72011-02-18 16:25:37 +00002355 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002356 if (A && C && (A == C || A == D || B == C || B == D) &&
2357 NoOp0WrapProblem && NoOp1WrapProblem &&
2358 // Try not to increase register pressure.
2359 BO0->hasOneUse() && BO1->hasOneUse()) {
2360 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2361 Value *Y = (A == C || A == D) ? B : A;
2362 Value *Z = (C == A || C == B) ? D : C;
2363 return new ICmpInst(Pred, Y, Z);
2364 }
2365
2366 // Analyze the case when either Op0 or Op1 is a sub instruction.
2367 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2368 A = 0; B = 0; C = 0; D = 0;
2369 if (BO0 && BO0->getOpcode() == Instruction::Sub)
2370 A = BO0->getOperand(0), B = BO0->getOperand(1);
2371 if (BO1 && BO1->getOpcode() == Instruction::Sub)
2372 C = BO1->getOperand(0), D = BO1->getOperand(1);
2373
Duncan Sands39a7de72011-02-18 16:25:37 +00002374 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2375 if (A == Op1 && NoOp0WrapProblem)
2376 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2377
2378 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2379 if (C == Op0 && NoOp1WrapProblem)
2380 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2381
2382 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002383 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2384 // Try not to increase register pressure.
2385 BO0->hasOneUse() && BO1->hasOneUse())
2386 return new ICmpInst(Pred, A, C);
2387
Duncan Sands39a7de72011-02-18 16:25:37 +00002388 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2389 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2390 // Try not to increase register pressure.
2391 BO0->hasOneUse() && BO1->hasOneUse())
2392 return new ICmpInst(Pred, D, B);
2393
Nick Lewycky9feda172011-03-05 04:28:48 +00002394 BinaryOperator *SRem = NULL;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002395 // icmp (srem X, Y), Y
Nick Lewycky9feda172011-03-05 04:28:48 +00002396 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2397 Op1 == BO0->getOperand(1))
2398 SRem = BO0;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002399 // icmp Y, (srem X, Y)
Nick Lewycky9feda172011-03-05 04:28:48 +00002400 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2401 Op0 == BO1->getOperand(1))
2402 SRem = BO1;
2403 if (SRem) {
2404 // We don't check hasOneUse to avoid increasing register pressure because
2405 // the value we use is the same value this instruction was already using.
2406 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2407 default: break;
2408 case ICmpInst::ICMP_EQ:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002409 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002410 case ICmpInst::ICMP_NE:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002411 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002412 case ICmpInst::ICMP_SGT:
2413 case ICmpInst::ICMP_SGE:
2414 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2415 Constant::getAllOnesValue(SRem->getType()));
2416 case ICmpInst::ICMP_SLT:
2417 case ICmpInst::ICMP_SLE:
2418 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2419 Constant::getNullValue(SRem->getType()));
2420 }
2421 }
2422
Duncan Sandsa7724332011-02-17 07:46:37 +00002423 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2424 BO0->hasOneUse() && BO1->hasOneUse() &&
2425 BO0->getOperand(1) == BO1->getOperand(1)) {
2426 switch (BO0->getOpcode()) {
2427 default: break;
2428 case Instruction::Add:
2429 case Instruction::Sub:
2430 case Instruction::Xor:
2431 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
2432 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2433 BO1->getOperand(0));
2434 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2435 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2436 if (CI->getValue().isSignBit()) {
2437 ICmpInst::Predicate Pred = I.isSigned()
2438 ? I.getUnsignedPredicate()
2439 : I.getSignedPredicate();
2440 return new ICmpInst(Pred, BO0->getOperand(0),
2441 BO1->getOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00002442 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002443
Chris Lattnerc73b24d2011-07-15 06:08:15 +00002444 if (CI->isMaxValue(true)) {
Duncan Sandsa7724332011-02-17 07:46:37 +00002445 ICmpInst::Predicate Pred = I.isSigned()
2446 ? I.getUnsignedPredicate()
2447 : I.getSignedPredicate();
2448 Pred = I.getSwappedPredicate(Pred);
2449 return new ICmpInst(Pred, BO0->getOperand(0),
2450 BO1->getOperand(0));
2451 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002452 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002453 break;
2454 case Instruction::Mul:
2455 if (!I.isEquality())
2456 break;
2457
2458 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2459 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2460 // Mask = -1 >> count-trailing-zeros(Cst).
2461 if (!CI->isZero() && !CI->isOne()) {
2462 const APInt &AP = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002463 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandsa7724332011-02-17 07:46:37 +00002464 APInt::getLowBitsSet(AP.getBitWidth(),
2465 AP.getBitWidth() -
2466 AP.countTrailingZeros()));
2467 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2468 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2469 return new ICmpInst(I.getPredicate(), And1, And2);
2470 }
2471 }
2472 break;
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002473 case Instruction::UDiv:
2474 case Instruction::LShr:
2475 if (I.isSigned())
2476 break;
2477 // fall-through
2478 case Instruction::SDiv:
2479 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002480 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002481 break;
2482 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2483 BO1->getOperand(0));
2484 case Instruction::Shl: {
2485 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2486 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2487 if (!NUW && !NSW)
2488 break;
2489 if (!NSW && I.isSigned())
2490 break;
2491 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2492 BO1->getOperand(0));
2493 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002494 }
2495 }
2496 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002497
Chris Lattner02446fc2010-01-04 07:37:31 +00002498 { Value *A, *B;
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002499 // ~x < ~y --> y < x
2500 // ~x < cst --> ~cst < x
2501 if (match(Op0, m_Not(m_Value(A)))) {
2502 if (match(Op1, m_Not(m_Value(B))))
2503 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner27a98482011-01-15 05:42:47 +00002504 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002505 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2506 }
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002507
2508 // (a+b) <u a --> llvm.uadd.with.overflow.
2509 // (a+b) <u b --> llvm.uadd.with.overflow.
2510 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002511 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002512 (Op1 == A || Op1 == B))
2513 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2514 return R;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002515
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002516 // a >u (a+b) --> llvm.uadd.with.overflow.
2517 // b >u (a+b) --> llvm.uadd.with.overflow.
2518 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2519 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2520 (Op0 == A || Op0 == B))
2521 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2522 return R;
Chris Lattner02446fc2010-01-04 07:37:31 +00002523 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002524
Chris Lattner02446fc2010-01-04 07:37:31 +00002525 if (I.isEquality()) {
2526 Value *A, *B, *C, *D;
Duncan Sands39a7de72011-02-18 16:25:37 +00002527
Chris Lattner02446fc2010-01-04 07:37:31 +00002528 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2529 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
2530 Value *OtherVal = A == Op1 ? B : A;
2531 return new ICmpInst(I.getPredicate(), OtherVal,
2532 Constant::getNullValue(A->getType()));
2533 }
2534
2535 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2536 // A^c1 == C^c2 --> A == C^(c1^c2)
2537 ConstantInt *C1, *C2;
2538 if (match(B, m_ConstantInt(C1)) &&
2539 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2540 Constant *NC = ConstantInt::get(I.getContext(),
2541 C1->getValue() ^ C2->getValue());
Benjamin Kramera9390a42011-09-27 20:39:19 +00002542 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner02446fc2010-01-04 07:37:31 +00002543 return new ICmpInst(I.getPredicate(), A, Xor);
2544 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002545
Chris Lattner02446fc2010-01-04 07:37:31 +00002546 // A^B == A^D -> B == D
2547 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2548 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2549 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2550 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2551 }
2552 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002553
Chris Lattner02446fc2010-01-04 07:37:31 +00002554 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2555 (A == Op0 || B == Op0)) {
2556 // A == (A^B) -> B == 0
2557 Value *OtherVal = A == Op0 ? B : A;
2558 return new ICmpInst(I.getPredicate(), OtherVal,
2559 Constant::getNullValue(A->getType()));
2560 }
2561
Chris Lattner02446fc2010-01-04 07:37:31 +00002562 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002563 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner5036ce42011-04-26 20:02:45 +00002564 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002565 Value *X = 0, *Y = 0, *Z = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002566
Chris Lattner02446fc2010-01-04 07:37:31 +00002567 if (A == C) {
2568 X = B; Y = D; Z = A;
2569 } else if (A == D) {
2570 X = B; Y = C; Z = A;
2571 } else if (B == C) {
2572 X = A; Y = D; Z = B;
2573 } else if (B == D) {
2574 X = A; Y = C; Z = B;
2575 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002576
Chris Lattner02446fc2010-01-04 07:37:31 +00002577 if (X) { // Build (X^Y) & Z
Benjamin Kramera9390a42011-09-27 20:39:19 +00002578 Op1 = Builder->CreateXor(X, Y);
2579 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner02446fc2010-01-04 07:37:31 +00002580 I.setOperand(0, Op1);
2581 I.setOperand(1, Constant::getNullValue(Op1->getType()));
2582 return &I;
2583 }
2584 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002585
Benjamin Kramer66821d92012-06-10 20:35:00 +00002586 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer7a99b462012-06-11 08:01:25 +00002587 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer66821d92012-06-10 20:35:00 +00002588 ConstantInt *Cst1;
Benjamin Kramer7a99b462012-06-11 08:01:25 +00002589 if ((Op0->hasOneUse() &&
2590 match(Op0, m_ZExt(m_Value(A))) &&
2591 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
2592 (Op1->hasOneUse() &&
2593 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
2594 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer66821d92012-06-10 20:35:00 +00002595 APInt Pow2 = Cst1->getValue() + 1;
2596 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
2597 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
2598 return new ICmpInst(I.getPredicate(), A,
2599 Builder->CreateTrunc(B, A->getType()));
2600 }
2601
Chris Lattner325eeb12011-04-26 20:18:20 +00002602 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2603 // "icmp (and X, mask), cst"
2604 uint64_t ShAmt = 0;
Chris Lattner325eeb12011-04-26 20:18:20 +00002605 if (Op0->hasOneUse() &&
2606 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2607 m_ConstantInt(ShAmt))))) &&
2608 match(Op1, m_ConstantInt(Cst1)) &&
2609 // Only do this when A has multiple uses. This is most important to do
2610 // when it exposes other optimizations.
2611 !A->hasOneUse()) {
2612 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002613
Chris Lattner325eeb12011-04-26 20:18:20 +00002614 if (ShAmt < ASize) {
2615 APInt MaskV =
2616 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2617 MaskV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002618
Chris Lattner325eeb12011-04-26 20:18:20 +00002619 APInt CmpV = Cst1->getValue().zext(ASize);
2620 CmpV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002621
Chris Lattner325eeb12011-04-26 20:18:20 +00002622 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2623 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2624 }
2625 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002626 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002627
Chris Lattner02446fc2010-01-04 07:37:31 +00002628 {
2629 Value *X; ConstantInt *Cst;
2630 // icmp X+Cst, X
2631 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
2632 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
2633
2634 // icmp X, X+Cst
2635 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
2636 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
2637 }
2638 return Changed ? &I : 0;
2639}
2640
2641
2642
2643
2644
2645
2646/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2647///
2648Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2649 Instruction *LHSI,
2650 Constant *RHSC) {
2651 if (!isa<ConstantFP>(RHSC)) return 0;
2652 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002653
Chris Lattner02446fc2010-01-04 07:37:31 +00002654 // Get the width of the mantissa. We don't want to hack on conversions that
2655 // might lose information from the integer, e.g. "i64 -> float"
2656 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2657 if (MantissaWidth == -1) return 0; // Unknown.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002658
Chris Lattner02446fc2010-01-04 07:37:31 +00002659 // Check to see that the input is converted from an integer type that is small
2660 // enough that preserves all bits. TODO: check here for "known" sign bits.
2661 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
2662 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002663
Chris Lattner02446fc2010-01-04 07:37:31 +00002664 // If this is a uitofp instruction, we need an extra bit to hold the sign.
2665 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
2666 if (LHSUnsigned)
2667 ++InputSize;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002668
Chris Lattner02446fc2010-01-04 07:37:31 +00002669 // If the conversion would lose info, don't hack on this.
2670 if ((int)InputSize > MantissaWidth)
2671 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002672
Chris Lattner02446fc2010-01-04 07:37:31 +00002673 // Otherwise, we can potentially simplify the comparison. We know that it
2674 // will always come through as an integer value and we know the constant is
2675 // not a NAN (it would have been previously simplified).
2676 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002677
Chris Lattner02446fc2010-01-04 07:37:31 +00002678 ICmpInst::Predicate Pred;
2679 switch (I.getPredicate()) {
2680 default: llvm_unreachable("Unexpected predicate!");
2681 case FCmpInst::FCMP_UEQ:
2682 case FCmpInst::FCMP_OEQ:
2683 Pred = ICmpInst::ICMP_EQ;
2684 break;
2685 case FCmpInst::FCMP_UGT:
2686 case FCmpInst::FCMP_OGT:
2687 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
2688 break;
2689 case FCmpInst::FCMP_UGE:
2690 case FCmpInst::FCMP_OGE:
2691 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
2692 break;
2693 case FCmpInst::FCMP_ULT:
2694 case FCmpInst::FCMP_OLT:
2695 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
2696 break;
2697 case FCmpInst::FCMP_ULE:
2698 case FCmpInst::FCMP_OLE:
2699 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
2700 break;
2701 case FCmpInst::FCMP_UNE:
2702 case FCmpInst::FCMP_ONE:
2703 Pred = ICmpInst::ICMP_NE;
2704 break;
2705 case FCmpInst::FCMP_ORD:
2706 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2707 case FCmpInst::FCMP_UNO:
2708 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2709 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002710
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002711 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002712
Chris Lattner02446fc2010-01-04 07:37:31 +00002713 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002714
Chris Lattner02446fc2010-01-04 07:37:31 +00002715 // See if the FP constant is too large for the integer. For example,
2716 // comparing an i8 to 300.0.
2717 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002718
Chris Lattner02446fc2010-01-04 07:37:31 +00002719 if (!LHSUnsigned) {
2720 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
2721 // and large values.
2722 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
2723 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
2724 APFloat::rmNearestTiesToEven);
2725 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
2726 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
2727 Pred == ICmpInst::ICMP_SLE)
2728 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2729 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2730 }
2731 } else {
2732 // If the RHS value is > UnsignedMax, fold the comparison. This handles
2733 // +INF and large values.
2734 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
2735 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
2736 APFloat::rmNearestTiesToEven);
2737 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
2738 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
2739 Pred == ICmpInst::ICMP_ULE)
2740 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2741 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2742 }
2743 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002744
Chris Lattner02446fc2010-01-04 07:37:31 +00002745 if (!LHSUnsigned) {
2746 // See if the RHS value is < SignedMin.
2747 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2748 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
2749 APFloat::rmNearestTiesToEven);
2750 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
2751 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
2752 Pred == ICmpInst::ICMP_SGE)
2753 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2754 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2755 }
Devang Patela2e0f6b2012-02-13 23:05:18 +00002756 } else {
2757 // See if the RHS value is < UnsignedMin.
2758 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2759 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
2760 APFloat::rmNearestTiesToEven);
2761 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
2762 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
2763 Pred == ICmpInst::ICMP_UGE)
2764 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2765 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2766 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002767 }
2768
2769 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
2770 // [0, UMAX], but it may still be fractional. See if it is fractional by
2771 // casting the FP value to the integer value and back, checking for equality.
2772 // Don't do this for zero, because -0.0 is not fractional.
2773 Constant *RHSInt = LHSUnsigned
2774 ? ConstantExpr::getFPToUI(RHSC, IntTy)
2775 : ConstantExpr::getFPToSI(RHSC, IntTy);
2776 if (!RHS.isZero()) {
2777 bool Equal = LHSUnsigned
2778 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
2779 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
2780 if (!Equal) {
2781 // If we had a comparison against a fractional value, we have to adjust
2782 // the compare predicate and sometimes the value. RHSC is rounded towards
2783 // zero at this point.
2784 switch (Pred) {
2785 default: llvm_unreachable("Unexpected integer comparison!");
2786 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
2787 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2788 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
2789 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2790 case ICmpInst::ICMP_ULE:
2791 // (float)int <= 4.4 --> int <= 4
2792 // (float)int <= -4.4 --> false
2793 if (RHS.isNegative())
2794 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2795 break;
2796 case ICmpInst::ICMP_SLE:
2797 // (float)int <= 4.4 --> int <= 4
2798 // (float)int <= -4.4 --> int < -4
2799 if (RHS.isNegative())
2800 Pred = ICmpInst::ICMP_SLT;
2801 break;
2802 case ICmpInst::ICMP_ULT:
2803 // (float)int < -4.4 --> false
2804 // (float)int < 4.4 --> int <= 4
2805 if (RHS.isNegative())
2806 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2807 Pred = ICmpInst::ICMP_ULE;
2808 break;
2809 case ICmpInst::ICMP_SLT:
2810 // (float)int < -4.4 --> int < -4
2811 // (float)int < 4.4 --> int <= 4
2812 if (!RHS.isNegative())
2813 Pred = ICmpInst::ICMP_SLE;
2814 break;
2815 case ICmpInst::ICMP_UGT:
2816 // (float)int > 4.4 --> int > 4
2817 // (float)int > -4.4 --> true
2818 if (RHS.isNegative())
2819 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2820 break;
2821 case ICmpInst::ICMP_SGT:
2822 // (float)int > 4.4 --> int > 4
2823 // (float)int > -4.4 --> int >= -4
2824 if (RHS.isNegative())
2825 Pred = ICmpInst::ICMP_SGE;
2826 break;
2827 case ICmpInst::ICMP_UGE:
2828 // (float)int >= -4.4 --> true
2829 // (float)int >= 4.4 --> int > 4
Bob Wilsonf12c95a2012-08-07 22:35:16 +00002830 if (RHS.isNegative())
Chris Lattner02446fc2010-01-04 07:37:31 +00002831 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2832 Pred = ICmpInst::ICMP_UGT;
2833 break;
2834 case ICmpInst::ICMP_SGE:
2835 // (float)int >= -4.4 --> int >= -4
2836 // (float)int >= 4.4 --> int > 4
2837 if (!RHS.isNegative())
2838 Pred = ICmpInst::ICMP_SGT;
2839 break;
2840 }
2841 }
2842 }
2843
2844 // Lower this FP comparison into an appropriate integer version of the
2845 // comparison.
2846 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
2847}
2848
2849Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
2850 bool Changed = false;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002851
Chris Lattner02446fc2010-01-04 07:37:31 +00002852 /// Orders the operands of the compare so that they are listed from most
2853 /// complex to least complex. This puts constants before unary operators,
2854 /// before binary operators.
2855 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
2856 I.swapOperands();
2857 Changed = true;
2858 }
2859
2860 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002861
Chris Lattner02446fc2010-01-04 07:37:31 +00002862 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
2863 return ReplaceInstUsesWith(I, V);
2864
2865 // Simplify 'fcmp pred X, X'
2866 if (Op0 == Op1) {
2867 switch (I.getPredicate()) {
2868 default: llvm_unreachable("Unknown predicate!");
2869 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
2870 case FCmpInst::FCMP_ULT: // True if unordered or less than
2871 case FCmpInst::FCMP_UGT: // True if unordered or greater than
2872 case FCmpInst::FCMP_UNE: // True if unordered or not equal
2873 // Canonicalize these to be 'fcmp uno %X, 0.0'.
2874 I.setPredicate(FCmpInst::FCMP_UNO);
2875 I.setOperand(1, Constant::getNullValue(Op0->getType()));
2876 return &I;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002877
Chris Lattner02446fc2010-01-04 07:37:31 +00002878 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
2879 case FCmpInst::FCMP_OEQ: // True if ordered and equal
2880 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
2881 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
2882 // Canonicalize these to be 'fcmp ord %X, 0.0'.
2883 I.setPredicate(FCmpInst::FCMP_ORD);
2884 I.setOperand(1, Constant::getNullValue(Op0->getType()));
2885 return &I;
2886 }
2887 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002888
Chris Lattner02446fc2010-01-04 07:37:31 +00002889 // Handle fcmp with constant RHS
2890 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2891 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2892 switch (LHSI->getOpcode()) {
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002893 case Instruction::FPExt: {
2894 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
2895 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
2896 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
2897 if (!RHSF)
2898 break;
2899
Benjamin Kramer7ebdc372011-03-31 21:35:49 +00002900 // We can't convert a PPC double double.
2901 if (RHSF->getType()->isPPC_FP128Ty())
2902 break;
2903
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002904 const fltSemantics *Sem;
2905 // FIXME: This shouldn't be here.
Dan Gohmance163392011-12-17 00:04:22 +00002906 if (LHSExt->getSrcTy()->isHalfTy())
2907 Sem = &APFloat::IEEEhalf;
2908 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002909 Sem = &APFloat::IEEEsingle;
2910 else if (LHSExt->getSrcTy()->isDoubleTy())
2911 Sem = &APFloat::IEEEdouble;
2912 else if (LHSExt->getSrcTy()->isFP128Ty())
2913 Sem = &APFloat::IEEEquad;
2914 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
2915 Sem = &APFloat::x87DoubleExtended;
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002916 else
2917 break;
2918
2919 bool Lossy;
2920 APFloat F = RHSF->getValueAPF();
2921 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
2922
Jim Grosbachcbf676b2011-09-30 18:45:50 +00002923 // Avoid lossy conversions and denormals. Zero is a special case
2924 // that's OK to convert.
Jim Grosbach68e05fb2011-09-30 19:58:46 +00002925 APFloat Fabs = F;
2926 Fabs.clearSign();
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002927 if (!Lossy &&
Jim Grosbach68e05fb2011-09-30 19:58:46 +00002928 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
2929 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbachcbf676b2011-09-30 18:45:50 +00002930
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002931 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
2932 ConstantFP::get(RHSC->getContext(), F));
2933 break;
2934 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002935 case Instruction::PHI:
2936 // Only fold fcmp into the PHI if the phi and fcmp are in the same
2937 // block. If in the same block, we're encouraging jump threading. If
2938 // not, we are just pessimizing the code by making an i1 phi.
2939 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002940 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002941 return NV;
2942 break;
2943 case Instruction::SIToFP:
2944 case Instruction::UIToFP:
2945 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
2946 return NV;
2947 break;
2948 case Instruction::Select: {
2949 // If either operand of the select is a constant, we can fold the
2950 // comparison into the select arms, which will cause one to be
2951 // constant folded and the select turned into a bitwise or.
2952 Value *Op1 = 0, *Op2 = 0;
2953 if (LHSI->hasOneUse()) {
2954 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2955 // Fold the known value into the constant operand.
2956 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2957 // Insert a new FCmp of the other select operand.
2958 Op2 = Builder->CreateFCmp(I.getPredicate(),
2959 LHSI->getOperand(2), RHSC, I.getName());
2960 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2961 // Fold the known value into the constant operand.
2962 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2963 // Insert a new FCmp of the other select operand.
2964 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
2965 RHSC, I.getName());
2966 }
2967 }
2968
2969 if (Op1)
2970 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2971 break;
2972 }
Benjamin Kramer0db50182011-03-31 10:12:15 +00002973 case Instruction::FSub: {
2974 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
2975 Value *Op;
2976 if (match(LHSI, m_FNeg(m_Value(Op))))
2977 return new FCmpInst(I.getSwappedPredicate(), Op,
2978 ConstantExpr::getFNeg(RHSC));
2979 break;
2980 }
Dan Gohman39516a62010-02-24 06:46:09 +00002981 case Instruction::Load:
2982 if (GetElementPtrInst *GEP =
2983 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2984 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2985 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2986 !cast<LoadInst>(LHSI)->isVolatile())
2987 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2988 return Res;
2989 }
2990 break;
Benjamin Kramer00abcd32012-08-18 20:06:47 +00002991 case Instruction::Call: {
2992 CallInst *CI = cast<CallInst>(LHSI);
2993 LibFunc::Func Func;
2994 // Various optimization for fabs compared with zero.
Benjamin Kramera4b57172012-08-18 22:04:34 +00002995 if (RHSC->isNullValue() && CI->getCalledFunction() &&
Benjamin Kramer00abcd32012-08-18 20:06:47 +00002996 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
2997 TLI->has(Func)) {
2998 if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
2999 Func == LibFunc::fabsl) {
3000 switch (I.getPredicate()) {
3001 default: break;
3002 // fabs(x) < 0 --> false
3003 case FCmpInst::FCMP_OLT:
3004 return ReplaceInstUsesWith(I, Builder->getFalse());
3005 // fabs(x) > 0 --> x != 0
3006 case FCmpInst::FCMP_OGT:
3007 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3008 RHSC);
3009 // fabs(x) <= 0 --> x == 0
3010 case FCmpInst::FCMP_OLE:
3011 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3012 RHSC);
3013 // fabs(x) >= 0 --> !isnan(x)
3014 case FCmpInst::FCMP_OGE:
3015 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3016 RHSC);
3017 // fabs(x) == 0 --> x == 0
3018 // fabs(x) != 0 --> x != 0
3019 case FCmpInst::FCMP_OEQ:
3020 case FCmpInst::FCMP_UEQ:
3021 case FCmpInst::FCMP_ONE:
3022 case FCmpInst::FCMP_UNE:
3023 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3024 RHSC);
3025 }
3026 }
3027 }
3028 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003029 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003030 }
3031
Benjamin Kramer00e00d62011-03-31 10:46:03 +00003032 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00003033 Value *X, *Y;
3034 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramer00e00d62011-03-31 10:46:03 +00003035 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00003036
Benjamin Kramercd0274c2011-03-31 10:11:58 +00003037 // fcmp (fpext x), (fpext y) -> fcmp x, y
3038 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3039 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3040 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3041 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3042 RHSExt->getOperand(0));
3043
Chris Lattner02446fc2010-01-04 07:37:31 +00003044 return Changed ? &I : 0;
3045}