blob: bad46b4dab3accc67a70329f229675f931a17e48 [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"
Eli Friedman74703252011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner02446fc2010-01-04 07:37:31 +000016#include "llvm/Analysis/InstructionSimplify.h"
17#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000018#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/IntrinsicInst.h"
Chris Lattner02446fc2010-01-04 07:37:31 +000020#include "llvm/Support/ConstantRange.h"
21#include "llvm/Support/GetElementPtrTypeIterator.h"
22#include "llvm/Support/PatternMatch.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner02446fc2010-01-04 07:37:31 +000024using 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
Chris Lattnerd7f5a582010-01-04 18:57:15 +0000368 // If the index is larger than the pointer size of the target, truncate the
369 // index down like the GEP would do implicitly. We don't have to do this for
370 // an inbounds GEP because the index can't be out of range.
371 if (!GEP->isInBounds() &&
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000372 Idx->getType()->getPrimitiveSizeInBits() > TD->getPointerSizeInBits())
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000373 Idx = Builder->CreateTrunc(Idx, TD->getIntPtrType(Idx->getContext()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000374
Chris Lattner02446fc2010-01-04 07:37:31 +0000375 // If the comparison is only true for one or two elements, emit direct
376 // comparisons.
377 if (SecondTrueElement != Overdefined) {
378 // None true -> false.
379 if (FirstTrueElement == Undefined)
380 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(GEP->getContext()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000381
Chris Lattner02446fc2010-01-04 07:37:31 +0000382 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000383
Chris Lattner02446fc2010-01-04 07:37:31 +0000384 // True for one element -> 'i == 47'.
385 if (SecondTrueElement == Undefined)
386 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000387
Chris Lattner02446fc2010-01-04 07:37:31 +0000388 // True for two elements -> 'i == 47 | i == 72'.
389 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
390 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
391 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
392 return BinaryOperator::CreateOr(C1, C2);
393 }
394
395 // If the comparison is only false for one or two elements, emit direct
396 // comparisons.
397 if (SecondFalseElement != Overdefined) {
398 // None false -> true.
399 if (FirstFalseElement == Undefined)
400 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(GEP->getContext()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000401
Chris Lattner02446fc2010-01-04 07:37:31 +0000402 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
403
404 // False for one element -> 'i != 47'.
405 if (SecondFalseElement == Undefined)
406 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000407
Chris Lattner02446fc2010-01-04 07:37:31 +0000408 // False for two elements -> 'i != 47 & i != 72'.
409 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
410 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
411 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
412 return BinaryOperator::CreateAnd(C1, C2);
413 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000414
Chris Lattner02446fc2010-01-04 07:37:31 +0000415 // If the comparison can be replaced with a range comparison for the elements
416 // where it is true, emit the range check.
417 if (TrueRangeEnd != Overdefined) {
418 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000419
Chris Lattner02446fc2010-01-04 07:37:31 +0000420 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
421 if (FirstTrueElement) {
422 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
423 Idx = Builder->CreateAdd(Idx, Offs);
424 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000425
Chris Lattner02446fc2010-01-04 07:37:31 +0000426 Value *End = ConstantInt::get(Idx->getType(),
427 TrueRangeEnd-FirstTrueElement+1);
428 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
429 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000430
Chris Lattner02446fc2010-01-04 07:37:31 +0000431 // False range check.
432 if (FalseRangeEnd != Overdefined) {
433 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
434 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
435 if (FirstFalseElement) {
436 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
437 Idx = Builder->CreateAdd(Idx, Offs);
438 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000439
Chris Lattner02446fc2010-01-04 07:37:31 +0000440 Value *End = ConstantInt::get(Idx->getType(),
441 FalseRangeEnd-FirstFalseElement);
442 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
443 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000444
445
Chris Lattner02446fc2010-01-04 07:37:31 +0000446 // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
447 // of this load, replace it with computation that does:
448 // ((magic_cst >> i) & 1) != 0
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000449 if (ArrayElementCount <= 32 ||
450 (TD && ArrayElementCount <= 64 && TD->isLegalInteger(64))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000451 Type *Ty;
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000452 if (ArrayElementCount <= 32)
Chris Lattner02446fc2010-01-04 07:37:31 +0000453 Ty = Type::getInt32Ty(Init->getContext());
454 else
455 Ty = Type::getInt64Ty(Init->getContext());
456 Value *V = Builder->CreateIntCast(Idx, Ty, false);
457 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
458 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
459 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
460 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000461
Chris Lattner02446fc2010-01-04 07:37:31 +0000462 return 0;
463}
464
465
466/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
467/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
468/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
469/// be complex, and scales are involved. The above expression would also be
470/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
471/// This later form is less amenable to optimization though, and we are allowed
472/// to generate the first by knowing that pointer arithmetic doesn't overflow.
473///
474/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000475///
Eli Friedman107ffd52011-05-18 23:11:30 +0000476static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000477 DataLayout &TD = *IC.getDataLayout();
Chris Lattner02446fc2010-01-04 07:37:31 +0000478 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000479
Chris Lattner02446fc2010-01-04 07:37:31 +0000480 // Check to see if this gep only has a single variable index. If so, and if
481 // any constant indices are a multiple of its scale, then we can compute this
482 // in terms of the scale of the variable index. For example, if the GEP
483 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
484 // because the expression will cross zero at the same point.
485 unsigned i, e = GEP->getNumOperands();
486 int64_t Offset = 0;
487 for (i = 1; i != e; ++i, ++GTI) {
488 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
489 // Compute the aggregate offset of constant indices.
490 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000491
Chris Lattner02446fc2010-01-04 07:37:31 +0000492 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000493 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000494 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
495 } else {
496 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
497 Offset += Size*CI->getSExtValue();
498 }
499 } else {
500 // Found our variable index.
501 break;
502 }
503 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000504
Chris Lattner02446fc2010-01-04 07:37:31 +0000505 // If there are no variable indices, we must have a constant offset, just
506 // evaluate it the general way.
507 if (i == e) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000508
Chris Lattner02446fc2010-01-04 07:37:31 +0000509 Value *VariableIdx = GEP->getOperand(i);
510 // Determine the scale factor of the variable element. For example, this is
511 // 4 if the variable index is into an array of i32.
512 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000513
Chris Lattner02446fc2010-01-04 07:37:31 +0000514 // Verify that there are no other variable indices. If so, emit the hard way.
515 for (++i, ++GTI; i != e; ++i, ++GTI) {
516 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
517 if (!CI) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000518
Chris Lattner02446fc2010-01-04 07:37:31 +0000519 // Compute the aggregate offset of constant indices.
520 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000521
Chris Lattner02446fc2010-01-04 07:37:31 +0000522 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000523 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000524 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
525 } else {
526 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
527 Offset += Size*CI->getSExtValue();
528 }
529 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000530
Chris Lattner02446fc2010-01-04 07:37:31 +0000531 // Okay, we know we have a single variable index, which must be a
532 // pointer/array/vector index. If there is no offset, life is simple, return
533 // the index.
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000534 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattner02446fc2010-01-04 07:37:31 +0000535 if (Offset == 0) {
536 // Cast to intptrty in case a truncation occurs. If an extension is needed,
537 // we don't need to bother extending: the extension won't affect where the
538 // computation crosses zero.
Eli Friedman107ffd52011-05-18 23:11:30 +0000539 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000540 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Eli Friedman107ffd52011-05-18 23:11:30 +0000541 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
542 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000543 return VariableIdx;
544 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000545
Chris Lattner02446fc2010-01-04 07:37:31 +0000546 // Otherwise, there is an index. The computation we will do will be modulo
547 // the pointer size, so get it.
548 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000549
Chris Lattner02446fc2010-01-04 07:37:31 +0000550 Offset &= PtrSizeMask;
551 VariableScale &= PtrSizeMask;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000552
Chris Lattner02446fc2010-01-04 07:37:31 +0000553 // To do this transformation, any constant index must be a multiple of the
554 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
555 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
556 // multiple of the variable scale.
557 int64_t NewOffs = Offset / (int64_t)VariableScale;
558 if (Offset != NewOffs*(int64_t)VariableScale)
559 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000560
Chris Lattner02446fc2010-01-04 07:37:31 +0000561 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000562 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner02446fc2010-01-04 07:37:31 +0000563 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman107ffd52011-05-18 23:11:30 +0000564 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
565 true /*Signed*/);
Chris Lattner02446fc2010-01-04 07:37:31 +0000566 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman107ffd52011-05-18 23:11:30 +0000567 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner02446fc2010-01-04 07:37:31 +0000568}
569
570/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
571/// else. At this point we know that the GEP is on the LHS of the comparison.
572Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
573 ICmpInst::Predicate Cond,
574 Instruction &I) {
Benjamin Kramer8294eb52012-02-21 13:31:09 +0000575 // Don't transform signed compares of GEPs into index compares. Even if the
576 // GEP is inbounds, the final add of the base pointer can have signed overflow
577 // and would change the result of the icmp.
578 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramera42d5c42012-02-21 13:40:06 +0000579 // the maximum signed value for the pointer type.
Benjamin Kramer8294eb52012-02-21 13:31:09 +0000580 if (ICmpInst::isSigned(Cond))
581 return 0;
582
Chris Lattner02446fc2010-01-04 07:37:31 +0000583 // Look through bitcasts.
584 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
585 RHS = BCI->getOperand(0);
586
587 Value *PtrBase = GEPLHS->getOperand(0);
588 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
589 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
590 // This transformation (ignoring the base and scales) is valid because we
591 // know pointers can't overflow since the gep is inbounds. See if we can
592 // output an optimized form.
Eli Friedman107ffd52011-05-18 23:11:30 +0000593 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000594
Chris Lattner02446fc2010-01-04 07:37:31 +0000595 // If not, synthesize the offset the hard way.
596 if (Offset == 0)
597 Offset = EmitGEPOffset(GEPLHS);
598 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
599 Constant::getNullValue(Offset->getType()));
600 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
601 // If the base pointers are different, but the indices are the same, just
602 // compare the base pointer.
603 if (PtrBase != GEPRHS->getOperand(0)) {
604 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
605 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
606 GEPRHS->getOperand(0)->getType();
607 if (IndicesTheSame)
608 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
609 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
610 IndicesTheSame = false;
611 break;
612 }
613
614 // If all indices are the same, just compare the base pointers.
615 if (IndicesTheSame)
616 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
617 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
618
Benjamin Kramer9bb40852012-02-20 15:07:47 +0000619 // If we're comparing GEPs with two base pointers that only differ in type
620 // and both GEPs have only constant indices or just one use, then fold
621 // the compare with the adjusted indices.
Benjamin Kramer6ad48f42012-02-20 18:45:10 +0000622 if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer9bb40852012-02-20 15:07:47 +0000623 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
624 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
625 PtrBase->stripPointerCasts() ==
626 GEPRHS->getOperand(0)->stripPointerCasts()) {
627 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
628 EmitGEPOffset(GEPLHS),
629 EmitGEPOffset(GEPRHS));
630 return ReplaceInstUsesWith(I, Cmp);
631 }
632
Chris Lattner02446fc2010-01-04 07:37:31 +0000633 // Otherwise, the base pointers are different and the indices are
634 // different, bail out.
635 return 0;
636 }
637
638 // If one of the GEPs has all zero indices, recurse.
639 bool AllZeros = true;
640 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
641 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
642 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
643 AllZeros = false;
644 break;
645 }
646 if (AllZeros)
647 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
648 ICmpInst::getSwappedPredicate(Cond), I);
649
650 // If the other GEP has all zero indices, recurse.
651 AllZeros = true;
652 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
653 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
654 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
655 AllZeros = false;
656 break;
657 }
658 if (AllZeros)
659 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
660
Stuart Hastings67f071e2011-05-14 05:55:10 +0000661 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner02446fc2010-01-04 07:37:31 +0000662 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
663 // If the GEPs only differ by one index, compare it.
664 unsigned NumDifferences = 0; // Keep track of # differences.
665 unsigned DiffOperand = 0; // The operand that differs.
666 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
667 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
668 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
669 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
670 // Irreconcilable differences.
671 NumDifferences = 2;
672 break;
673 } else {
674 if (NumDifferences++) break;
675 DiffOperand = i;
676 }
677 }
678
679 if (NumDifferences == 0) // SAME GEP?
680 return ReplaceInstUsesWith(I, // No comparison is needed here.
681 ConstantInt::get(Type::getInt1Ty(I.getContext()),
682 ICmpInst::isTrueWhenEqual(Cond)));
683
Stuart Hastings67f071e2011-05-14 05:55:10 +0000684 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000685 Value *LHSV = GEPLHS->getOperand(DiffOperand);
686 Value *RHSV = GEPRHS->getOperand(DiffOperand);
687 // Make sure we do a signed comparison here.
688 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
689 }
690 }
691
692 // Only lower this if the icmp is the only user of the GEP or if we expect
693 // the result to fold to a constant!
694 if (TD &&
Stuart Hastings67f071e2011-05-14 05:55:10 +0000695 GEPsInBounds &&
Chris Lattner02446fc2010-01-04 07:37:31 +0000696 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
697 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
698 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
699 Value *L = EmitGEPOffset(GEPLHS);
700 Value *R = EmitGEPOffset(GEPRHS);
701 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
702 }
703 }
704 return 0;
705}
706
707/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
708Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
709 Value *X, ConstantInt *CI,
710 ICmpInst::Predicate Pred,
711 Value *TheAdd) {
712 // If we have X+0, exit early (simplifying logic below) and let it get folded
713 // elsewhere. icmp X+0, X -> icmp X, X
714 if (CI->isZero()) {
715 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
716 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
717 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000718
Chris Lattner02446fc2010-01-04 07:37:31 +0000719 // (X+4) == X -> false.
720 if (Pred == ICmpInst::ICMP_EQ)
721 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
722
723 // (X+4) != X -> true.
724 if (Pred == ICmpInst::ICMP_NE)
725 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
726
Chris Lattner02446fc2010-01-04 07:37:31 +0000727 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000728 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner02446fc2010-01-04 07:37:31 +0000729 // operators.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000730
Chris Lattner9aa1e242010-01-08 17:48:19 +0000731 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner02446fc2010-01-04 07:37:31 +0000732 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
733 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
734 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000735 Value *R =
Chris Lattner9aa1e242010-01-08 17:48:19 +0000736 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner02446fc2010-01-04 07:37:31 +0000737 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
738 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000739
Chris Lattner02446fc2010-01-04 07:37:31 +0000740 // (X+1) >u X --> X <u (0-1) --> X != 255
741 // (X+2) >u X --> X <u (0-2) --> X <u 254
742 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandsa7724332011-02-17 07:46:37 +0000743 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000744 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000745
Chris Lattner02446fc2010-01-04 07:37:31 +0000746 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
747 ConstantInt *SMax = ConstantInt::get(X->getContext(),
748 APInt::getSignedMaxValue(BitWidth));
749
750 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
751 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
752 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
753 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
754 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
755 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandsa7724332011-02-17 07:46:37 +0000756 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000757 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000758
Chris Lattner02446fc2010-01-04 07:37:31 +0000759 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
760 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
761 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
762 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
763 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
764 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000765
Chris Lattner02446fc2010-01-04 07:37:31 +0000766 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
767 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
768 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
769}
770
771/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
772/// and CmpRHS are both known to be integer constants.
773Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
774 ConstantInt *DivRHS) {
775 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
776 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000777
778 // FIXME: If the operand types don't match the type of the divide
Chris Lattner02446fc2010-01-04 07:37:31 +0000779 // then don't attempt this transform. The code below doesn't have the
780 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000781 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner02446fc2010-01-04 07:37:31 +0000782 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000783 // (x /u C1) <u C2. Simply casting the operands and result won't
784 // work. :( The if statement below tests that condition and bails
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000785 // if it finds it.
Chris Lattner02446fc2010-01-04 07:37:31 +0000786 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
787 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
788 return 0;
789 if (DivRHS->isZero())
790 return 0; // The ProdOV computation fails on divide by zero.
791 if (DivIsSigned && DivRHS->isAllOnesValue())
792 return 0; // The overflow computation also screws up here
Chris Lattnerbb75d332011-02-13 08:07:21 +0000793 if (DivRHS->isOne()) {
794 // This eliminates some funny cases with INT_MIN.
795 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
796 return &ICI;
797 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000798
799 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000800 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
801 // C2 (CI). By solving for X we can turn this into a range check
802 // instead of computing a divide.
Chris Lattner02446fc2010-01-04 07:37:31 +0000803 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
804
805 // Determine if the product overflows by seeing if the product is
806 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000807 // as in the LHS instruction that we're folding.
Chris Lattner02446fc2010-01-04 07:37:31 +0000808 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
809 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
810
811 // Get the ICmp opcode
812 ICmpInst::Predicate Pred = ICI.getPredicate();
813
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000814 /// If the division is known to be exact, then there is no remainder from the
815 /// divide, so the covered range size is unit, otherwise it is the divisor.
816 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000817
Chris Lattner02446fc2010-01-04 07:37:31 +0000818 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000819 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner02446fc2010-01-04 07:37:31 +0000820 // Compute this interval based on the constants involved and the signedness of
821 // the compare/divide. This computes a half-open interval, keeping track of
822 // whether either value in the interval overflows. After analysis each
823 // overflow variable is set to 0 if it's corresponding bound variable is valid
824 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
825 int LoOverflow = 0, HiOverflow = 0;
826 Constant *LoBound = 0, *HiBound = 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000827
Chris Lattner02446fc2010-01-04 07:37:31 +0000828 if (!DivIsSigned) { // udiv
829 // e.g. X/5 op 3 --> [15, 20)
830 LoBound = Prod;
831 HiOverflow = LoOverflow = ProdOV;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000832 if (!HiOverflow) {
833 // If this is not an exact divide, then many values in the range collapse
834 // to the same result value.
835 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
836 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000837
Chris Lattner02446fc2010-01-04 07:37:31 +0000838 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
839 if (CmpRHSV == 0) { // (X / pos) op 0
840 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000841 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
842 HiBound = RangeSize;
Chris Lattner02446fc2010-01-04 07:37:31 +0000843 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
844 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
845 HiOverflow = LoOverflow = ProdOV;
846 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000847 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000848 } else { // (X / pos) op neg
849 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
850 HiBound = AddOne(Prod);
851 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
852 if (!LoOverflow) {
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000853 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000854 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000855 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000856 }
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000857 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000858 if (DivI->isExact())
859 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000860 if (CmpRHSV == 0) { // (X / neg) op 0
861 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000862 LoBound = AddOne(RangeSize);
863 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000864 if (HiBound == DivRHS) { // -INTMIN = INTMIN
865 HiOverflow = 1; // [INTMIN+1, overflow)
866 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
867 }
868 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
869 // e.g. X/-5 op 3 --> [-19, -14)
870 HiBound = AddOne(Prod);
871 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
872 if (!LoOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000873 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner02446fc2010-01-04 07:37:31 +0000874 } else { // (X / neg) op neg
875 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
876 LoOverflow = HiOverflow = ProdOV;
877 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000878 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000879 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000880
Chris Lattner02446fc2010-01-04 07:37:31 +0000881 // Dividing by a negative swaps the condition. LT <-> GT
882 Pred = ICmpInst::getSwappedPredicate(Pred);
883 }
884
885 Value *X = DivI->getOperand(0);
886 switch (Pred) {
887 default: llvm_unreachable("Unhandled icmp opcode!");
888 case ICmpInst::ICMP_EQ:
889 if (LoOverflow && HiOverflow)
890 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000891 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000892 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
893 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000894 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000895 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
896 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000897 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
898 DivIsSigned, true));
Chris Lattner02446fc2010-01-04 07:37:31 +0000899 case ICmpInst::ICMP_NE:
900 if (LoOverflow && HiOverflow)
901 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000902 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000903 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
904 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000905 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000906 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
907 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000908 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
909 DivIsSigned, false));
Chris Lattner02446fc2010-01-04 07:37:31 +0000910 case ICmpInst::ICMP_ULT:
911 case ICmpInst::ICMP_SLT:
912 if (LoOverflow == +1) // Low bound is greater than input range.
913 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
914 if (LoOverflow == -1) // Low bound is less than input range.
915 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
916 return new ICmpInst(Pred, X, LoBound);
917 case ICmpInst::ICMP_UGT:
918 case ICmpInst::ICMP_SGT:
919 if (HiOverflow == +1) // High bound greater than input range.
920 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000921 if (HiOverflow == -1) // High bound less than input range.
Chris Lattner02446fc2010-01-04 07:37:31 +0000922 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
923 if (Pred == ICmpInst::ICMP_UGT)
924 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000925 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner02446fc2010-01-04 07:37:31 +0000926 }
927}
928
Chris Lattner74542aa2011-02-13 07:43:07 +0000929/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
930Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
931 ConstantInt *ShAmt) {
Chris Lattner74542aa2011-02-13 07:43:07 +0000932 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000933
Chris Lattner74542aa2011-02-13 07:43:07 +0000934 // Check that the shift amount is in range. If not, don't perform
935 // undefined shifts. When the shift is visited it will be
936 // simplified.
937 uint32_t TypeBits = CmpRHSV.getBitWidth();
938 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnerbb75d332011-02-13 08:07:21 +0000939 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Chris Lattner74542aa2011-02-13 07:43:07 +0000940 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000941
Chris Lattnerbb75d332011-02-13 08:07:21 +0000942 if (!ICI.isEquality()) {
943 // If we have an unsigned comparison and an ashr, we can't simplify this.
944 // Similarly for signed comparisons with lshr.
945 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
946 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000947
Eli Friedmana831a9b2011-05-25 23:26:20 +0000948 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
949 // by a power of 2. Since we already have logic to simplify these,
950 // transform to div and then simplify the resultant comparison.
Chris Lattnerbb75d332011-02-13 08:07:21 +0000951 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedmana831a9b2011-05-25 23:26:20 +0000952 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Chris Lattnerbb75d332011-02-13 08:07:21 +0000953 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000954
Chris Lattnerbb75d332011-02-13 08:07:21 +0000955 // Revisit the shift (to delete it).
956 Worklist.Add(Shr);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000957
Chris Lattnerbb75d332011-02-13 08:07:21 +0000958 Constant *DivCst =
959 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000960
Chris Lattnerbb75d332011-02-13 08:07:21 +0000961 Value *Tmp =
962 Shr->getOpcode() == Instruction::AShr ?
963 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
964 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000965
Chris Lattnerbb75d332011-02-13 08:07:21 +0000966 ICI.setOperand(0, Tmp);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000967
Chris Lattnerbb75d332011-02-13 08:07:21 +0000968 // If the builder folded the binop, just return it.
969 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
970 if (TheDiv == 0)
971 return &ICI;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000972
Chris Lattnerbb75d332011-02-13 08:07:21 +0000973 // Otherwise, fold this div/compare.
974 assert(TheDiv->getOpcode() == Instruction::SDiv ||
975 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000976
Chris Lattnerbb75d332011-02-13 08:07:21 +0000977 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
978 assert(Res && "This div/cst should have folded!");
979 return Res;
980 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000981
982
Chris Lattner74542aa2011-02-13 07:43:07 +0000983 // If we are comparing against bits always shifted out, the
984 // comparison cannot succeed.
985 APInt Comp = CmpRHSV << ShAmtVal;
986 ConstantInt *ShiftedCmpRHS = ConstantInt::get(ICI.getContext(), Comp);
987 if (Shr->getOpcode() == Instruction::LShr)
988 Comp = Comp.lshr(ShAmtVal);
989 else
990 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000991
Chris Lattner74542aa2011-02-13 07:43:07 +0000992 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
993 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
994 Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
995 IsICMP_NE);
996 return ReplaceInstUsesWith(ICI, Cst);
997 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000998
Chris Lattner74542aa2011-02-13 07:43:07 +0000999 // Otherwise, check to see if the bits shifted out are known to be zero.
1000 // If so, we can compare against the unshifted value:
1001 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattnere5116f82011-02-13 18:30:09 +00001002 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattner74542aa2011-02-13 07:43:07 +00001003 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001004
Chris Lattner74542aa2011-02-13 07:43:07 +00001005 if (Shr->hasOneUse()) {
1006 // Otherwise strength reduce the shift into an and.
1007 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1008 Constant *Mask = ConstantInt::get(ICI.getContext(), Val);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001009
Chris Lattner74542aa2011-02-13 07:43:07 +00001010 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1011 Mask, Shr->getName()+".mask");
1012 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1013 }
1014 return 0;
1015}
1016
Chris Lattner02446fc2010-01-04 07:37:31 +00001017
1018/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1019///
1020Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1021 Instruction *LHSI,
1022 ConstantInt *RHS) {
1023 const APInt &RHSV = RHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001024
Chris Lattner02446fc2010-01-04 07:37:31 +00001025 switch (LHSI->getOpcode()) {
1026 case Instruction::Trunc:
1027 if (ICI.isEquality() && LHSI->hasOneUse()) {
1028 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1029 // of the high bits truncated out of x are known.
1030 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1031 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner02446fc2010-01-04 07:37:31 +00001032 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001033 ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001034
Chris Lattner02446fc2010-01-04 07:37:31 +00001035 // If all the high bits are known, we can do this xform.
1036 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1037 // Pull in the high bits from known-ones set.
Jay Foad40f8f622010-12-07 08:25:19 +00001038 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedman5b6dfee2012-05-11 01:32:59 +00001039 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner02446fc2010-01-04 07:37:31 +00001040 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1041 ConstantInt::get(ICI.getContext(), NewRHS));
1042 }
1043 }
1044 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001045
Chris Lattner02446fc2010-01-04 07:37:31 +00001046 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
1047 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1048 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1049 // fold the xor.
1050 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1051 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1052 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001053
Chris Lattner02446fc2010-01-04 07:37:31 +00001054 // If the sign bit of the XorCST is not set, there is no change to
1055 // the operation, just stop using the Xor.
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001056 if (!XorCST->isNegative()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001057 ICI.setOperand(0, CompareVal);
1058 Worklist.Add(LHSI);
1059 return &ICI;
1060 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001061
Chris Lattner02446fc2010-01-04 07:37:31 +00001062 // Was the old condition true if the operand is positive?
1063 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001064
Chris Lattner02446fc2010-01-04 07:37:31 +00001065 // If so, the new one isn't.
1066 isTrueIfPositive ^= true;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001067
Chris Lattner02446fc2010-01-04 07:37:31 +00001068 if (isTrueIfPositive)
1069 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1070 SubOne(RHS));
1071 else
1072 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1073 AddOne(RHS));
1074 }
1075
1076 if (LHSI->hasOneUse()) {
1077 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1078 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
1079 const APInt &SignBit = XorCST->getValue();
1080 ICmpInst::Predicate Pred = ICI.isSigned()
1081 ? ICI.getUnsignedPredicate()
1082 : ICI.getSignedPredicate();
1083 return new ICmpInst(Pred, LHSI->getOperand(0),
1084 ConstantInt::get(ICI.getContext(),
1085 RHSV ^ SignBit));
1086 }
1087
1088 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001089 if (!ICI.isEquality() && XorCST->isMaxValue(true)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001090 const APInt &NotSignBit = XorCST->getValue();
1091 ICmpInst::Predicate Pred = ICI.isSigned()
1092 ? ICI.getUnsignedPredicate()
1093 : ICI.getSignedPredicate();
1094 Pred = ICI.getSwappedPredicate(Pred);
1095 return new ICmpInst(Pred, LHSI->getOperand(0),
1096 ConstantInt::get(ICI.getContext(),
1097 RHSV ^ NotSignBit));
1098 }
1099 }
1100 }
1101 break;
1102 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
1103 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1104 LHSI->getOperand(0)->hasOneUse()) {
1105 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001106
Chris Lattner02446fc2010-01-04 07:37:31 +00001107 // If the LHS is an AND of a truncating cast, we can widen the
1108 // and/compare to be the input width without changing the value
1109 // produced, eliminating a cast.
1110 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1111 // We can do this transformation if either the AND constant does not
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001112 // have its sign bit set or if it is an equality comparison.
Chris Lattner02446fc2010-01-04 07:37:31 +00001113 // Extending a relational comparison when we're checking the sign
1114 // bit would not work.
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001115 if (ICI.isEquality() ||
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001116 (!AndCST->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001117 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001118 Builder->CreateAnd(Cast->getOperand(0),
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001119 ConstantExpr::getZExt(AndCST, Cast->getSrcTy()));
1120 NewAnd->takeName(LHSI);
Chris Lattner02446fc2010-01-04 07:37:31 +00001121 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001122 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001123 }
1124 }
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001125
1126 // If the LHS is an AND of a zext, and we have an equality compare, we can
1127 // shrink the and/compare to the smaller type, eliminating the cast.
1128 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001129 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001130 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1131 // should fold the icmp to true/false in that case.
1132 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1133 Value *NewAnd =
1134 Builder->CreateAnd(Cast->getOperand(0),
1135 ConstantExpr::getTrunc(AndCST, Ty));
1136 NewAnd->takeName(LHSI);
1137 return new ICmpInst(ICI.getPredicate(), NewAnd,
1138 ConstantExpr::getTrunc(RHS, Ty));
1139 }
1140 }
1141
Chris Lattner02446fc2010-01-04 07:37:31 +00001142 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1143 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1144 // happens a LOT in code produced by the C front-end, for bitfield
1145 // access.
1146 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1147 if (Shift && !Shift->isShift())
1148 Shift = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001149
Chris Lattner02446fc2010-01-04 07:37:31 +00001150 ConstantInt *ShAmt;
1151 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001152 Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
1153 Type *AndTy = AndCST->getType(); // Type of the and.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001154
Chris Lattner02446fc2010-01-04 07:37:31 +00001155 // We can fold this as long as we can't shift unknown bits
1156 // into the mask. This can only happen with signed shift
1157 // rights, as they sign-extend.
1158 if (ShAmt) {
1159 bool CanFold = Shift->isLogicalShift();
1160 if (!CanFold) {
1161 // To test for the bad case of the signed shr, see if any
1162 // of the bits shifted in could be tested after the mask.
1163 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1164 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001165
Chris Lattner02446fc2010-01-04 07:37:31 +00001166 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001167 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
Chris Lattner02446fc2010-01-04 07:37:31 +00001168 AndCST->getValue()) == 0)
1169 CanFold = true;
1170 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001171
Chris Lattner02446fc2010-01-04 07:37:31 +00001172 if (CanFold) {
1173 Constant *NewCst;
1174 if (Shift->getOpcode() == Instruction::Shl)
1175 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1176 else
1177 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001178
Chris Lattner02446fc2010-01-04 07:37:31 +00001179 // Check to see if we are shifting out any of the bits being
1180 // compared.
1181 if (ConstantExpr::get(Shift->getOpcode(),
1182 NewCst, ShAmt) != RHS) {
1183 // If we shifted bits out, the fold is not going to work out.
1184 // As a special case, check to see if this means that the
1185 // result is always true or false now.
1186 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1187 return ReplaceInstUsesWith(ICI,
1188 ConstantInt::getFalse(ICI.getContext()));
1189 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1190 return ReplaceInstUsesWith(ICI,
1191 ConstantInt::getTrue(ICI.getContext()));
1192 } else {
1193 ICI.setOperand(1, NewCst);
1194 Constant *NewAndCST;
1195 if (Shift->getOpcode() == Instruction::Shl)
1196 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1197 else
1198 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1199 LHSI->setOperand(1, NewAndCST);
1200 LHSI->setOperand(0, Shift->getOperand(0));
1201 Worklist.Add(Shift); // Shift is dead.
1202 return &ICI;
1203 }
1204 }
1205 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001206
Chris Lattner02446fc2010-01-04 07:37:31 +00001207 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1208 // preferable because it allows the C<<Y expression to be hoisted out
1209 // of a loop if Y is invariant and X is not.
1210 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1211 ICI.isEquality() && !Shift->isArithmeticShift() &&
1212 !isa<Constant>(Shift->getOperand(0))) {
1213 // Compute C << Y.
1214 Value *NS;
1215 if (Shift->getOpcode() == Instruction::LShr) {
Benjamin Kramera9390a42011-09-27 20:39:19 +00001216 NS = Builder->CreateShl(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001217 } else {
1218 // Insert a logical shift.
Benjamin Kramera9390a42011-09-27 20:39:19 +00001219 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001220 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001221
Chris Lattner02446fc2010-01-04 07:37:31 +00001222 // Compute X & (C << Y).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001223 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001224 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001225
Chris Lattner02446fc2010-01-04 07:37:31 +00001226 ICI.setOperand(0, NewAnd);
1227 return &ICI;
1228 }
Paul Redmond6da2e222012-12-19 19:47:13 +00001229
1230 // Replace ((X & AndCST) > RHSV) with ((X & AndCST) != 0), if any
1231 // bit set in (X & AndCST) will produce a result greater than RHSV.
1232 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
1233 unsigned NTZ = AndCST->getValue().countTrailingZeros();
1234 if ((NTZ < AndCST->getBitWidth()) &&
1235 APInt::getOneBitSet(AndCST->getBitWidth(), NTZ).ugt(RHSV))
1236 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1237 Constant::getNullValue(RHS->getType()));
1238 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001239 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001240
Chris Lattner02446fc2010-01-04 07:37:31 +00001241 // Try to optimize things like "A[i]&42 == 0" to index computations.
1242 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1243 if (GetElementPtrInst *GEP =
1244 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1245 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1246 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1247 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1248 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1249 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1250 return Res;
1251 }
1252 }
1253 break;
1254
1255 case Instruction::Or: {
1256 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1257 break;
1258 Value *P, *Q;
1259 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1260 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1261 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner02446fc2010-01-04 07:37:31 +00001262 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1263 Constant::getNullValue(P->getType()));
1264 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1265 Constant::getNullValue(Q->getType()));
1266 Instruction *Op;
1267 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1268 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1269 else
1270 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1271 return Op;
1272 }
1273 break;
1274 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001275
Chris Lattner02446fc2010-01-04 07:37:31 +00001276 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
1277 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1278 if (!ShAmt) break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001279
Chris Lattner02446fc2010-01-04 07:37:31 +00001280 uint32_t TypeBits = RHSV.getBitWidth();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001281
Chris Lattner02446fc2010-01-04 07:37:31 +00001282 // Check that the shift amount is in range. If not, don't perform
1283 // undefined shifts. When the shift is visited it will be
1284 // simplified.
1285 if (ShAmt->uge(TypeBits))
1286 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001287
Chris Lattner02446fc2010-01-04 07:37:31 +00001288 if (ICI.isEquality()) {
1289 // If we are comparing against bits always shifted out, the
1290 // comparison cannot succeed.
1291 Constant *Comp =
1292 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1293 ShAmt);
1294 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1295 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1296 Constant *Cst =
1297 ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE);
1298 return ReplaceInstUsesWith(ICI, Cst);
1299 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001300
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001301 // If the shift is NUW, then it is just shifting out zeros, no need for an
1302 // AND.
1303 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1304 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1305 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001306
Chris Lattner02446fc2010-01-04 07:37:31 +00001307 if (LHSI->hasOneUse()) {
1308 // Otherwise strength reduce the shift into an and.
1309 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1310 Constant *Mask =
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001311 ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits,
Chris Lattner02446fc2010-01-04 07:37:31 +00001312 TypeBits-ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001313
Chris Lattner02446fc2010-01-04 07:37:31 +00001314 Value *And =
1315 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1316 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001317 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner02446fc2010-01-04 07:37:31 +00001318 }
1319 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001320
Chris Lattner02446fc2010-01-04 07:37:31 +00001321 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1322 bool TrueIfSigned = false;
1323 if (LHSI->hasOneUse() &&
1324 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1325 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattnerbb75d332011-02-13 08:07:21 +00001326 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001327 APInt::getOneBitSet(TypeBits,
Chris Lattnerbb75d332011-02-13 08:07:21 +00001328 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001329 Value *And =
1330 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1331 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1332 And, Constant::getNullValue(And->getType()));
1333 }
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001334
1335 // Transform (icmp pred iM (shl iM %v, N), CI)
1336 // -> (icmp pred i(M-N) (trunc %v iM to i(N-N)), (trunc (CI>>N))
1337 // Transform the shl to a trunc if (trunc (CI>>N)) has no loss.
1338 // This enables to get rid of the shift in favor of a trunc which can be
1339 // free on the target. It has the additional benefit of comparing to a
1340 // smaller constant, which will be target friendly.
1341 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
1342 if (Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
1343 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1344 Constant *NCI = ConstantExpr::getTrunc(
1345 ConstantExpr::getAShr(RHS,
1346 ConstantInt::get(RHS->getType(), Amt)),
1347 NTy);
1348 return new ICmpInst(ICI.getPredicate(),
1349 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaisonad079b22013-02-15 15:18:17 +00001350 NCI);
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001351 }
1352
Chris Lattner02446fc2010-01-04 07:37:31 +00001353 break;
1354 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001355
Chris Lattner02446fc2010-01-04 07:37:31 +00001356 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001357 case Instruction::AShr: {
1358 // Handle equality comparisons of shift-by-constant.
1359 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1360 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1361 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattner74542aa2011-02-13 07:43:07 +00001362 return Res;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001363 }
1364
1365 // Handle exact shr's.
1366 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1367 if (RHSV.isMinValue())
1368 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1369 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001370 break;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001371 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001372
Chris Lattner02446fc2010-01-04 07:37:31 +00001373 case Instruction::SDiv:
1374 case Instruction::UDiv:
1375 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001376 // Fold this div into the comparison, producing a range check.
1377 // Determine, based on the divide type, what the range is being
1378 // checked. If there is an overflow on the low or high side, remember
Chris Lattner02446fc2010-01-04 07:37:31 +00001379 // it, otherwise compute the range [low, hi) bounding the new value.
1380 // See: InsertRangeTest above for the kinds of replacements possible.
1381 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1382 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1383 DivRHS))
1384 return R;
1385 break;
1386
1387 case Instruction::Add:
1388 // Fold: icmp pred (add X, C1), C2
1389 if (!ICI.isEquality()) {
1390 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1391 if (!LHSC) break;
1392 const APInt &LHSV = LHSC->getValue();
1393
1394 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1395 .subtract(LHSV);
1396
1397 if (ICI.isSigned()) {
1398 if (CR.getLower().isSignBit()) {
1399 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1400 ConstantInt::get(ICI.getContext(),CR.getUpper()));
1401 } else if (CR.getUpper().isSignBit()) {
1402 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1403 ConstantInt::get(ICI.getContext(),CR.getLower()));
1404 }
1405 } else {
1406 if (CR.getLower().isMinValue()) {
1407 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1408 ConstantInt::get(ICI.getContext(),CR.getUpper()));
1409 } else if (CR.getUpper().isMinValue()) {
1410 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1411 ConstantInt::get(ICI.getContext(),CR.getLower()));
1412 }
1413 }
1414 }
1415 break;
1416 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001417
Chris Lattner02446fc2010-01-04 07:37:31 +00001418 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1419 if (ICI.isEquality()) {
1420 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001421
1422 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner02446fc2010-01-04 07:37:31 +00001423 // the second operand is a constant, simplify a bit.
1424 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1425 switch (BO->getOpcode()) {
1426 case Instruction::SRem:
1427 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1428 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1429 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohmane0567812010-04-08 23:03:40 +00001430 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001431 Value *NewRem =
1432 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1433 BO->getName());
1434 return new ICmpInst(ICI.getPredicate(), NewRem,
1435 Constant::getNullValue(BO->getType()));
1436 }
1437 }
1438 break;
1439 case Instruction::Add:
1440 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1441 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1442 if (BO->hasOneUse())
1443 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1444 ConstantExpr::getSub(RHS, BOp1C));
1445 } else if (RHSV == 0) {
1446 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1447 // efficiently invertible, or if the add has just this one use.
1448 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001449
Chris Lattner02446fc2010-01-04 07:37:31 +00001450 if (Value *NegVal = dyn_castNegVal(BOp1))
1451 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner5036ce42011-04-26 20:02:45 +00001452 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner02446fc2010-01-04 07:37:31 +00001453 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner5036ce42011-04-26 20:02:45 +00001454 if (BO->hasOneUse()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001455 Value *Neg = Builder->CreateNeg(BOp1);
1456 Neg->takeName(BO);
1457 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1458 }
1459 }
1460 break;
1461 case Instruction::Xor:
1462 // For the xor case, we can xor two constants together, eliminating
1463 // the explicit xor.
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001464 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1465 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner02446fc2010-01-04 07:37:31 +00001466 ConstantExpr::getXor(RHS, BOC));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001467 } else if (RHSV == 0) {
1468 // Replace ((xor A, B) != 0) with (A != B)
Chris Lattner02446fc2010-01-04 07:37:31 +00001469 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1470 BO->getOperand(1));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001471 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001472 break;
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001473 case Instruction::Sub:
1474 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1475 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1476 if (BO->hasOneUse())
1477 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1478 ConstantExpr::getSub(BOp0C, RHS));
1479 } else if (RHSV == 0) {
1480 // Replace ((sub A, B) != 0) with (A != B)
1481 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1482 BO->getOperand(1));
1483 }
1484 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001485 case Instruction::Or:
1486 // If bits are being or'd in that are not present in the constant we
1487 // are comparing against, then the comparison could never succeed!
Eli Friedman618898e2010-07-29 18:03:33 +00001488 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001489 Constant *NotCI = ConstantExpr::getNot(RHS);
1490 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1491 return ReplaceInstUsesWith(ICI,
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001492 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
Chris Lattner02446fc2010-01-04 07:37:31 +00001493 isICMP_NE));
1494 }
1495 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001496
Chris Lattner02446fc2010-01-04 07:37:31 +00001497 case Instruction::And:
1498 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1499 // If bits are being compared against that are and'd out, then the
1500 // comparison can never succeed!
1501 if ((RHSV & ~BOC->getValue()) != 0)
1502 return ReplaceInstUsesWith(ICI,
1503 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1504 isICMP_NE));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001505
Chris Lattner02446fc2010-01-04 07:37:31 +00001506 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1507 if (RHS == BOC && RHSV.isPowerOf2())
1508 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1509 ICmpInst::ICMP_NE, LHSI,
1510 Constant::getNullValue(RHS->getType()));
Benjamin Kramerfc87cdc2011-07-04 20:16:36 +00001511
1512 // Don't perform the following transforms if the AND has multiple uses
1513 if (!BO->hasOneUse())
1514 break;
1515
Chris Lattner02446fc2010-01-04 07:37:31 +00001516 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1517 if (BOC->getValue().isSignBit()) {
1518 Value *X = BO->getOperand(0);
1519 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001520 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001521 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1522 return new ICmpInst(pred, X, Zero);
1523 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001524
Chris Lattner02446fc2010-01-04 07:37:31 +00001525 // ((X & ~7) == 0) --> X < 8
1526 if (RHSV == 0 && isHighOnes(BOC)) {
1527 Value *X = BO->getOperand(0);
1528 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001529 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001530 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1531 return new ICmpInst(pred, X, NegX);
1532 }
1533 }
1534 default: break;
1535 }
1536 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1537 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner03357402010-01-05 18:09:56 +00001538 switch (II->getIntrinsicID()) {
1539 case Intrinsic::bswap:
Chris Lattner02446fc2010-01-04 07:37:31 +00001540 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001541 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00001542 ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
1543 return &ICI;
Chris Lattner03357402010-01-05 18:09:56 +00001544 case Intrinsic::ctlz:
1545 case Intrinsic::cttz:
1546 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1547 if (RHSV == RHS->getType()->getBitWidth()) {
1548 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001549 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001550 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1551 return &ICI;
1552 }
1553 break;
1554 case Intrinsic::ctpop:
1555 // popcount(A) == 0 -> A == 0 and likewise for !=
1556 if (RHS->isZero()) {
1557 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001558 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001559 ICI.setOperand(1, RHS);
1560 return &ICI;
1561 }
1562 break;
1563 default:
Duncan Sands34727662010-07-12 08:16:59 +00001564 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001565 }
1566 }
1567 }
1568 return 0;
1569}
1570
1571/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1572/// We only handle extending casts so far.
1573///
1574Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1575 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1576 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001577 Type *SrcTy = LHSCIOp->getType();
1578 Type *DestTy = LHSCI->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00001579 Value *RHSCIOp;
1580
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001581 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner02446fc2010-01-04 07:37:31 +00001582 // integer type is the same size as the pointer type.
1583 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
Chandler Carruth426c2bf2012-11-01 09:14:31 +00001584 TD->getPointerSizeInBits() ==
Chris Lattner02446fc2010-01-04 07:37:31 +00001585 cast<IntegerType>(DestTy)->getBitWidth()) {
1586 Value *RHSOp = 0;
1587 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1588 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1589 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1590 RHSOp = RHSC->getOperand(0);
1591 // If the pointer types don't match, insert a bitcast.
1592 if (LHSCIOp->getType() != RHSOp->getType())
1593 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1594 }
1595
1596 if (RHSOp)
1597 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1598 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001599
Chris Lattner02446fc2010-01-04 07:37:31 +00001600 // The code below only handles extension cast instructions, so far.
1601 // Enforce this.
1602 if (LHSCI->getOpcode() != Instruction::ZExt &&
1603 LHSCI->getOpcode() != Instruction::SExt)
1604 return 0;
1605
1606 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1607 bool isSignedCmp = ICI.isSigned();
1608
1609 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1610 // Not an extension from the same type?
1611 RHSCIOp = CI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001612 if (RHSCIOp->getType() != LHSCIOp->getType())
Chris Lattner02446fc2010-01-04 07:37:31 +00001613 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001614
Chris Lattner02446fc2010-01-04 07:37:31 +00001615 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1616 // and the other is a zext), then we can't handle this.
1617 if (CI->getOpcode() != LHSCI->getOpcode())
1618 return 0;
1619
1620 // Deal with equality cases early.
1621 if (ICI.isEquality())
1622 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1623
1624 // A signed comparison of sign extended values simplifies into a
1625 // signed comparison.
1626 if (isSignedCmp && isSignedExt)
1627 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1628
1629 // The other three cases all fold into an unsigned comparison.
1630 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1631 }
1632
1633 // If we aren't dealing with a constant on the RHS, exit early
1634 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1635 if (!CI)
1636 return 0;
1637
1638 // Compute the constant that would happen if we truncated to SrcTy then
1639 // reextended to DestTy.
1640 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1641 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1642 Res1, DestTy);
1643
1644 // If the re-extended constant didn't change...
1645 if (Res2 == CI) {
1646 // Deal with equality cases early.
1647 if (ICI.isEquality())
1648 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1649
1650 // A signed comparison of sign extended values simplifies into a
1651 // signed comparison.
1652 if (isSignedExt && isSignedCmp)
1653 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1654
1655 // The other three cases all fold into an unsigned comparison.
1656 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1657 }
1658
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001659 // The re-extended constant changed so the constant cannot be represented
Chris Lattner02446fc2010-01-04 07:37:31 +00001660 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands9d32f602011-01-20 13:21:55 +00001661 // All the cases that fold to true or false will have already been handled
1662 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner02446fc2010-01-04 07:37:31 +00001663
Duncan Sands9d32f602011-01-20 13:21:55 +00001664 if (isSignedCmp || !isSignedExt)
1665 return 0;
Chris Lattner02446fc2010-01-04 07:37:31 +00001666
1667 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1668 // should have been folded away previously and not enter in here.
Duncan Sands9d32f602011-01-20 13:21:55 +00001669
1670 // We're performing an unsigned comp with a sign extended value.
1671 // This is true if the input is >= 0. [aka >s -1]
1672 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1673 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner02446fc2010-01-04 07:37:31 +00001674
1675 // Finally, return the value computed.
Duncan Sands9d32f602011-01-20 13:21:55 +00001676 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner02446fc2010-01-04 07:37:31 +00001677 return ReplaceInstUsesWith(ICI, Result);
1678
Duncan Sands9d32f602011-01-20 13:21:55 +00001679 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner02446fc2010-01-04 07:37:31 +00001680 return BinaryOperator::CreateNot(Result);
1681}
1682
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001683/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1684/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001685/// If this is of the form:
1686/// sum = a + b
1687/// if (sum+128 >u 255)
1688/// Then replace it with llvm.sadd.with.overflow.i8.
1689///
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001690static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1691 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001692 InstCombiner &IC) {
Chris Lattner368397b2010-12-19 17:59:02 +00001693 // The transformation we're trying to do here is to transform this into an
1694 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1695 // with a narrower add, and discard the add-with-constant that is part of the
1696 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001697
Chris Lattner368397b2010-12-19 17:59:02 +00001698 // In order to eliminate the add-with-constant, the compare can be its only
1699 // use.
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001700 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Chris Lattner368397b2010-12-19 17:59:02 +00001701 if (!AddWithCst->hasOneUse()) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001702
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001703 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1704 if (!CI2->getValue().isPowerOf2()) return 0;
1705 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1706 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001707
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001708 // The width of the new add formed is 1 more than the bias.
1709 ++NewWidth;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001710
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001711 // Check to see that CI1 is an all-ones value with NewWidth bits.
1712 if (CI1->getBitWidth() == NewWidth ||
1713 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1714 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001715
Eli Friedman54b92112011-11-28 23:32:19 +00001716 // This is only really a signed overflow check if the inputs have been
1717 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1718 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1719 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1720 if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1721 IC.ComputeNumSignBits(B) < NeededSignBits)
1722 return 0;
1723
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001724 // In order to replace the original add with a narrower
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001725 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1726 // and truncates that discard the high bits of the add. Verify that this is
1727 // the case.
1728 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1729 for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1730 UI != E; ++UI) {
1731 if (*UI == AddWithCst) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001732
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001733 // Only accept truncates for now. We would really like a nice recursive
1734 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1735 // chain to see which bits of a value are actually demanded. If the
1736 // original add had another add which was then immediately truncated, we
1737 // could still do the transformation.
1738 TruncInst *TI = dyn_cast<TruncInst>(*UI);
1739 if (TI == 0 ||
1740 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1741 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001742
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001743 // If the pattern matches, truncate the inputs to the narrower type and
1744 // use the sadd_with_overflow intrinsic to efficiently compute both the
1745 // result and the overflow bit.
Chris Lattner0a624742010-12-19 18:35:09 +00001746 Module *M = I.getParent()->getParent()->getParent();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001747
Jay Foad5fdd6c82011-07-12 14:06:48 +00001748 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Chris Lattner0a624742010-12-19 18:35:09 +00001749 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001750 NewType);
Chris Lattner0a624742010-12-19 18:35:09 +00001751
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001752 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001753
Chris Lattner0a624742010-12-19 18:35:09 +00001754 // Put the new code above the original add, in case there are any uses of the
1755 // add between the add and the compare.
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001756 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001757
Chris Lattner0a624742010-12-19 18:35:09 +00001758 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1759 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1760 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1761 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1762 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001763
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001764 // The inner add was the result of the narrow add, zero extended to the
1765 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001766 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001767
Chris Lattner0a624742010-12-19 18:35:09 +00001768 // The original icmp gets replaced with the overflow value.
1769 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001770}
Chris Lattner02446fc2010-01-04 07:37:31 +00001771
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001772static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1773 InstCombiner &IC) {
1774 // Don't bother doing this transformation for pointers, don't do it for
1775 // vectors.
1776 if (!isa<IntegerType>(OrigAddV->getType())) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001777
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001778 // If the add is a constant expr, then we don't bother transforming it.
1779 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1780 if (OrigAdd == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001781
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001782 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001783
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001784 // Put the new code above the original add, in case there are any uses of the
1785 // add between the add and the compare.
1786 InstCombiner::BuilderTy *Builder = IC.Builder;
1787 Builder->SetInsertPoint(OrigAdd);
1788
1789 Module *M = I.getParent()->getParent()->getParent();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001790 Type *Ty = LHS->getType();
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001791 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001792 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1793 Value *Add = Builder->CreateExtractValue(Call, 0);
1794
1795 IC.ReplaceInstUsesWith(*OrigAdd, Add);
1796
1797 // The original icmp gets replaced with the overflow value.
1798 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
1799}
1800
Owen Andersonda1c1222011-01-11 00:36:45 +00001801// DemandedBitsLHSMask - When performing a comparison against a constant,
1802// it is possible that not all the bits in the LHS are demanded. This helper
1803// method computes the mask that IS demanded.
1804static APInt DemandedBitsLHSMask(ICmpInst &I,
1805 unsigned BitWidth, bool isSignCheck) {
1806 if (isSignCheck)
1807 return APInt::getSignBit(BitWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001808
Owen Andersonda1c1222011-01-11 00:36:45 +00001809 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
1810 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Andersona33b6252011-01-11 18:26:37 +00001811 const APInt &RHS = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001812
Owen Andersonda1c1222011-01-11 00:36:45 +00001813 switch (I.getPredicate()) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001814 // For a UGT comparison, we don't care about any bits that
Owen Andersonda1c1222011-01-11 00:36:45 +00001815 // correspond to the trailing ones of the comparand. The value of these
1816 // bits doesn't impact the outcome of the comparison, because any value
1817 // greater than the RHS must differ in a bit higher than these due to carry.
1818 case ICmpInst::ICMP_UGT: {
1819 unsigned trailingOnes = RHS.countTrailingOnes();
1820 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
1821 return ~lowBitsSet;
1822 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001823
Owen Andersonda1c1222011-01-11 00:36:45 +00001824 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
1825 // Any value less than the RHS must differ in a higher bit because of carries.
1826 case ICmpInst::ICMP_ULT: {
1827 unsigned trailingZeros = RHS.countTrailingZeros();
1828 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
1829 return ~lowBitsSet;
1830 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001831
Owen Andersonda1c1222011-01-11 00:36:45 +00001832 default:
1833 return APInt::getAllOnesValue(BitWidth);
1834 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001835
Owen Andersonda1c1222011-01-11 00:36:45 +00001836}
Chris Lattner02446fc2010-01-04 07:37:31 +00001837
1838Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
1839 bool Changed = false;
Chris Lattner5f670d42010-02-01 19:54:45 +00001840 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001841
Chris Lattner02446fc2010-01-04 07:37:31 +00001842 /// Orders the operands of the compare so that they are listed from most
1843 /// complex to least complex. This puts constants before unary operators,
1844 /// before binary operators.
Chris Lattner5f670d42010-02-01 19:54:45 +00001845 if (getComplexity(Op0) < getComplexity(Op1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001846 I.swapOperands();
Chris Lattner5f670d42010-02-01 19:54:45 +00001847 std::swap(Op0, Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00001848 Changed = true;
1849 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001850
Chris Lattner02446fc2010-01-04 07:37:31 +00001851 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
1852 return ReplaceInstUsesWith(I, V);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001853
Pete Cooper65a6b572011-12-01 03:58:40 +00001854 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooper165695d2011-12-01 19:13:26 +00001855 // ie, abs(val) != 0 -> val != 0
Pete Cooper65a6b572011-12-01 03:58:40 +00001856 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
1857 {
Pete Cooper165695d2011-12-01 19:13:26 +00001858 Value *Cond, *SelectTrue, *SelectFalse;
1859 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooper65a6b572011-12-01 03:58:40 +00001860 m_Value(SelectFalse)))) {
Pete Cooper165695d2011-12-01 19:13:26 +00001861 if (Value *V = dyn_castNegVal(SelectTrue)) {
1862 if (V == SelectFalse)
1863 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
1864 }
1865 else if (Value *V = dyn_castNegVal(SelectFalse)) {
1866 if (V == SelectTrue)
1867 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooper65a6b572011-12-01 03:58:40 +00001868 }
1869 }
1870 }
1871
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001872 Type *Ty = Op0->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00001873
1874 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001875 if (Ty->isIntegerTy(1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001876 switch (I.getPredicate()) {
1877 default: llvm_unreachable("Invalid icmp instruction!");
1878 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
1879 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
1880 return BinaryOperator::CreateNot(Xor);
1881 }
1882 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
1883 return BinaryOperator::CreateXor(Op0, Op1);
1884
1885 case ICmpInst::ICMP_UGT:
1886 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
1887 // FALL THROUGH
1888 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
1889 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1890 return BinaryOperator::CreateAnd(Not, Op1);
1891 }
1892 case ICmpInst::ICMP_SGT:
1893 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
1894 // FALL THROUGH
1895 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
1896 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1897 return BinaryOperator::CreateAnd(Not, Op0);
1898 }
1899 case ICmpInst::ICMP_UGE:
1900 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
1901 // FALL THROUGH
1902 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
1903 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1904 return BinaryOperator::CreateOr(Not, Op1);
1905 }
1906 case ICmpInst::ICMP_SGE:
1907 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
1908 // FALL THROUGH
1909 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
1910 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1911 return BinaryOperator::CreateOr(Not, Op0);
1912 }
1913 }
1914 }
1915
1916 unsigned BitWidth = 0;
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001917 if (Ty->isIntOrIntVectorTy())
Chris Lattner02446fc2010-01-04 07:37:31 +00001918 BitWidth = Ty->getScalarSizeInBits();
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001919 else if (TD) // Pointers require TD info to get their size.
1920 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001921
Chris Lattner02446fc2010-01-04 07:37:31 +00001922 bool isSignBit = false;
1923
1924 // See if we are doing a comparison with a constant.
1925 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1926 Value *A = 0, *B = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001927
Owen Andersone63dda52010-12-17 18:08:00 +00001928 // Match the following pattern, which is a common idiom when writing
1929 // overflow-safe integer arithmetic function. The source performs an
1930 // addition in wider type, and explicitly checks for overflow using
1931 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
1932 // sadd_with_overflow intrinsic.
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001933 //
1934 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001935 // operations if we worked out the formulas to compute the appropriate
Owen Andersone63dda52010-12-17 18:08:00 +00001936 // magic constants.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001937 //
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001938 // sum = a + b
1939 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Andersone63dda52010-12-17 18:08:00 +00001940 {
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001941 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Andersone63dda52010-12-17 18:08:00 +00001942 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001943 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001944 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001945 return Res;
Owen Andersone63dda52010-12-17 18:08:00 +00001946 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001947
Chris Lattner02446fc2010-01-04 07:37:31 +00001948 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
1949 if (I.isEquality() && CI->isZero() &&
1950 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
1951 // (icmp cond A B) if cond is equality
1952 return new ICmpInst(I.getPredicate(), A, B);
1953 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001954
Chris Lattner02446fc2010-01-04 07:37:31 +00001955 // If we have an icmp le or icmp ge instruction, turn it into the
1956 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
1957 // them being folded in the code below. The SimplifyICmpInst code has
1958 // already handled the edge cases for us, so we just assert on them.
1959 switch (I.getPredicate()) {
1960 default: break;
1961 case ICmpInst::ICMP_ULE:
1962 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
1963 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
1964 ConstantInt::get(CI->getContext(), CI->getValue()+1));
1965 case ICmpInst::ICMP_SLE:
1966 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
1967 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
1968 ConstantInt::get(CI->getContext(), CI->getValue()+1));
1969 case ICmpInst::ICMP_UGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001970 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00001971 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
1972 ConstantInt::get(CI->getContext(), CI->getValue()-1));
1973 case ICmpInst::ICMP_SGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001974 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00001975 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
1976 ConstantInt::get(CI->getContext(), CI->getValue()-1));
1977 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001978
Chris Lattner02446fc2010-01-04 07:37:31 +00001979 // If this comparison is a normal comparison, it demands all
1980 // bits, if it is a sign bit comparison, it only demands the sign bit.
1981 bool UnusedBit;
1982 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
1983 }
1984
1985 // See if we can fold the comparison based on range information we can get
1986 // by checking whether bits are known to be zero or one in the input.
1987 if (BitWidth != 0) {
1988 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
1989 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
1990
1991 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersonda1c1222011-01-11 00:36:45 +00001992 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner02446fc2010-01-04 07:37:31 +00001993 Op0KnownZero, Op0KnownOne, 0))
1994 return &I;
1995 if (SimplifyDemandedBits(I.getOperandUse(1),
1996 APInt::getAllOnesValue(BitWidth),
1997 Op1KnownZero, Op1KnownOne, 0))
1998 return &I;
1999
2000 // Given the known and unknown bits, compute a range that the LHS could be
2001 // in. Compute the Min, Max and RHS values based on the known bits. For the
2002 // EQ and NE we use unsigned values.
2003 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2004 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2005 if (I.isSigned()) {
2006 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2007 Op0Min, Op0Max);
2008 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2009 Op1Min, Op1Max);
2010 } else {
2011 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2012 Op0Min, Op0Max);
2013 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2014 Op1Min, Op1Max);
2015 }
2016
2017 // If Min and Max are known to be the same, then SimplifyDemandedBits
2018 // figured out that the LHS is a constant. Just constant fold this now so
2019 // that code below can assume that Min != Max.
2020 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2021 return new ICmpInst(I.getPredicate(),
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002022 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00002023 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2024 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002025 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner02446fc2010-01-04 07:37:31 +00002026
2027 // Based on the range information we know about the LHS, see if we can
Nick Lewyckyd8d15842011-02-28 06:20:05 +00002028 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner02446fc2010-01-04 07:37:31 +00002029 switch (I.getPredicate()) {
2030 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner75d8f592010-11-21 06:44:42 +00002031 case ICmpInst::ICMP_EQ: {
Chris Lattner02446fc2010-01-04 07:37:31 +00002032 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002033 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002034
Chris Lattner75d8f592010-11-21 06:44:42 +00002035 // If all bits are known zero except for one, then we know at most one
2036 // bit is set. If the comparison is against zero, then this is a check
2037 // to see if *that* bit is set.
2038 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2039 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2040 // If the LHS is an AND with the same constant, look through it.
2041 Value *LHS = 0;
2042 ConstantInt *LHSC = 0;
2043 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2044 LHSC->getValue() != Op0KnownZeroInverted)
2045 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002046
Chris Lattner75d8f592010-11-21 06:44:42 +00002047 // 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 +00002048 // then turn "((1 << x)&8) == 0" into "x != 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002049 Value *X = 0;
2050 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2051 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002052 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002053 ConstantInt::get(X->getType(), CmpVal));
2054 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002055
Chris Lattner75d8f592010-11-21 06:44:42 +00002056 // 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 +00002057 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002058 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002059 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002060 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002061 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002062 ConstantInt::get(X->getType(),
2063 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002064 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002065
Chris Lattner02446fc2010-01-04 07:37:31 +00002066 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002067 }
2068 case ICmpInst::ICMP_NE: {
Chris Lattner02446fc2010-01-04 07:37:31 +00002069 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002070 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002071
Chris Lattner75d8f592010-11-21 06:44:42 +00002072 // If all bits are known zero except for one, then we know at most one
2073 // bit is set. If the comparison is against zero, then this is a check
2074 // to see if *that* bit is set.
2075 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2076 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2077 // If the LHS is an AND with the same constant, look through it.
2078 Value *LHS = 0;
2079 ConstantInt *LHSC = 0;
2080 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2081 LHSC->getValue() != Op0KnownZeroInverted)
2082 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002083
Chris Lattner75d8f592010-11-21 06:44:42 +00002084 // 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 +00002085 // then turn "((1 << x)&8) != 0" into "x == 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002086 Value *X = 0;
2087 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2088 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002089 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002090 ConstantInt::get(X->getType(), CmpVal));
2091 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002092
Chris Lattner75d8f592010-11-21 06:44:42 +00002093 // 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 +00002094 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002095 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002096 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002097 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002098 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002099 ConstantInt::get(X->getType(),
2100 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002101 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002102
Chris Lattner02446fc2010-01-04 07:37:31 +00002103 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002104 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002105 case ICmpInst::ICMP_ULT:
2106 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002107 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002108 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002109 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002110 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2111 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2112 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2113 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2114 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2115 ConstantInt::get(CI->getContext(), CI->getValue()-1));
2116
2117 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2118 if (CI->isMinValue(true))
2119 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2120 Constant::getAllOnesValue(Op0->getType()));
2121 }
2122 break;
2123 case ICmpInst::ICMP_UGT:
2124 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002125 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002126 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002127 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002128
2129 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2130 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2131 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2132 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2133 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2134 ConstantInt::get(CI->getContext(), CI->getValue()+1));
2135
2136 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2137 if (CI->isMaxValue(true))
2138 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2139 Constant::getNullValue(Op0->getType()));
2140 }
2141 break;
2142 case ICmpInst::ICMP_SLT:
2143 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002144 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002145 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002146 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002147 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2148 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2149 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2150 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2151 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2152 ConstantInt::get(CI->getContext(), CI->getValue()-1));
2153 }
2154 break;
2155 case ICmpInst::ICMP_SGT:
2156 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002157 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002158 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002159 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002160
2161 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2162 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2163 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2164 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2165 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2166 ConstantInt::get(CI->getContext(), CI->getValue()+1));
2167 }
2168 break;
2169 case ICmpInst::ICMP_SGE:
2170 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2171 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002172 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002173 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002174 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002175 break;
2176 case ICmpInst::ICMP_SLE:
2177 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2178 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002179 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002180 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002181 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002182 break;
2183 case ICmpInst::ICMP_UGE:
2184 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2185 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002186 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002187 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002188 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002189 break;
2190 case ICmpInst::ICMP_ULE:
2191 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2192 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002193 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002194 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002195 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002196 break;
2197 }
2198
2199 // Turn a signed comparison into an unsigned one if both operands
2200 // are known to have the same sign.
2201 if (I.isSigned() &&
2202 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2203 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2204 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2205 }
2206
2207 // Test if the ICmpInst instruction is used exclusively by a select as
2208 // part of a minimum or maximum operation. If so, refrain from doing
2209 // any other folding. This helps out other analyses which understand
2210 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2211 // and CodeGen. And in this case, at least one of the comparison
2212 // operands has at least one user besides the compare (the select),
2213 // which would often largely negate the benefit of folding anyway.
2214 if (I.hasOneUse())
2215 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2216 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2217 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2218 return 0;
2219
2220 // See if we are doing a comparison between a constant and an instruction that
2221 // can be folded into the comparison.
2222 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002223 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2224 // instruction, see if that instruction also has constants so that the
2225 // instruction can be folded into the icmp
Chris Lattner02446fc2010-01-04 07:37:31 +00002226 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2227 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2228 return Res;
2229 }
2230
2231 // Handle icmp with constant (but not simple integer constant) RHS
2232 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2233 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2234 switch (LHSI->getOpcode()) {
2235 case Instruction::GetElementPtr:
2236 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2237 if (RHSC->isNullValue() &&
2238 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2239 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2240 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2241 break;
2242 case Instruction::PHI:
2243 // Only fold icmp into the PHI if the phi and icmp are in the same
2244 // block. If in the same block, we're encouraging jump threading. If
2245 // not, we are just pessimizing the code by making an i1 phi.
2246 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002247 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002248 return NV;
2249 break;
2250 case Instruction::Select: {
2251 // If either operand of the select is a constant, we can fold the
2252 // comparison into the select arms, which will cause one to be
2253 // constant folded and the select turned into a bitwise or.
2254 Value *Op1 = 0, *Op2 = 0;
2255 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2256 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2257 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2258 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2259
2260 // We only want to perform this transformation if it will not lead to
2261 // additional code. This is true if either both sides of the select
2262 // fold to a constant (in which case the icmp is replaced with a select
2263 // which will usually simplify) or this is the only user of the
2264 // select (in which case we are trading a select+icmp for a simpler
2265 // select+icmp).
2266 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2267 if (!Op1)
2268 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2269 RHSC, I.getName());
2270 if (!Op2)
2271 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2272 RHSC, I.getName());
2273 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2274 }
2275 break;
2276 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002277 case Instruction::IntToPtr:
2278 // icmp pred inttoptr(X), null -> icmp pred X, 0
2279 if (RHSC->isNullValue() && TD &&
Chandler Carruthece6c6b2012-11-01 08:07:29 +00002280 TD->getIntPtrType(RHSC->getContext()) ==
Chris Lattner02446fc2010-01-04 07:37:31 +00002281 LHSI->getOperand(0)->getType())
2282 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2283 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2284 break;
2285
2286 case Instruction::Load:
2287 // Try to optimize things like "A[i] > 4" to index computations.
2288 if (GetElementPtrInst *GEP =
2289 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2290 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2291 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2292 !cast<LoadInst>(LHSI)->isVolatile())
2293 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2294 return Res;
2295 }
2296 break;
2297 }
2298 }
2299
2300 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2301 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2302 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2303 return NI;
2304 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2305 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2306 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2307 return NI;
2308
2309 // Test to see if the operands of the icmp are casted versions of other
2310 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
2311 // now.
2312 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002313 if (Op0->getType()->isPointerTy() &&
2314 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002315 // We keep moving the cast from the left operand over to the right
2316 // operand, where it can often be eliminated completely.
2317 Op0 = CI->getOperand(0);
2318
2319 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2320 // so eliminate it as well.
2321 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2322 Op1 = CI2->getOperand(0);
2323
2324 // If Op1 is a constant, we can fold the cast into the constant.
2325 if (Op0->getType() != Op1->getType()) {
2326 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2327 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2328 } else {
2329 // Otherwise, cast the RHS right before the icmp
2330 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2331 }
2332 }
2333 return new ICmpInst(I.getPredicate(), Op0, Op1);
2334 }
2335 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002336
Chris Lattner02446fc2010-01-04 07:37:31 +00002337 if (isa<CastInst>(Op0)) {
2338 // Handle the special case of: icmp (cast bool to X), <cst>
2339 // This comes up when you have code like
2340 // int X = A < B;
2341 // if (X) ...
2342 // For generality, we handle any zero-extension of any operand comparison
2343 // with a constant or another cast from the same type.
2344 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2345 if (Instruction *R = visitICmpInstWithCastAndCast(I))
2346 return R;
2347 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002348
Duncan Sandsa7724332011-02-17 07:46:37 +00002349 // Special logic for binary operators.
2350 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2351 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2352 if (BO0 || BO1) {
2353 CmpInst::Predicate Pred = I.getPredicate();
2354 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2355 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2356 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2357 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2358 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2359 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2360 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2361 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2362 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2363
2364 // Analyze the case when either Op0 or Op1 is an add instruction.
2365 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2366 Value *A = 0, *B = 0, *C = 0, *D = 0;
2367 if (BO0 && BO0->getOpcode() == Instruction::Add)
2368 A = BO0->getOperand(0), B = BO0->getOperand(1);
2369 if (BO1 && BO1->getOpcode() == Instruction::Add)
2370 C = BO1->getOperand(0), D = BO1->getOperand(1);
2371
2372 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2373 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2374 return new ICmpInst(Pred, A == Op1 ? B : A,
2375 Constant::getNullValue(Op1->getType()));
2376
2377 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2378 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2379 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2380 C == Op0 ? D : C);
2381
Duncan Sands39a7de72011-02-18 16:25:37 +00002382 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002383 if (A && C && (A == C || A == D || B == C || B == D) &&
2384 NoOp0WrapProblem && NoOp1WrapProblem &&
2385 // Try not to increase register pressure.
2386 BO0->hasOneUse() && BO1->hasOneUse()) {
2387 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsafe45392012-11-16 18:55:49 +00002388 Value *Y, *Z;
2389 if (A == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002390 // C + B == C + D -> B == D
Duncan Sandsafe45392012-11-16 18:55:49 +00002391 Y = B;
2392 Z = D;
2393 } else if (A == D) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002394 // D + B == C + D -> B == C
Duncan Sandsafe45392012-11-16 18:55:49 +00002395 Y = B;
2396 Z = C;
2397 } else if (B == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002398 // A + C == C + D -> A == D
Duncan Sandsafe45392012-11-16 18:55:49 +00002399 Y = A;
2400 Z = D;
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002401 } else {
2402 assert(B == D);
2403 // A + D == C + D -> A == C
Duncan Sandsafe45392012-11-16 18:55:49 +00002404 Y = A;
2405 Z = C;
2406 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002407 return new ICmpInst(Pred, Y, Z);
2408 }
2409
2410 // Analyze the case when either Op0 or Op1 is a sub instruction.
2411 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2412 A = 0; B = 0; C = 0; D = 0;
2413 if (BO0 && BO0->getOpcode() == Instruction::Sub)
2414 A = BO0->getOperand(0), B = BO0->getOperand(1);
2415 if (BO1 && BO1->getOpcode() == Instruction::Sub)
2416 C = BO1->getOperand(0), D = BO1->getOperand(1);
2417
Duncan Sands39a7de72011-02-18 16:25:37 +00002418 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2419 if (A == Op1 && NoOp0WrapProblem)
2420 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2421
2422 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2423 if (C == Op0 && NoOp1WrapProblem)
2424 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2425
2426 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002427 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2428 // Try not to increase register pressure.
2429 BO0->hasOneUse() && BO1->hasOneUse())
2430 return new ICmpInst(Pred, A, C);
2431
Duncan Sands39a7de72011-02-18 16:25:37 +00002432 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2433 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2434 // Try not to increase register pressure.
2435 BO0->hasOneUse() && BO1->hasOneUse())
2436 return new ICmpInst(Pred, D, B);
2437
Nick Lewycky9feda172011-03-05 04:28:48 +00002438 BinaryOperator *SRem = NULL;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002439 // icmp (srem X, Y), Y
Nick Lewycky9feda172011-03-05 04:28:48 +00002440 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2441 Op1 == BO0->getOperand(1))
2442 SRem = BO0;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002443 // icmp Y, (srem X, Y)
Nick Lewycky9feda172011-03-05 04:28:48 +00002444 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2445 Op0 == BO1->getOperand(1))
2446 SRem = BO1;
2447 if (SRem) {
2448 // We don't check hasOneUse to avoid increasing register pressure because
2449 // the value we use is the same value this instruction was already using.
2450 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2451 default: break;
2452 case ICmpInst::ICMP_EQ:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002453 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002454 case ICmpInst::ICMP_NE:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002455 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002456 case ICmpInst::ICMP_SGT:
2457 case ICmpInst::ICMP_SGE:
2458 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2459 Constant::getAllOnesValue(SRem->getType()));
2460 case ICmpInst::ICMP_SLT:
2461 case ICmpInst::ICMP_SLE:
2462 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2463 Constant::getNullValue(SRem->getType()));
2464 }
2465 }
2466
Duncan Sandsa7724332011-02-17 07:46:37 +00002467 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2468 BO0->hasOneUse() && BO1->hasOneUse() &&
2469 BO0->getOperand(1) == BO1->getOperand(1)) {
2470 switch (BO0->getOpcode()) {
2471 default: break;
2472 case Instruction::Add:
2473 case Instruction::Sub:
2474 case Instruction::Xor:
2475 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
2476 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2477 BO1->getOperand(0));
2478 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2479 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2480 if (CI->getValue().isSignBit()) {
2481 ICmpInst::Predicate Pred = I.isSigned()
2482 ? I.getUnsignedPredicate()
2483 : I.getSignedPredicate();
2484 return new ICmpInst(Pred, BO0->getOperand(0),
2485 BO1->getOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00002486 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002487
Chris Lattnerc73b24d2011-07-15 06:08:15 +00002488 if (CI->isMaxValue(true)) {
Duncan Sandsa7724332011-02-17 07:46:37 +00002489 ICmpInst::Predicate Pred = I.isSigned()
2490 ? I.getUnsignedPredicate()
2491 : I.getSignedPredicate();
2492 Pred = I.getSwappedPredicate(Pred);
2493 return new ICmpInst(Pred, BO0->getOperand(0),
2494 BO1->getOperand(0));
2495 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002496 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002497 break;
2498 case Instruction::Mul:
2499 if (!I.isEquality())
2500 break;
2501
2502 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2503 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2504 // Mask = -1 >> count-trailing-zeros(Cst).
2505 if (!CI->isZero() && !CI->isOne()) {
2506 const APInt &AP = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002507 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandsa7724332011-02-17 07:46:37 +00002508 APInt::getLowBitsSet(AP.getBitWidth(),
2509 AP.getBitWidth() -
2510 AP.countTrailingZeros()));
2511 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2512 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2513 return new ICmpInst(I.getPredicate(), And1, And2);
2514 }
2515 }
2516 break;
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002517 case Instruction::UDiv:
2518 case Instruction::LShr:
2519 if (I.isSigned())
2520 break;
2521 // fall-through
2522 case Instruction::SDiv:
2523 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002524 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002525 break;
2526 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2527 BO1->getOperand(0));
2528 case Instruction::Shl: {
2529 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2530 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2531 if (!NUW && !NSW)
2532 break;
2533 if (!NSW && I.isSigned())
2534 break;
2535 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2536 BO1->getOperand(0));
2537 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002538 }
2539 }
2540 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002541
Chris Lattner02446fc2010-01-04 07:37:31 +00002542 { Value *A, *B;
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002543 // ~x < ~y --> y < x
2544 // ~x < cst --> ~cst < x
2545 if (match(Op0, m_Not(m_Value(A)))) {
2546 if (match(Op1, m_Not(m_Value(B))))
2547 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner27a98482011-01-15 05:42:47 +00002548 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002549 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2550 }
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002551
2552 // (a+b) <u a --> llvm.uadd.with.overflow.
2553 // (a+b) <u b --> llvm.uadd.with.overflow.
2554 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002555 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002556 (Op1 == A || Op1 == B))
2557 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2558 return R;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002559
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002560 // a >u (a+b) --> llvm.uadd.with.overflow.
2561 // b >u (a+b) --> llvm.uadd.with.overflow.
2562 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2563 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2564 (Op0 == A || Op0 == B))
2565 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2566 return R;
Chris Lattner02446fc2010-01-04 07:37:31 +00002567 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002568
Chris Lattner02446fc2010-01-04 07:37:31 +00002569 if (I.isEquality()) {
2570 Value *A, *B, *C, *D;
Duncan Sands39a7de72011-02-18 16:25:37 +00002571
Chris Lattner02446fc2010-01-04 07:37:31 +00002572 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2573 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
2574 Value *OtherVal = A == Op1 ? B : A;
2575 return new ICmpInst(I.getPredicate(), OtherVal,
2576 Constant::getNullValue(A->getType()));
2577 }
2578
2579 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2580 // A^c1 == C^c2 --> A == C^(c1^c2)
2581 ConstantInt *C1, *C2;
2582 if (match(B, m_ConstantInt(C1)) &&
2583 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2584 Constant *NC = ConstantInt::get(I.getContext(),
2585 C1->getValue() ^ C2->getValue());
Benjamin Kramera9390a42011-09-27 20:39:19 +00002586 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner02446fc2010-01-04 07:37:31 +00002587 return new ICmpInst(I.getPredicate(), A, Xor);
2588 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002589
Chris Lattner02446fc2010-01-04 07:37:31 +00002590 // A^B == A^D -> B == D
2591 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2592 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2593 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2594 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2595 }
2596 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002597
Chris Lattner02446fc2010-01-04 07:37:31 +00002598 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2599 (A == Op0 || B == Op0)) {
2600 // A == (A^B) -> B == 0
2601 Value *OtherVal = A == Op0 ? B : A;
2602 return new ICmpInst(I.getPredicate(), OtherVal,
2603 Constant::getNullValue(A->getType()));
2604 }
2605
Chris Lattner02446fc2010-01-04 07:37:31 +00002606 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002607 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner5036ce42011-04-26 20:02:45 +00002608 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002609 Value *X = 0, *Y = 0, *Z = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002610
Chris Lattner02446fc2010-01-04 07:37:31 +00002611 if (A == C) {
2612 X = B; Y = D; Z = A;
2613 } else if (A == D) {
2614 X = B; Y = C; Z = A;
2615 } else if (B == C) {
2616 X = A; Y = D; Z = B;
2617 } else if (B == D) {
2618 X = A; Y = C; Z = B;
2619 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002620
Chris Lattner02446fc2010-01-04 07:37:31 +00002621 if (X) { // Build (X^Y) & Z
Benjamin Kramera9390a42011-09-27 20:39:19 +00002622 Op1 = Builder->CreateXor(X, Y);
2623 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner02446fc2010-01-04 07:37:31 +00002624 I.setOperand(0, Op1);
2625 I.setOperand(1, Constant::getNullValue(Op1->getType()));
2626 return &I;
2627 }
2628 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002629
Benjamin Kramer66821d92012-06-10 20:35:00 +00002630 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer7a99b462012-06-11 08:01:25 +00002631 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer66821d92012-06-10 20:35:00 +00002632 ConstantInt *Cst1;
Benjamin Kramer7a99b462012-06-11 08:01:25 +00002633 if ((Op0->hasOneUse() &&
2634 match(Op0, m_ZExt(m_Value(A))) &&
2635 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
2636 (Op1->hasOneUse() &&
2637 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
2638 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer66821d92012-06-10 20:35:00 +00002639 APInt Pow2 = Cst1->getValue() + 1;
2640 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
2641 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
2642 return new ICmpInst(I.getPredicate(), A,
2643 Builder->CreateTrunc(B, A->getType()));
2644 }
2645
Chris Lattner325eeb12011-04-26 20:18:20 +00002646 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2647 // "icmp (and X, mask), cst"
2648 uint64_t ShAmt = 0;
Chris Lattner325eeb12011-04-26 20:18:20 +00002649 if (Op0->hasOneUse() &&
2650 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2651 m_ConstantInt(ShAmt))))) &&
2652 match(Op1, m_ConstantInt(Cst1)) &&
2653 // Only do this when A has multiple uses. This is most important to do
2654 // when it exposes other optimizations.
2655 !A->hasOneUse()) {
2656 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002657
Chris Lattner325eeb12011-04-26 20:18:20 +00002658 if (ShAmt < ASize) {
2659 APInt MaskV =
2660 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2661 MaskV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002662
Chris Lattner325eeb12011-04-26 20:18:20 +00002663 APInt CmpV = Cst1->getValue().zext(ASize);
2664 CmpV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002665
Chris Lattner325eeb12011-04-26 20:18:20 +00002666 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2667 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2668 }
2669 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002670 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002671
Chris Lattner02446fc2010-01-04 07:37:31 +00002672 {
2673 Value *X; ConstantInt *Cst;
2674 // icmp X+Cst, X
2675 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
2676 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
2677
2678 // icmp X, X+Cst
2679 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
2680 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
2681 }
2682 return Changed ? &I : 0;
2683}
2684
2685
2686
2687
2688
2689
2690/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2691///
2692Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2693 Instruction *LHSI,
2694 Constant *RHSC) {
2695 if (!isa<ConstantFP>(RHSC)) return 0;
2696 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002697
Chris Lattner02446fc2010-01-04 07:37:31 +00002698 // Get the width of the mantissa. We don't want to hack on conversions that
2699 // might lose information from the integer, e.g. "i64 -> float"
2700 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2701 if (MantissaWidth == -1) return 0; // Unknown.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002702
Chris Lattner02446fc2010-01-04 07:37:31 +00002703 // Check to see that the input is converted from an integer type that is small
2704 // enough that preserves all bits. TODO: check here for "known" sign bits.
2705 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
2706 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002707
Chris Lattner02446fc2010-01-04 07:37:31 +00002708 // If this is a uitofp instruction, we need an extra bit to hold the sign.
2709 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
2710 if (LHSUnsigned)
2711 ++InputSize;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002712
Chris Lattner02446fc2010-01-04 07:37:31 +00002713 // If the conversion would lose info, don't hack on this.
2714 if ((int)InputSize > MantissaWidth)
2715 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002716
Chris Lattner02446fc2010-01-04 07:37:31 +00002717 // Otherwise, we can potentially simplify the comparison. We know that it
2718 // will always come through as an integer value and we know the constant is
2719 // not a NAN (it would have been previously simplified).
2720 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002721
Chris Lattner02446fc2010-01-04 07:37:31 +00002722 ICmpInst::Predicate Pred;
2723 switch (I.getPredicate()) {
2724 default: llvm_unreachable("Unexpected predicate!");
2725 case FCmpInst::FCMP_UEQ:
2726 case FCmpInst::FCMP_OEQ:
2727 Pred = ICmpInst::ICMP_EQ;
2728 break;
2729 case FCmpInst::FCMP_UGT:
2730 case FCmpInst::FCMP_OGT:
2731 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
2732 break;
2733 case FCmpInst::FCMP_UGE:
2734 case FCmpInst::FCMP_OGE:
2735 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
2736 break;
2737 case FCmpInst::FCMP_ULT:
2738 case FCmpInst::FCMP_OLT:
2739 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
2740 break;
2741 case FCmpInst::FCMP_ULE:
2742 case FCmpInst::FCMP_OLE:
2743 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
2744 break;
2745 case FCmpInst::FCMP_UNE:
2746 case FCmpInst::FCMP_ONE:
2747 Pred = ICmpInst::ICMP_NE;
2748 break;
2749 case FCmpInst::FCMP_ORD:
2750 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2751 case FCmpInst::FCMP_UNO:
2752 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2753 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002754
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002755 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002756
Chris Lattner02446fc2010-01-04 07:37:31 +00002757 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002758
Chris Lattner02446fc2010-01-04 07:37:31 +00002759 // See if the FP constant is too large for the integer. For example,
2760 // comparing an i8 to 300.0.
2761 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002762
Chris Lattner02446fc2010-01-04 07:37:31 +00002763 if (!LHSUnsigned) {
2764 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
2765 // and large values.
2766 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
2767 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
2768 APFloat::rmNearestTiesToEven);
2769 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
2770 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
2771 Pred == ICmpInst::ICMP_SLE)
2772 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2773 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2774 }
2775 } else {
2776 // If the RHS value is > UnsignedMax, fold the comparison. This handles
2777 // +INF and large values.
2778 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
2779 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
2780 APFloat::rmNearestTiesToEven);
2781 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
2782 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
2783 Pred == ICmpInst::ICMP_ULE)
2784 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2785 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2786 }
2787 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002788
Chris Lattner02446fc2010-01-04 07:37:31 +00002789 if (!LHSUnsigned) {
2790 // See if the RHS value is < SignedMin.
2791 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2792 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
2793 APFloat::rmNearestTiesToEven);
2794 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
2795 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
2796 Pred == ICmpInst::ICMP_SGE)
2797 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2798 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2799 }
Devang Patela2e0f6b2012-02-13 23:05:18 +00002800 } else {
2801 // See if the RHS value is < UnsignedMin.
2802 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2803 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
2804 APFloat::rmNearestTiesToEven);
2805 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
2806 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
2807 Pred == ICmpInst::ICMP_UGE)
2808 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2809 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2810 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002811 }
2812
2813 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
2814 // [0, UMAX], but it may still be fractional. See if it is fractional by
2815 // casting the FP value to the integer value and back, checking for equality.
2816 // Don't do this for zero, because -0.0 is not fractional.
2817 Constant *RHSInt = LHSUnsigned
2818 ? ConstantExpr::getFPToUI(RHSC, IntTy)
2819 : ConstantExpr::getFPToSI(RHSC, IntTy);
2820 if (!RHS.isZero()) {
2821 bool Equal = LHSUnsigned
2822 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
2823 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
2824 if (!Equal) {
2825 // If we had a comparison against a fractional value, we have to adjust
2826 // the compare predicate and sometimes the value. RHSC is rounded towards
2827 // zero at this point.
2828 switch (Pred) {
2829 default: llvm_unreachable("Unexpected integer comparison!");
2830 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
2831 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2832 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
2833 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2834 case ICmpInst::ICMP_ULE:
2835 // (float)int <= 4.4 --> int <= 4
2836 // (float)int <= -4.4 --> false
2837 if (RHS.isNegative())
2838 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2839 break;
2840 case ICmpInst::ICMP_SLE:
2841 // (float)int <= 4.4 --> int <= 4
2842 // (float)int <= -4.4 --> int < -4
2843 if (RHS.isNegative())
2844 Pred = ICmpInst::ICMP_SLT;
2845 break;
2846 case ICmpInst::ICMP_ULT:
2847 // (float)int < -4.4 --> false
2848 // (float)int < 4.4 --> int <= 4
2849 if (RHS.isNegative())
2850 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2851 Pred = ICmpInst::ICMP_ULE;
2852 break;
2853 case ICmpInst::ICMP_SLT:
2854 // (float)int < -4.4 --> int < -4
2855 // (float)int < 4.4 --> int <= 4
2856 if (!RHS.isNegative())
2857 Pred = ICmpInst::ICMP_SLE;
2858 break;
2859 case ICmpInst::ICMP_UGT:
2860 // (float)int > 4.4 --> int > 4
2861 // (float)int > -4.4 --> true
2862 if (RHS.isNegative())
2863 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2864 break;
2865 case ICmpInst::ICMP_SGT:
2866 // (float)int > 4.4 --> int > 4
2867 // (float)int > -4.4 --> int >= -4
2868 if (RHS.isNegative())
2869 Pred = ICmpInst::ICMP_SGE;
2870 break;
2871 case ICmpInst::ICMP_UGE:
2872 // (float)int >= -4.4 --> true
2873 // (float)int >= 4.4 --> int > 4
Bob Wilsonf12c95a2012-08-07 22:35:16 +00002874 if (RHS.isNegative())
Chris Lattner02446fc2010-01-04 07:37:31 +00002875 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2876 Pred = ICmpInst::ICMP_UGT;
2877 break;
2878 case ICmpInst::ICMP_SGE:
2879 // (float)int >= -4.4 --> int >= -4
2880 // (float)int >= 4.4 --> int > 4
2881 if (!RHS.isNegative())
2882 Pred = ICmpInst::ICMP_SGT;
2883 break;
2884 }
2885 }
2886 }
2887
2888 // Lower this FP comparison into an appropriate integer version of the
2889 // comparison.
2890 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
2891}
2892
2893Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
2894 bool Changed = false;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002895
Chris Lattner02446fc2010-01-04 07:37:31 +00002896 /// Orders the operands of the compare so that they are listed from most
2897 /// complex to least complex. This puts constants before unary operators,
2898 /// before binary operators.
2899 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
2900 I.swapOperands();
2901 Changed = true;
2902 }
2903
2904 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002905
Chris Lattner02446fc2010-01-04 07:37:31 +00002906 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
2907 return ReplaceInstUsesWith(I, V);
2908
2909 // Simplify 'fcmp pred X, X'
2910 if (Op0 == Op1) {
2911 switch (I.getPredicate()) {
2912 default: llvm_unreachable("Unknown predicate!");
2913 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
2914 case FCmpInst::FCMP_ULT: // True if unordered or less than
2915 case FCmpInst::FCMP_UGT: // True if unordered or greater than
2916 case FCmpInst::FCMP_UNE: // True if unordered or not equal
2917 // Canonicalize these to be 'fcmp uno %X, 0.0'.
2918 I.setPredicate(FCmpInst::FCMP_UNO);
2919 I.setOperand(1, Constant::getNullValue(Op0->getType()));
2920 return &I;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002921
Chris Lattner02446fc2010-01-04 07:37:31 +00002922 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
2923 case FCmpInst::FCMP_OEQ: // True if ordered and equal
2924 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
2925 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
2926 // Canonicalize these to be 'fcmp ord %X, 0.0'.
2927 I.setPredicate(FCmpInst::FCMP_ORD);
2928 I.setOperand(1, Constant::getNullValue(Op0->getType()));
2929 return &I;
2930 }
2931 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002932
Chris Lattner02446fc2010-01-04 07:37:31 +00002933 // Handle fcmp with constant RHS
2934 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2935 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2936 switch (LHSI->getOpcode()) {
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002937 case Instruction::FPExt: {
2938 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
2939 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
2940 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
2941 if (!RHSF)
2942 break;
2943
2944 const fltSemantics *Sem;
2945 // FIXME: This shouldn't be here.
Dan Gohmance163392011-12-17 00:04:22 +00002946 if (LHSExt->getSrcTy()->isHalfTy())
2947 Sem = &APFloat::IEEEhalf;
2948 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002949 Sem = &APFloat::IEEEsingle;
2950 else if (LHSExt->getSrcTy()->isDoubleTy())
2951 Sem = &APFloat::IEEEdouble;
2952 else if (LHSExt->getSrcTy()->isFP128Ty())
2953 Sem = &APFloat::IEEEquad;
2954 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
2955 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand3467b9f2012-10-30 12:33:18 +00002956 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
2957 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002958 else
2959 break;
2960
2961 bool Lossy;
2962 APFloat F = RHSF->getValueAPF();
2963 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
2964
Jim Grosbachcbf676b2011-09-30 18:45:50 +00002965 // Avoid lossy conversions and denormals. Zero is a special case
2966 // that's OK to convert.
Jim Grosbach68e05fb2011-09-30 19:58:46 +00002967 APFloat Fabs = F;
2968 Fabs.clearSign();
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002969 if (!Lossy &&
Jim Grosbach68e05fb2011-09-30 19:58:46 +00002970 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
2971 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbachcbf676b2011-09-30 18:45:50 +00002972
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002973 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
2974 ConstantFP::get(RHSC->getContext(), F));
2975 break;
2976 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002977 case Instruction::PHI:
2978 // Only fold fcmp into the PHI if the phi and fcmp are in the same
2979 // block. If in the same block, we're encouraging jump threading. If
2980 // not, we are just pessimizing the code by making an i1 phi.
2981 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002982 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002983 return NV;
2984 break;
2985 case Instruction::SIToFP:
2986 case Instruction::UIToFP:
2987 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
2988 return NV;
2989 break;
2990 case Instruction::Select: {
2991 // If either operand of the select is a constant, we can fold the
2992 // comparison into the select arms, which will cause one to be
2993 // constant folded and the select turned into a bitwise or.
2994 Value *Op1 = 0, *Op2 = 0;
2995 if (LHSI->hasOneUse()) {
2996 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2997 // Fold the known value into the constant operand.
2998 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2999 // Insert a new FCmp of the other select operand.
3000 Op2 = Builder->CreateFCmp(I.getPredicate(),
3001 LHSI->getOperand(2), RHSC, I.getName());
3002 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3003 // Fold the known value into the constant operand.
3004 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3005 // Insert a new FCmp of the other select operand.
3006 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
3007 RHSC, I.getName());
3008 }
3009 }
3010
3011 if (Op1)
3012 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3013 break;
3014 }
Benjamin Kramer0db50182011-03-31 10:12:15 +00003015 case Instruction::FSub: {
3016 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3017 Value *Op;
3018 if (match(LHSI, m_FNeg(m_Value(Op))))
3019 return new FCmpInst(I.getSwappedPredicate(), Op,
3020 ConstantExpr::getFNeg(RHSC));
3021 break;
3022 }
Dan Gohman39516a62010-02-24 06:46:09 +00003023 case Instruction::Load:
3024 if (GetElementPtrInst *GEP =
3025 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3026 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3027 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3028 !cast<LoadInst>(LHSI)->isVolatile())
3029 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3030 return Res;
3031 }
3032 break;
Benjamin Kramer00abcd32012-08-18 20:06:47 +00003033 case Instruction::Call: {
3034 CallInst *CI = cast<CallInst>(LHSI);
3035 LibFunc::Func Func;
3036 // Various optimization for fabs compared with zero.
Benjamin Kramera4b57172012-08-18 22:04:34 +00003037 if (RHSC->isNullValue() && CI->getCalledFunction() &&
Benjamin Kramer00abcd32012-08-18 20:06:47 +00003038 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3039 TLI->has(Func)) {
3040 if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3041 Func == LibFunc::fabsl) {
3042 switch (I.getPredicate()) {
3043 default: break;
3044 // fabs(x) < 0 --> false
3045 case FCmpInst::FCMP_OLT:
3046 return ReplaceInstUsesWith(I, Builder->getFalse());
3047 // fabs(x) > 0 --> x != 0
3048 case FCmpInst::FCMP_OGT:
3049 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3050 RHSC);
3051 // fabs(x) <= 0 --> x == 0
3052 case FCmpInst::FCMP_OLE:
3053 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3054 RHSC);
3055 // fabs(x) >= 0 --> !isnan(x)
3056 case FCmpInst::FCMP_OGE:
3057 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3058 RHSC);
3059 // fabs(x) == 0 --> x == 0
3060 // fabs(x) != 0 --> x != 0
3061 case FCmpInst::FCMP_OEQ:
3062 case FCmpInst::FCMP_UEQ:
3063 case FCmpInst::FCMP_ONE:
3064 case FCmpInst::FCMP_UNE:
3065 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3066 RHSC);
3067 }
3068 }
3069 }
3070 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003071 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003072 }
3073
Benjamin Kramer00e00d62011-03-31 10:46:03 +00003074 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00003075 Value *X, *Y;
3076 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramer00e00d62011-03-31 10:46:03 +00003077 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00003078
Benjamin Kramercd0274c2011-03-31 10:11:58 +00003079 // fcmp (fpext x), (fpext y) -> fcmp x, y
3080 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3081 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3082 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3083 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3084 RHSExt->getOperand(0));
3085
Chris Lattner02446fc2010-01-04 07:37:31 +00003086 return Changed ? &I : 0;
3087}