blob: 2c292ce29d0a22e99bb2044f59b2914889b52286 [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
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +0000142/// Returns true if the exploded icmp can be expressed as a signed comparison
143/// to zero and updates the predicate accordingly.
144/// The signedness of the comparison is preserved.
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +0000145static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
146 if (!ICmpInst::isSigned(pred))
147 return false;
148
149 if (RHS->isZero())
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +0000150 return ICmpInst::isRelational(pred);
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +0000151
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +0000152 if (RHS->isOne()) {
153 if (pred == ICmpInst::ICMP_SLT) {
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +0000154 pred = ICmpInst::ICMP_SLE;
155 return true;
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +0000156 }
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +0000157 } else if (RHS->isAllOnesValue()) {
158 if (pred == ICmpInst::ICMP_SGT) {
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +0000159 pred = ICmpInst::ICMP_SGE;
160 return true;
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +0000161 }
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +0000162 }
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +0000163
164 return false;
165}
166
Chris Lattner02446fc2010-01-04 07:37:31 +0000167// isHighOnes - Return true if the constant is of the form 1+0+.
168// This is the same as lowones(~X).
169static bool isHighOnes(const ConstantInt *CI) {
170 return (~CI->getValue() + 1).isPowerOf2();
171}
172
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000173/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
Chris Lattner02446fc2010-01-04 07:37:31 +0000174/// set of known zero and one bits, compute the maximum and minimum values that
175/// could have the specified known zero and known one bits, returning them in
176/// min/max.
177static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
178 const APInt& KnownOne,
179 APInt& Min, APInt& Max) {
180 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
181 KnownZero.getBitWidth() == Min.getBitWidth() &&
182 KnownZero.getBitWidth() == Max.getBitWidth() &&
183 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
184 APInt UnknownBits = ~(KnownZero|KnownOne);
185
186 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
187 // bit if it is unknown.
188 Min = KnownOne;
189 Max = KnownOne|UnknownBits;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000190
Chris Lattner02446fc2010-01-04 07:37:31 +0000191 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad7a874dd2010-12-01 08:53:58 +0000192 Min.setBit(Min.getBitWidth()-1);
193 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner02446fc2010-01-04 07:37:31 +0000194 }
195}
196
197// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
198// a set of known zero and one bits, compute the maximum and minimum values that
199// could have the specified known zero and known one bits, returning them in
200// min/max.
201static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
202 const APInt &KnownOne,
203 APInt &Min, APInt &Max) {
204 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
205 KnownZero.getBitWidth() == Min.getBitWidth() &&
206 KnownZero.getBitWidth() == Max.getBitWidth() &&
207 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
208 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000209
Chris Lattner02446fc2010-01-04 07:37:31 +0000210 // The minimum value is when the unknown bits are all zeros.
211 Min = KnownOne;
212 // The maximum value is when the unknown bits are all ones.
213 Max = KnownOne|UnknownBits;
214}
215
216
217
218/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
219/// cmp pred (load (gep GV, ...)), cmpcst
220/// where GV is a global variable with a constant initializer. Try to simplify
221/// this into some simple computation that does not need the load. For example
222/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
223///
224/// If AndCst is non-null, then the loaded value is masked with that constant
225/// before doing the comparison. This handles cases like "A[i]&4 == 0".
226Instruction *InstCombiner::
227FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
228 CmpInst &ICI, ConstantInt *AndCst) {
Matt Arsenault89062b82013-08-19 21:40:31 +0000229 // We need TD information to know the pointer size unless this is inbounds.
230 if (!GEP->isInBounds() && TD == 0)
Matt Arsenaulta630cb02013-08-15 23:11:07 +0000231 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000232
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000233 Constant *Init = GV->getInitializer();
234 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
235 return 0;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000236
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000237 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
238 if (ArrayElementCount > 1024) return 0; // Don't blow up on huge arrays.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000239
Chris Lattner02446fc2010-01-04 07:37:31 +0000240 // There are many forms of this optimization we can handle, for now, just do
241 // the simple index into a single-dimensional array.
242 //
243 // Require: GEP GV, 0, i {{, constant indices}}
244 if (GEP->getNumOperands() < 3 ||
245 !isa<ConstantInt>(GEP->getOperand(1)) ||
246 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
247 isa<Constant>(GEP->getOperand(2)))
248 return 0;
249
250 // Check that indices after the variable are constants and in-range for the
251 // type they index. Collect the indices. This is typically for arrays of
252 // structs.
253 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000254
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000255 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner02446fc2010-01-04 07:37:31 +0000256 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
257 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
258 if (Idx == 0) return 0; // Variable index.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000259
Chris Lattner02446fc2010-01-04 07:37:31 +0000260 uint64_t IdxVal = Idx->getZExtValue();
261 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000262
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000263 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner02446fc2010-01-04 07:37:31 +0000264 EltTy = STy->getElementType(IdxVal);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000265 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000266 if (IdxVal >= ATy->getNumElements()) return 0;
267 EltTy = ATy->getElementType();
268 } else {
269 return 0; // Unknown type.
270 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000271
Chris Lattner02446fc2010-01-04 07:37:31 +0000272 LaterIndices.push_back(IdxVal);
273 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000274
Chris Lattner02446fc2010-01-04 07:37:31 +0000275 enum { Overdefined = -3, Undefined = -2 };
276
277 // Variables for our state machines.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000278
Chris Lattner02446fc2010-01-04 07:37:31 +0000279 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
280 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
281 // and 87 is the second (and last) index. FirstTrueElement is -2 when
282 // undefined, otherwise set to the first true element. SecondTrueElement is
283 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
284 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
285
286 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
287 // form "i != 47 & i != 87". Same state transitions as for true elements.
288 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000289
Chris Lattner02446fc2010-01-04 07:37:31 +0000290 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
291 /// define a state machine that triggers for ranges of values that the index
292 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
293 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
294 /// index in the range (inclusive). We use -2 for undefined here because we
295 /// use relative comparisons and don't want 0-1 to match -1.
296 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000297
Chris Lattner02446fc2010-01-04 07:37:31 +0000298 // MagicBitvector - This is a magic bitvector where we set a bit if the
299 // comparison is true for element 'i'. If there are 64 elements or less in
300 // the array, this will fully represent all the comparison results.
301 uint64_t MagicBitvector = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000302
303
Chris Lattner02446fc2010-01-04 07:37:31 +0000304 // Scan the array and see if one of our patterns matches.
305 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000306 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
307 Constant *Elt = Init->getAggregateElement(i);
308 if (Elt == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000309
Chris Lattner02446fc2010-01-04 07:37:31 +0000310 // If this is indexing an array of structures, get the structure element.
311 if (!LaterIndices.empty())
Jay Foadfc6d3a42011-07-13 10:26:04 +0000312 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000313
Chris Lattner02446fc2010-01-04 07:37:31 +0000314 // If the element is masked, handle it.
315 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000316
Chris Lattner02446fc2010-01-04 07:37:31 +0000317 // Find out if the comparison would be true or false for the i'th element.
318 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Chad Rosieraab8e282011-12-02 01:26:24 +0000319 CompareRHS, TD, TLI);
Chris Lattner02446fc2010-01-04 07:37:31 +0000320 // If the result is undef for this element, ignore it.
321 if (isa<UndefValue>(C)) {
322 // Extend range state machines to cover this element in case there is an
323 // undef in the middle of the range.
324 if (TrueRangeEnd == (int)i-1)
325 TrueRangeEnd = i;
326 if (FalseRangeEnd == (int)i-1)
327 FalseRangeEnd = i;
328 continue;
329 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000330
Chris Lattner02446fc2010-01-04 07:37:31 +0000331 // If we can't compute the result for any of the elements, we have to give
332 // up evaluating the entire conditional.
333 if (!isa<ConstantInt>(C)) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000334
Chris Lattner02446fc2010-01-04 07:37:31 +0000335 // Otherwise, we know if the comparison is true or false for this element,
336 // update our state machines.
337 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000338
Chris Lattner02446fc2010-01-04 07:37:31 +0000339 // State machine for single/double/range index comparison.
340 if (IsTrueForElt) {
341 // Update the TrueElement state machine.
342 if (FirstTrueElement == Undefined)
343 FirstTrueElement = TrueRangeEnd = i; // First true element.
344 else {
345 // Update double-compare state machine.
346 if (SecondTrueElement == Undefined)
347 SecondTrueElement = i;
348 else
349 SecondTrueElement = Overdefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000350
Chris Lattner02446fc2010-01-04 07:37:31 +0000351 // Update range state machine.
352 if (TrueRangeEnd == (int)i-1)
353 TrueRangeEnd = i;
354 else
355 TrueRangeEnd = Overdefined;
356 }
357 } else {
358 // Update the FalseElement state machine.
359 if (FirstFalseElement == Undefined)
360 FirstFalseElement = FalseRangeEnd = i; // First false element.
361 else {
362 // Update double-compare state machine.
363 if (SecondFalseElement == Undefined)
364 SecondFalseElement = i;
365 else
366 SecondFalseElement = Overdefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000367
Chris Lattner02446fc2010-01-04 07:37:31 +0000368 // Update range state machine.
369 if (FalseRangeEnd == (int)i-1)
370 FalseRangeEnd = i;
371 else
372 FalseRangeEnd = Overdefined;
373 }
374 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000375
376
Chris Lattner02446fc2010-01-04 07:37:31 +0000377 // If this element is in range, update our magic bitvector.
378 if (i < 64 && IsTrueForElt)
379 MagicBitvector |= 1ULL << i;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000380
Chris Lattner02446fc2010-01-04 07:37:31 +0000381 // If all of our states become overdefined, bail out early. Since the
382 // predicate is expensive, only check it every 8 elements. This is only
383 // really useful for really huge arrays.
384 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
385 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
386 FalseRangeEnd == Overdefined)
387 return 0;
388 }
389
390 // Now that we've scanned the entire array, emit our new comparison(s). We
391 // order the state machines in complexity of the generated code.
392 Value *Idx = GEP->getOperand(2);
393
Matt Arsenault89062b82013-08-19 21:40:31 +0000394 // If the index is larger than the pointer size of the target, truncate the
395 // index down like the GEP would do implicitly. We don't have to do this for
396 // an inbounds GEP because the index can't be out of range.
397 if (!GEP->isInBounds() &&
398 Idx->getType()->getPrimitiveSizeInBits() > TD->getPointerSizeInBits())
399 Idx = Builder->CreateTrunc(Idx, TD->getIntPtrType(Idx->getContext()));
400
Chris Lattner02446fc2010-01-04 07:37:31 +0000401 // If the comparison is only true for one or two elements, emit direct
402 // comparisons.
403 if (SecondTrueElement != Overdefined) {
404 // None true -> false.
405 if (FirstTrueElement == Undefined)
Jakub Staszak3facc432013-06-06 20:18:46 +0000406 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000407
Chris Lattner02446fc2010-01-04 07:37:31 +0000408 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000409
Chris Lattner02446fc2010-01-04 07:37:31 +0000410 // True for one element -> 'i == 47'.
411 if (SecondTrueElement == Undefined)
412 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000413
Chris Lattner02446fc2010-01-04 07:37:31 +0000414 // True for two elements -> 'i == 47 | i == 72'.
415 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
416 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
417 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
418 return BinaryOperator::CreateOr(C1, C2);
419 }
420
421 // If the comparison is only false for one or two elements, emit direct
422 // comparisons.
423 if (SecondFalseElement != Overdefined) {
424 // None false -> true.
425 if (FirstFalseElement == Undefined)
Jakub Staszak3facc432013-06-06 20:18:46 +0000426 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000427
Chris Lattner02446fc2010-01-04 07:37:31 +0000428 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
429
430 // False for one element -> 'i != 47'.
431 if (SecondFalseElement == Undefined)
432 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000433
Chris Lattner02446fc2010-01-04 07:37:31 +0000434 // False for two elements -> 'i != 47 & i != 72'.
435 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
436 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
437 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
438 return BinaryOperator::CreateAnd(C1, C2);
439 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000440
Chris Lattner02446fc2010-01-04 07:37:31 +0000441 // If the comparison can be replaced with a range comparison for the elements
442 // where it is true, emit the range check.
443 if (TrueRangeEnd != Overdefined) {
444 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000445
Chris Lattner02446fc2010-01-04 07:37:31 +0000446 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
447 if (FirstTrueElement) {
448 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
449 Idx = Builder->CreateAdd(Idx, Offs);
450 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000451
Chris Lattner02446fc2010-01-04 07:37:31 +0000452 Value *End = ConstantInt::get(Idx->getType(),
453 TrueRangeEnd-FirstTrueElement+1);
454 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
455 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000456
Chris Lattner02446fc2010-01-04 07:37:31 +0000457 // False range check.
458 if (FalseRangeEnd != Overdefined) {
459 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
460 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
461 if (FirstFalseElement) {
462 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
463 Idx = Builder->CreateAdd(Idx, Offs);
464 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000465
Chris Lattner02446fc2010-01-04 07:37:31 +0000466 Value *End = ConstantInt::get(Idx->getType(),
467 FalseRangeEnd-FirstFalseElement);
468 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
469 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000470
471
Arnaud A. de Grandmaison2be921a2013-03-22 08:25:01 +0000472 // If a magic bitvector captures the entire comparison state
Chris Lattner02446fc2010-01-04 07:37:31 +0000473 // of this load, replace it with computation that does:
474 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaison2be921a2013-03-22 08:25:01 +0000475 {
476 Type *Ty = 0;
477
478 // Look for an appropriate type:
479 // - The type of Idx if the magic fits
480 // - The smallest fitting legal type if we have a DataLayout
481 // - Default to i32
482 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
483 Ty = Idx->getType();
484 else if (TD)
485 Ty = TD->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
486 else if (ArrayElementCount <= 32)
Chris Lattner02446fc2010-01-04 07:37:31 +0000487 Ty = Type::getInt32Ty(Init->getContext());
Arnaud A. de Grandmaison2be921a2013-03-22 08:25:01 +0000488
489 if (Ty != 0) {
490 Value *V = Builder->CreateIntCast(Idx, Ty, false);
491 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
492 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
493 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
494 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000495 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000496
Chris Lattner02446fc2010-01-04 07:37:31 +0000497 return 0;
498}
499
500
501/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
502/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
503/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
504/// be complex, and scales are involved. The above expression would also be
505/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
506/// This later form is less amenable to optimization though, and we are allowed
507/// to generate the first by knowing that pointer arithmetic doesn't overflow.
508///
509/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000510///
Eli Friedman107ffd52011-05-18 23:11:30 +0000511static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000512 DataLayout &TD = *IC.getDataLayout();
Chris Lattner02446fc2010-01-04 07:37:31 +0000513 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000514
Chris Lattner02446fc2010-01-04 07:37:31 +0000515 // Check to see if this gep only has a single variable index. If so, and if
516 // any constant indices are a multiple of its scale, then we can compute this
517 // in terms of the scale of the variable index. For example, if the GEP
518 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
519 // because the expression will cross zero at the same point.
520 unsigned i, e = GEP->getNumOperands();
521 int64_t Offset = 0;
522 for (i = 1; i != e; ++i, ++GTI) {
523 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
524 // Compute the aggregate offset of constant indices.
525 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000526
Chris Lattner02446fc2010-01-04 07:37:31 +0000527 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000528 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000529 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
530 } else {
531 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
532 Offset += Size*CI->getSExtValue();
533 }
534 } else {
535 // Found our variable index.
536 break;
537 }
538 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000539
Chris Lattner02446fc2010-01-04 07:37:31 +0000540 // If there are no variable indices, we must have a constant offset, just
541 // evaluate it the general way.
542 if (i == e) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000543
Chris Lattner02446fc2010-01-04 07:37:31 +0000544 Value *VariableIdx = GEP->getOperand(i);
545 // Determine the scale factor of the variable element. For example, this is
546 // 4 if the variable index is into an array of i32.
547 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000548
Chris Lattner02446fc2010-01-04 07:37:31 +0000549 // Verify that there are no other variable indices. If so, emit the hard way.
550 for (++i, ++GTI; i != e; ++i, ++GTI) {
551 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
552 if (!CI) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000553
Chris Lattner02446fc2010-01-04 07:37:31 +0000554 // Compute the aggregate offset of constant indices.
555 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000556
Chris Lattner02446fc2010-01-04 07:37:31 +0000557 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000558 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000559 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
560 } else {
561 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
562 Offset += Size*CI->getSExtValue();
563 }
564 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000565
Matt Arsenault52c7d8e2013-08-21 19:53:10 +0000566
567
Chris Lattner02446fc2010-01-04 07:37:31 +0000568 // Okay, we know we have a single variable index, which must be a
569 // pointer/array/vector index. If there is no offset, life is simple, return
570 // the index.
Matt Arsenault52c7d8e2013-08-21 19:53:10 +0000571 Type *IntPtrTy = TD.getIntPtrType(GEP->getOperand(0)->getType());
572 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner02446fc2010-01-04 07:37:31 +0000573 if (Offset == 0) {
574 // Cast to intptrty in case a truncation occurs. If an extension is needed,
575 // we don't need to bother extending: the extension won't affect where the
576 // computation crosses zero.
Eli Friedman107ffd52011-05-18 23:11:30 +0000577 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman107ffd52011-05-18 23:11:30 +0000578 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
579 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000580 return VariableIdx;
581 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000582
Chris Lattner02446fc2010-01-04 07:37:31 +0000583 // Otherwise, there is an index. The computation we will do will be modulo
584 // the pointer size, so get it.
585 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000586
Chris Lattner02446fc2010-01-04 07:37:31 +0000587 Offset &= PtrSizeMask;
588 VariableScale &= PtrSizeMask;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000589
Chris Lattner02446fc2010-01-04 07:37:31 +0000590 // To do this transformation, any constant index must be a multiple of the
591 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
592 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
593 // multiple of the variable scale.
594 int64_t NewOffs = Offset / (int64_t)VariableScale;
595 if (Offset != NewOffs*(int64_t)VariableScale)
596 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000597
Chris Lattner02446fc2010-01-04 07:37:31 +0000598 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner02446fc2010-01-04 07:37:31 +0000599 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman107ffd52011-05-18 23:11:30 +0000600 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
601 true /*Signed*/);
Chris Lattner02446fc2010-01-04 07:37:31 +0000602 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman107ffd52011-05-18 23:11:30 +0000603 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner02446fc2010-01-04 07:37:31 +0000604}
605
606/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
607/// else. At this point we know that the GEP is on the LHS of the comparison.
608Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
609 ICmpInst::Predicate Cond,
610 Instruction &I) {
Benjamin Kramer8294eb52012-02-21 13:31:09 +0000611 // Don't transform signed compares of GEPs into index compares. Even if the
612 // GEP is inbounds, the final add of the base pointer can have signed overflow
613 // and would change the result of the icmp.
614 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramera42d5c42012-02-21 13:40:06 +0000615 // the maximum signed value for the pointer type.
Benjamin Kramer8294eb52012-02-21 13:31:09 +0000616 if (ICmpInst::isSigned(Cond))
617 return 0;
618
Chris Lattner02446fc2010-01-04 07:37:31 +0000619 // Look through bitcasts.
620 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
621 RHS = BCI->getOperand(0);
622
623 Value *PtrBase = GEPLHS->getOperand(0);
624 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
625 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
626 // This transformation (ignoring the base and scales) is valid because we
627 // know pointers can't overflow since the gep is inbounds. See if we can
628 // output an optimized form.
Eli Friedman107ffd52011-05-18 23:11:30 +0000629 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000630
Chris Lattner02446fc2010-01-04 07:37:31 +0000631 // If not, synthesize the offset the hard way.
632 if (Offset == 0)
633 Offset = EmitGEPOffset(GEPLHS);
634 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
635 Constant::getNullValue(Offset->getType()));
636 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
637 // If the base pointers are different, but the indices are the same, just
638 // compare the base pointer.
639 if (PtrBase != GEPRHS->getOperand(0)) {
640 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
641 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
642 GEPRHS->getOperand(0)->getType();
643 if (IndicesTheSame)
644 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
645 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
646 IndicesTheSame = false;
647 break;
648 }
649
650 // If all indices are the same, just compare the base pointers.
651 if (IndicesTheSame)
David Majnemerc22a4ee2013-06-29 10:28:04 +0000652 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +0000653
Benjamin Kramer9bb40852012-02-20 15:07:47 +0000654 // If we're comparing GEPs with two base pointers that only differ in type
655 // and both GEPs have only constant indices or just one use, then fold
656 // the compare with the adjusted indices.
Benjamin Kramer6ad48f42012-02-20 18:45:10 +0000657 if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer9bb40852012-02-20 15:07:47 +0000658 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
659 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
660 PtrBase->stripPointerCasts() ==
661 GEPRHS->getOperand(0)->stripPointerCasts()) {
662 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
663 EmitGEPOffset(GEPLHS),
664 EmitGEPOffset(GEPRHS));
665 return ReplaceInstUsesWith(I, Cmp);
666 }
667
Chris Lattner02446fc2010-01-04 07:37:31 +0000668 // Otherwise, the base pointers are different and the indices are
669 // different, bail out.
670 return 0;
671 }
672
673 // If one of the GEPs has all zero indices, recurse.
674 bool AllZeros = true;
675 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
676 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
677 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
678 AllZeros = false;
679 break;
680 }
681 if (AllZeros)
682 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemerdf703252013-06-29 09:45:35 +0000683 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner02446fc2010-01-04 07:37:31 +0000684
685 // If the other GEP has all zero indices, recurse.
686 AllZeros = true;
687 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
688 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
689 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
690 AllZeros = false;
691 break;
692 }
693 if (AllZeros)
694 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
695
Stuart Hastings67f071e2011-05-14 05:55:10 +0000696 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner02446fc2010-01-04 07:37:31 +0000697 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
698 // If the GEPs only differ by one index, compare it.
699 unsigned NumDifferences = 0; // Keep track of # differences.
700 unsigned DiffOperand = 0; // The operand that differs.
701 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
702 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
703 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
704 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
705 // Irreconcilable differences.
706 NumDifferences = 2;
707 break;
708 } else {
709 if (NumDifferences++) break;
710 DiffOperand = i;
711 }
712 }
713
Rafael Espindola7de80e02013-06-06 17:03:05 +0000714 if (NumDifferences == 0) // SAME GEP?
715 return ReplaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszak3facc432013-06-06 20:18:46 +0000716 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner02446fc2010-01-04 07:37:31 +0000717
Stuart Hastings67f071e2011-05-14 05:55:10 +0000718 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000719 Value *LHSV = GEPLHS->getOperand(DiffOperand);
720 Value *RHSV = GEPRHS->getOperand(DiffOperand);
721 // Make sure we do a signed comparison here.
722 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
723 }
724 }
725
726 // Only lower this if the icmp is the only user of the GEP or if we expect
727 // the result to fold to a constant!
728 if (TD &&
Stuart Hastings67f071e2011-05-14 05:55:10 +0000729 GEPsInBounds &&
Chris Lattner02446fc2010-01-04 07:37:31 +0000730 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
731 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
732 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
733 Value *L = EmitGEPOffset(GEPLHS);
734 Value *R = EmitGEPOffset(GEPRHS);
735 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
736 }
737 }
738 return 0;
739}
740
741/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
Benjamin Kramer19a6f112013-09-20 22:12:42 +0000742Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
Chris Lattner02446fc2010-01-04 07:37:31 +0000743 Value *X, ConstantInt *CI,
Benjamin Kramer19a6f112013-09-20 22:12:42 +0000744 ICmpInst::Predicate Pred) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000745 // If we have X+0, exit early (simplifying logic below) and let it get folded
746 // elsewhere. icmp X+0, X -> icmp X, X
747 if (CI->isZero()) {
748 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
749 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
750 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000751
Chris Lattner02446fc2010-01-04 07:37:31 +0000752 // (X+4) == X -> false.
753 if (Pred == ICmpInst::ICMP_EQ)
Jakub Staszak3facc432013-06-06 20:18:46 +0000754 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +0000755
756 // (X+4) != X -> true.
757 if (Pred == ICmpInst::ICMP_NE)
Jakub Staszak3facc432013-06-06 20:18:46 +0000758 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +0000759
Chris Lattner02446fc2010-01-04 07:37:31 +0000760 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000761 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner02446fc2010-01-04 07:37:31 +0000762 // operators.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000763
Chris Lattner9aa1e242010-01-08 17:48:19 +0000764 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner02446fc2010-01-04 07:37:31 +0000765 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
766 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
767 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000768 Value *R =
Chris Lattner9aa1e242010-01-08 17:48:19 +0000769 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner02446fc2010-01-04 07:37:31 +0000770 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
771 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000772
Chris Lattner02446fc2010-01-04 07:37:31 +0000773 // (X+1) >u X --> X <u (0-1) --> X != 255
774 // (X+2) >u X --> X <u (0-2) --> X <u 254
775 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandsa7724332011-02-17 07:46:37 +0000776 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000777 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000778
Chris Lattner02446fc2010-01-04 07:37:31 +0000779 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
780 ConstantInt *SMax = ConstantInt::get(X->getContext(),
781 APInt::getSignedMaxValue(BitWidth));
782
783 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
784 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
785 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
786 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
787 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
788 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandsa7724332011-02-17 07:46:37 +0000789 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000790 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000791
Chris Lattner02446fc2010-01-04 07:37:31 +0000792 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
793 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
794 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
795 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
796 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
797 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000798
Chris Lattner02446fc2010-01-04 07:37:31 +0000799 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszak3facc432013-06-06 20:18:46 +0000800 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner02446fc2010-01-04 07:37:31 +0000801 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
802}
803
804/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
805/// and CmpRHS are both known to be integer constants.
806Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
807 ConstantInt *DivRHS) {
808 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
809 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000810
811 // FIXME: If the operand types don't match the type of the divide
Chris Lattner02446fc2010-01-04 07:37:31 +0000812 // then don't attempt this transform. The code below doesn't have the
813 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000814 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner02446fc2010-01-04 07:37:31 +0000815 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000816 // (x /u C1) <u C2. Simply casting the operands and result won't
817 // work. :( The if statement below tests that condition and bails
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000818 // if it finds it.
Chris Lattner02446fc2010-01-04 07:37:31 +0000819 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
820 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
821 return 0;
822 if (DivRHS->isZero())
823 return 0; // The ProdOV computation fails on divide by zero.
824 if (DivIsSigned && DivRHS->isAllOnesValue())
825 return 0; // The overflow computation also screws up here
Chris Lattnerbb75d332011-02-13 08:07:21 +0000826 if (DivRHS->isOne()) {
827 // This eliminates some funny cases with INT_MIN.
828 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
829 return &ICI;
830 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000831
832 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000833 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
834 // C2 (CI). By solving for X we can turn this into a range check
835 // instead of computing a divide.
Chris Lattner02446fc2010-01-04 07:37:31 +0000836 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
837
838 // Determine if the product overflows by seeing if the product is
839 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000840 // as in the LHS instruction that we're folding.
Chris Lattner02446fc2010-01-04 07:37:31 +0000841 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
842 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
843
844 // Get the ICmp opcode
845 ICmpInst::Predicate Pred = ICI.getPredicate();
846
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000847 /// If the division is known to be exact, then there is no remainder from the
848 /// divide, so the covered range size is unit, otherwise it is the divisor.
849 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000850
Chris Lattner02446fc2010-01-04 07:37:31 +0000851 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000852 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner02446fc2010-01-04 07:37:31 +0000853 // Compute this interval based on the constants involved and the signedness of
854 // the compare/divide. This computes a half-open interval, keeping track of
855 // whether either value in the interval overflows. After analysis each
856 // overflow variable is set to 0 if it's corresponding bound variable is valid
857 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
858 int LoOverflow = 0, HiOverflow = 0;
859 Constant *LoBound = 0, *HiBound = 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000860
Chris Lattner02446fc2010-01-04 07:37:31 +0000861 if (!DivIsSigned) { // udiv
862 // e.g. X/5 op 3 --> [15, 20)
863 LoBound = Prod;
864 HiOverflow = LoOverflow = ProdOV;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000865 if (!HiOverflow) {
866 // If this is not an exact divide, then many values in the range collapse
867 // to the same result value.
868 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
869 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000870
Chris Lattner02446fc2010-01-04 07:37:31 +0000871 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
872 if (CmpRHSV == 0) { // (X / pos) op 0
873 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000874 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
875 HiBound = RangeSize;
Chris Lattner02446fc2010-01-04 07:37:31 +0000876 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
877 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
878 HiOverflow = LoOverflow = ProdOV;
879 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000880 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000881 } else { // (X / pos) op neg
882 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
883 HiBound = AddOne(Prod);
884 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
885 if (!LoOverflow) {
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000886 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000887 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000888 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000889 }
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000890 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000891 if (DivI->isExact())
892 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000893 if (CmpRHSV == 0) { // (X / neg) op 0
894 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000895 LoBound = AddOne(RangeSize);
896 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000897 if (HiBound == DivRHS) { // -INTMIN = INTMIN
898 HiOverflow = 1; // [INTMIN+1, overflow)
899 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
900 }
901 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
902 // e.g. X/-5 op 3 --> [-19, -14)
903 HiBound = AddOne(Prod);
904 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
905 if (!LoOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000906 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner02446fc2010-01-04 07:37:31 +0000907 } else { // (X / neg) op neg
908 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
909 LoOverflow = HiOverflow = ProdOV;
910 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000911 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000912 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000913
Chris Lattner02446fc2010-01-04 07:37:31 +0000914 // Dividing by a negative swaps the condition. LT <-> GT
915 Pred = ICmpInst::getSwappedPredicate(Pred);
916 }
917
918 Value *X = DivI->getOperand(0);
919 switch (Pred) {
920 default: llvm_unreachable("Unhandled icmp opcode!");
921 case ICmpInst::ICMP_EQ:
922 if (LoOverflow && HiOverflow)
Jakub Staszak3facc432013-06-06 20:18:46 +0000923 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000924 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000925 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
926 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000927 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000928 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
929 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000930 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
931 DivIsSigned, true));
Chris Lattner02446fc2010-01-04 07:37:31 +0000932 case ICmpInst::ICMP_NE:
933 if (LoOverflow && HiOverflow)
Jakub Staszak3facc432013-06-06 20:18:46 +0000934 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000935 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000936 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
937 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000938 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000939 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
940 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000941 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
942 DivIsSigned, false));
Chris Lattner02446fc2010-01-04 07:37:31 +0000943 case ICmpInst::ICMP_ULT:
944 case ICmpInst::ICMP_SLT:
945 if (LoOverflow == +1) // Low bound is greater than input range.
Jakub Staszak3facc432013-06-06 20:18:46 +0000946 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +0000947 if (LoOverflow == -1) // Low bound is less than input range.
Jakub Staszak3facc432013-06-06 20:18:46 +0000948 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +0000949 return new ICmpInst(Pred, X, LoBound);
950 case ICmpInst::ICMP_UGT:
951 case ICmpInst::ICMP_SGT:
952 if (HiOverflow == +1) // High bound greater than input range.
Jakub Staszak3facc432013-06-06 20:18:46 +0000953 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000954 if (HiOverflow == -1) // High bound less than input range.
Jakub Staszak3facc432013-06-06 20:18:46 +0000955 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +0000956 if (Pred == ICmpInst::ICMP_UGT)
957 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000958 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner02446fc2010-01-04 07:37:31 +0000959 }
960}
961
Chris Lattner74542aa2011-02-13 07:43:07 +0000962/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
963Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
964 ConstantInt *ShAmt) {
Chris Lattner74542aa2011-02-13 07:43:07 +0000965 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000966
Chris Lattner74542aa2011-02-13 07:43:07 +0000967 // Check that the shift amount is in range. If not, don't perform
968 // undefined shifts. When the shift is visited it will be
969 // simplified.
970 uint32_t TypeBits = CmpRHSV.getBitWidth();
971 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnerbb75d332011-02-13 08:07:21 +0000972 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Chris Lattner74542aa2011-02-13 07:43:07 +0000973 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000974
Chris Lattnerbb75d332011-02-13 08:07:21 +0000975 if (!ICI.isEquality()) {
976 // If we have an unsigned comparison and an ashr, we can't simplify this.
977 // Similarly for signed comparisons with lshr.
978 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
979 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000980
Eli Friedmana831a9b2011-05-25 23:26:20 +0000981 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
982 // by a power of 2. Since we already have logic to simplify these,
983 // transform to div and then simplify the resultant comparison.
Chris Lattnerbb75d332011-02-13 08:07:21 +0000984 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedmana831a9b2011-05-25 23:26:20 +0000985 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Chris Lattnerbb75d332011-02-13 08:07:21 +0000986 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000987
Chris Lattnerbb75d332011-02-13 08:07:21 +0000988 // Revisit the shift (to delete it).
989 Worklist.Add(Shr);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000990
Chris Lattnerbb75d332011-02-13 08:07:21 +0000991 Constant *DivCst =
992 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000993
Chris Lattnerbb75d332011-02-13 08:07:21 +0000994 Value *Tmp =
995 Shr->getOpcode() == Instruction::AShr ?
996 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
997 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000998
Chris Lattnerbb75d332011-02-13 08:07:21 +0000999 ICI.setOperand(0, Tmp);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001000
Chris Lattnerbb75d332011-02-13 08:07:21 +00001001 // If the builder folded the binop, just return it.
1002 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
1003 if (TheDiv == 0)
1004 return &ICI;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001005
Chris Lattnerbb75d332011-02-13 08:07:21 +00001006 // Otherwise, fold this div/compare.
1007 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1008 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001009
Chris Lattnerbb75d332011-02-13 08:07:21 +00001010 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1011 assert(Res && "This div/cst should have folded!");
1012 return Res;
1013 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001014
1015
Chris Lattner74542aa2011-02-13 07:43:07 +00001016 // If we are comparing against bits always shifted out, the
1017 // comparison cannot succeed.
1018 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszak3facc432013-06-06 20:18:46 +00001019 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattner74542aa2011-02-13 07:43:07 +00001020 if (Shr->getOpcode() == Instruction::LShr)
1021 Comp = Comp.lshr(ShAmtVal);
1022 else
1023 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001024
Chris Lattner74542aa2011-02-13 07:43:07 +00001025 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1026 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszak3facc432013-06-06 20:18:46 +00001027 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattner74542aa2011-02-13 07:43:07 +00001028 return ReplaceInstUsesWith(ICI, Cst);
1029 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001030
Chris Lattner74542aa2011-02-13 07:43:07 +00001031 // Otherwise, check to see if the bits shifted out are known to be zero.
1032 // If so, we can compare against the unshifted value:
1033 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattnere5116f82011-02-13 18:30:09 +00001034 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattner74542aa2011-02-13 07:43:07 +00001035 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001036
Chris Lattner74542aa2011-02-13 07:43:07 +00001037 if (Shr->hasOneUse()) {
1038 // Otherwise strength reduce the shift into an and.
1039 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszak3facc432013-06-06 20:18:46 +00001040 Constant *Mask = Builder->getInt(Val);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001041
Chris Lattner74542aa2011-02-13 07:43:07 +00001042 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1043 Mask, Shr->getName()+".mask");
1044 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1045 }
1046 return 0;
1047}
1048
Chris Lattner02446fc2010-01-04 07:37:31 +00001049
1050/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1051///
1052Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1053 Instruction *LHSI,
1054 ConstantInt *RHS) {
1055 const APInt &RHSV = RHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001056
Chris Lattner02446fc2010-01-04 07:37:31 +00001057 switch (LHSI->getOpcode()) {
1058 case Instruction::Trunc:
1059 if (ICI.isEquality() && LHSI->hasOneUse()) {
1060 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1061 // of the high bits truncated out of x are known.
1062 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1063 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner02446fc2010-01-04 07:37:31 +00001064 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001065 ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001066
Chris Lattner02446fc2010-01-04 07:37:31 +00001067 // If all the high bits are known, we can do this xform.
1068 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1069 // Pull in the high bits from known-ones set.
Jay Foad40f8f622010-12-07 08:25:19 +00001070 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedman5b6dfee2012-05-11 01:32:59 +00001071 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner02446fc2010-01-04 07:37:31 +00001072 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001073 Builder->getInt(NewRHS));
Chris Lattner02446fc2010-01-04 07:37:31 +00001074 }
1075 }
1076 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001077
Chris Lattner02446fc2010-01-04 07:37:31 +00001078 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
1079 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1080 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1081 // fold the xor.
1082 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1083 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1084 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001085
Chris Lattner02446fc2010-01-04 07:37:31 +00001086 // If the sign bit of the XorCST is not set, there is no change to
1087 // the operation, just stop using the Xor.
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001088 if (!XorCST->isNegative()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001089 ICI.setOperand(0, CompareVal);
1090 Worklist.Add(LHSI);
1091 return &ICI;
1092 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001093
Chris Lattner02446fc2010-01-04 07:37:31 +00001094 // Was the old condition true if the operand is positive?
1095 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001096
Chris Lattner02446fc2010-01-04 07:37:31 +00001097 // If so, the new one isn't.
1098 isTrueIfPositive ^= true;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001099
Chris Lattner02446fc2010-01-04 07:37:31 +00001100 if (isTrueIfPositive)
1101 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1102 SubOne(RHS));
1103 else
1104 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1105 AddOne(RHS));
1106 }
1107
1108 if (LHSI->hasOneUse()) {
1109 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1110 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
1111 const APInt &SignBit = XorCST->getValue();
1112 ICmpInst::Predicate Pred = ICI.isSigned()
1113 ? ICI.getUnsignedPredicate()
1114 : ICI.getSignedPredicate();
1115 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001116 Builder->getInt(RHSV ^ SignBit));
Chris Lattner02446fc2010-01-04 07:37:31 +00001117 }
1118
1119 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001120 if (!ICI.isEquality() && XorCST->isMaxValue(true)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001121 const APInt &NotSignBit = XorCST->getValue();
1122 ICmpInst::Predicate Pred = ICI.isSigned()
1123 ? ICI.getUnsignedPredicate()
1124 : ICI.getSignedPredicate();
1125 Pred = ICI.getSwappedPredicate(Pred);
1126 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001127 Builder->getInt(RHSV ^ NotSignBit));
Chris Lattner02446fc2010-01-04 07:37:31 +00001128 }
1129 }
David Majnemerfecf0d72013-07-09 09:20:58 +00001130
1131 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1132 // iff -C is a power of 2
1133 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
1134 XorCST->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1135 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCST);
1136
1137 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1138 // iff -C is a power of 2
1139 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
1140 XorCST->getValue() == -RHSV && RHSV.isPowerOf2())
1141 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCST);
Chris Lattner02446fc2010-01-04 07:37:31 +00001142 }
1143 break;
1144 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
1145 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1146 LHSI->getOperand(0)->hasOneUse()) {
1147 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001148
Chris Lattner02446fc2010-01-04 07:37:31 +00001149 // If the LHS is an AND of a truncating cast, we can widen the
1150 // and/compare to be the input width without changing the value
1151 // produced, eliminating a cast.
1152 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1153 // We can do this transformation if either the AND constant does not
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001154 // have its sign bit set or if it is an equality comparison.
Chris Lattner02446fc2010-01-04 07:37:31 +00001155 // Extending a relational comparison when we're checking the sign
1156 // bit would not work.
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001157 if (ICI.isEquality() ||
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001158 (!AndCST->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001159 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001160 Builder->CreateAnd(Cast->getOperand(0),
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001161 ConstantExpr::getZExt(AndCST, Cast->getSrcTy()));
1162 NewAnd->takeName(LHSI);
Chris Lattner02446fc2010-01-04 07:37:31 +00001163 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001164 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001165 }
1166 }
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001167
1168 // If the LHS is an AND of a zext, and we have an equality compare, we can
1169 // shrink the and/compare to the smaller type, eliminating the cast.
1170 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001171 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001172 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1173 // should fold the icmp to true/false in that case.
1174 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1175 Value *NewAnd =
1176 Builder->CreateAnd(Cast->getOperand(0),
1177 ConstantExpr::getTrunc(AndCST, Ty));
1178 NewAnd->takeName(LHSI);
1179 return new ICmpInst(ICI.getPredicate(), NewAnd,
1180 ConstantExpr::getTrunc(RHS, Ty));
1181 }
1182 }
1183
Chris Lattner02446fc2010-01-04 07:37:31 +00001184 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1185 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1186 // happens a LOT in code produced by the C front-end, for bitfield
1187 // access.
1188 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1189 if (Shift && !Shift->isShift())
1190 Shift = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001191
Chris Lattner02446fc2010-01-04 07:37:31 +00001192 ConstantInt *ShAmt;
1193 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001194 Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
1195 Type *AndTy = AndCST->getType(); // Type of the and.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001196
Chris Lattner02446fc2010-01-04 07:37:31 +00001197 // We can fold this as long as we can't shift unknown bits
1198 // into the mask. This can only happen with signed shift
1199 // rights, as they sign-extend.
1200 if (ShAmt) {
1201 bool CanFold = Shift->isLogicalShift();
1202 if (!CanFold) {
1203 // To test for the bad case of the signed shr, see if any
1204 // of the bits shifted in could be tested after the mask.
1205 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1206 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001207
Chris Lattner02446fc2010-01-04 07:37:31 +00001208 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001209 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
Chris Lattner02446fc2010-01-04 07:37:31 +00001210 AndCST->getValue()) == 0)
1211 CanFold = true;
1212 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001213
Chris Lattner02446fc2010-01-04 07:37:31 +00001214 if (CanFold) {
1215 Constant *NewCst;
1216 if (Shift->getOpcode() == Instruction::Shl)
1217 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1218 else
1219 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001220
Chris Lattner02446fc2010-01-04 07:37:31 +00001221 // Check to see if we are shifting out any of the bits being
1222 // compared.
1223 if (ConstantExpr::get(Shift->getOpcode(),
1224 NewCst, ShAmt) != RHS) {
1225 // If we shifted bits out, the fold is not going to work out.
1226 // As a special case, check to see if this means that the
1227 // result is always true or false now.
1228 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Jakub Staszak3facc432013-06-06 20:18:46 +00001229 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00001230 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Jakub Staszak3facc432013-06-06 20:18:46 +00001231 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +00001232 } else {
1233 ICI.setOperand(1, NewCst);
1234 Constant *NewAndCST;
1235 if (Shift->getOpcode() == Instruction::Shl)
1236 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1237 else
1238 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1239 LHSI->setOperand(1, NewAndCST);
1240 LHSI->setOperand(0, Shift->getOperand(0));
1241 Worklist.Add(Shift); // Shift is dead.
1242 return &ICI;
1243 }
1244 }
1245 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001246
Chris Lattner02446fc2010-01-04 07:37:31 +00001247 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1248 // preferable because it allows the C<<Y expression to be hoisted out
1249 // of a loop if Y is invariant and X is not.
1250 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1251 ICI.isEquality() && !Shift->isArithmeticShift() &&
1252 !isa<Constant>(Shift->getOperand(0))) {
1253 // Compute C << Y.
1254 Value *NS;
1255 if (Shift->getOpcode() == Instruction::LShr) {
Benjamin Kramera9390a42011-09-27 20:39:19 +00001256 NS = Builder->CreateShl(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001257 } else {
1258 // Insert a logical shift.
Benjamin Kramera9390a42011-09-27 20:39:19 +00001259 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001260 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001261
Chris Lattner02446fc2010-01-04 07:37:31 +00001262 // Compute X & (C << Y).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001263 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001264 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001265
Chris Lattner02446fc2010-01-04 07:37:31 +00001266 ICI.setOperand(0, NewAnd);
1267 return &ICI;
1268 }
Paul Redmond6da2e222012-12-19 19:47:13 +00001269
1270 // Replace ((X & AndCST) > RHSV) with ((X & AndCST) != 0), if any
1271 // bit set in (X & AndCST) will produce a result greater than RHSV.
1272 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
1273 unsigned NTZ = AndCST->getValue().countTrailingZeros();
1274 if ((NTZ < AndCST->getBitWidth()) &&
1275 APInt::getOneBitSet(AndCST->getBitWidth(), NTZ).ugt(RHSV))
1276 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1277 Constant::getNullValue(RHS->getType()));
1278 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001279 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001280
Chris Lattner02446fc2010-01-04 07:37:31 +00001281 // Try to optimize things like "A[i]&42 == 0" to index computations.
1282 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1283 if (GetElementPtrInst *GEP =
1284 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1285 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1286 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1287 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1288 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1289 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1290 return Res;
1291 }
1292 }
David Majnemer36b6f742013-07-09 08:09:32 +00001293
1294 // X & -C == -C -> X > u ~C
1295 // X & -C != -C -> X <= u ~C
1296 // iff C is a power of 2
1297 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1298 return new ICmpInst(
1299 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1300 : ICmpInst::ICMP_ULE,
1301 LHSI->getOperand(0), SubOne(RHS));
Chris Lattner02446fc2010-01-04 07:37:31 +00001302 break;
1303
1304 case Instruction::Or: {
1305 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1306 break;
1307 Value *P, *Q;
1308 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1309 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1310 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner02446fc2010-01-04 07:37:31 +00001311 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1312 Constant::getNullValue(P->getType()));
1313 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1314 Constant::getNullValue(Q->getType()));
1315 Instruction *Op;
1316 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1317 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1318 else
1319 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1320 return Op;
1321 }
1322 break;
1323 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001324
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001325 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1326 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1327 if (!Val) break;
1328
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +00001329 // If this is a signed comparison to 0 and the mul is sign preserving,
1330 // use the mul LHS operand instead.
1331 ICmpInst::Predicate pred = ICI.getPredicate();
1332 if (isSignTest(pred, RHS) && !Val->isZero() &&
1333 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1334 return new ICmpInst(Val->isNegative() ?
1335 ICmpInst::getSwappedPredicate(pred) : pred,
1336 LHSI->getOperand(0),
1337 Constant::getNullValue(RHS->getType()));
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001338
1339 break;
1340 }
1341
Chris Lattner02446fc2010-01-04 07:37:31 +00001342 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
Chris Lattner02446fc2010-01-04 07:37:31 +00001343 uint32_t TypeBits = RHSV.getBitWidth();
David Majnemerb41f4bb2013-06-28 23:42:03 +00001344 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1345 if (!ShAmt) {
1346 Value *X;
1347 // (1 << X) pred P2 -> X pred Log2(P2)
1348 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1349 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1350 ICmpInst::Predicate Pred = ICI.getPredicate();
1351 if (ICI.isUnsigned()) {
1352 if (!RHSVIsPowerOf2) {
1353 // (1 << X) < 30 -> X <= 4
1354 // (1 << X) <= 30 -> X <= 4
1355 // (1 << X) >= 30 -> X > 4
1356 // (1 << X) > 30 -> X > 4
1357 if (Pred == ICmpInst::ICMP_ULT)
1358 Pred = ICmpInst::ICMP_ULE;
1359 else if (Pred == ICmpInst::ICMP_UGE)
1360 Pred = ICmpInst::ICMP_UGT;
1361 }
1362 unsigned RHSLog2 = RHSV.logBase2();
1363
1364 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
1365 // (1 << X) > 2147483648 -> X > 31 -> false
1366 // (1 << X) <= 2147483648 -> X <= 31 -> true
1367 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1368 if (RHSLog2 == TypeBits-1) {
1369 if (Pred == ICmpInst::ICMP_UGE)
1370 Pred = ICmpInst::ICMP_EQ;
1371 else if (Pred == ICmpInst::ICMP_UGT)
1372 return ReplaceInstUsesWith(ICI, Builder->getFalse());
1373 else if (Pred == ICmpInst::ICMP_ULE)
1374 return ReplaceInstUsesWith(ICI, Builder->getTrue());
1375 else if (Pred == ICmpInst::ICMP_ULT)
1376 Pred = ICmpInst::ICMP_NE;
1377 }
1378
1379 return new ICmpInst(Pred, X,
1380 ConstantInt::get(RHS->getType(), RHSLog2));
1381 } else if (ICI.isSigned()) {
1382 if (RHSV.isAllOnesValue()) {
1383 // (1 << X) <= -1 -> X == 31
1384 if (Pred == ICmpInst::ICMP_SLE)
1385 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1386 ConstantInt::get(RHS->getType(), TypeBits-1));
1387
1388 // (1 << X) > -1 -> X != 31
1389 if (Pred == ICmpInst::ICMP_SGT)
1390 return new ICmpInst(ICmpInst::ICMP_NE, X,
1391 ConstantInt::get(RHS->getType(), TypeBits-1));
1392 } else if (!RHSV) {
1393 // (1 << X) < 0 -> X == 31
1394 // (1 << X) <= 0 -> X == 31
1395 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1396 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1397 ConstantInt::get(RHS->getType(), TypeBits-1));
1398
1399 // (1 << X) >= 0 -> X != 31
1400 // (1 << X) > 0 -> X != 31
1401 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1402 return new ICmpInst(ICmpInst::ICMP_NE, X,
1403 ConstantInt::get(RHS->getType(), TypeBits-1));
1404 }
1405 } else if (ICI.isEquality()) {
1406 if (RHSVIsPowerOf2)
1407 return new ICmpInst(
1408 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
1409
1410 return ReplaceInstUsesWith(
1411 ICI, Pred == ICmpInst::ICMP_EQ ? Builder->getFalse()
1412 : Builder->getTrue());
1413 }
1414 }
1415 break;
1416 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001417
Chris Lattner02446fc2010-01-04 07:37:31 +00001418 // Check that the shift amount is in range. If not, don't perform
1419 // undefined shifts. When the shift is visited it will be
1420 // simplified.
1421 if (ShAmt->uge(TypeBits))
1422 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001423
Chris Lattner02446fc2010-01-04 07:37:31 +00001424 if (ICI.isEquality()) {
1425 // If we are comparing against bits always shifted out, the
1426 // comparison cannot succeed.
1427 Constant *Comp =
1428 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1429 ShAmt);
1430 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1431 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszak3facc432013-06-06 20:18:46 +00001432 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattner02446fc2010-01-04 07:37:31 +00001433 return ReplaceInstUsesWith(ICI, Cst);
1434 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001435
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001436 // If the shift is NUW, then it is just shifting out zeros, no need for an
1437 // AND.
1438 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1439 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1440 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001441
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001442 // If the shift is NSW and we compare to 0, then it is just shifting out
1443 // sign bits, no need for an AND either.
1444 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1445 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1446 ConstantExpr::getLShr(RHS, ShAmt));
1447
Chris Lattner02446fc2010-01-04 07:37:31 +00001448 if (LHSI->hasOneUse()) {
1449 // Otherwise strength reduce the shift into an and.
1450 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Jakub Staszak3facc432013-06-06 20:18:46 +00001451 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
1452 TypeBits - ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001453
Chris Lattner02446fc2010-01-04 07:37:31 +00001454 Value *And =
1455 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1456 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001457 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner02446fc2010-01-04 07:37:31 +00001458 }
1459 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001460
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001461 // If this is a signed comparison to 0 and the shift is sign preserving,
1462 // use the shift LHS operand instead.
1463 ICmpInst::Predicate pred = ICI.getPredicate();
1464 if (isSignTest(pred, RHS) &&
1465 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1466 return new ICmpInst(pred,
1467 LHSI->getOperand(0),
1468 Constant::getNullValue(RHS->getType()));
1469
Chris Lattner02446fc2010-01-04 07:37:31 +00001470 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1471 bool TrueIfSigned = false;
1472 if (LHSI->hasOneUse() &&
1473 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1474 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattnerbb75d332011-02-13 08:07:21 +00001475 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001476 APInt::getOneBitSet(TypeBits,
Chris Lattnerbb75d332011-02-13 08:07:21 +00001477 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001478 Value *And =
1479 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1480 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1481 And, Constant::getNullValue(And->getType()));
1482 }
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001483
1484 // Transform (icmp pred iM (shl iM %v, N), CI)
Arnaud A. de Grandmaisonbdd2d982013-03-13 14:40:37 +00001485 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1486 // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001487 // This enables to get rid of the shift in favor of a trunc which can be
1488 // free on the target. It has the additional benefit of comparing to a
1489 // smaller constant, which will be target friendly.
1490 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
Arnaud A. de Grandmaisonbdd2d982013-03-13 14:40:37 +00001491 if (LHSI->hasOneUse() &&
1492 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001493 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1494 Constant *NCI = ConstantExpr::getTrunc(
1495 ConstantExpr::getAShr(RHS,
1496 ConstantInt::get(RHS->getType(), Amt)),
1497 NTy);
1498 return new ICmpInst(ICI.getPredicate(),
1499 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaisonad079b22013-02-15 15:18:17 +00001500 NCI);
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001501 }
1502
Chris Lattner02446fc2010-01-04 07:37:31 +00001503 break;
1504 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001505
Chris Lattner02446fc2010-01-04 07:37:31 +00001506 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001507 case Instruction::AShr: {
1508 // Handle equality comparisons of shift-by-constant.
1509 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1510 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1511 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattner74542aa2011-02-13 07:43:07 +00001512 return Res;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001513 }
1514
1515 // Handle exact shr's.
1516 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1517 if (RHSV.isMinValue())
1518 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1519 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001520 break;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001521 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001522
Chris Lattner02446fc2010-01-04 07:37:31 +00001523 case Instruction::SDiv:
1524 case Instruction::UDiv:
1525 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001526 // Fold this div into the comparison, producing a range check.
1527 // Determine, based on the divide type, what the range is being
1528 // checked. If there is an overflow on the low or high side, remember
Chris Lattner02446fc2010-01-04 07:37:31 +00001529 // it, otherwise compute the range [low, hi) bounding the new value.
1530 // See: InsertRangeTest above for the kinds of replacements possible.
1531 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1532 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1533 DivRHS))
1534 return R;
1535 break;
1536
David Majnemer377a5c12013-07-09 07:50:59 +00001537 case Instruction::Sub: {
1538 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
1539 if (!LHSC) break;
1540 const APInt &LHSV = LHSC->getValue();
1541
1542 // C1-X <u C2 -> (X|(C2-1)) == C1
1543 // iff C1 & (C2-1) == C2-1
1544 // C2 is a power of 2
1545 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1546 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
1547 return new ICmpInst(ICmpInst::ICMP_EQ,
1548 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
1549 LHSC);
1550
David Majnemerfcb7b972013-07-09 09:24:35 +00001551 // C1-X >u C2 -> (X|C2) != C1
David Majnemer377a5c12013-07-09 07:50:59 +00001552 // iff C1 & C2 == C2
1553 // C2+1 is a power of 2
1554 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1555 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
1556 return new ICmpInst(ICmpInst::ICMP_NE,
1557 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
1558 break;
1559 }
1560
Chris Lattner02446fc2010-01-04 07:37:31 +00001561 case Instruction::Add:
1562 // Fold: icmp pred (add X, C1), C2
1563 if (!ICI.isEquality()) {
1564 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1565 if (!LHSC) break;
1566 const APInt &LHSV = LHSC->getValue();
1567
1568 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1569 .subtract(LHSV);
1570
1571 if (ICI.isSigned()) {
1572 if (CR.getLower().isSignBit()) {
1573 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001574 Builder->getInt(CR.getUpper()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001575 } else if (CR.getUpper().isSignBit()) {
1576 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001577 Builder->getInt(CR.getLower()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001578 }
1579 } else {
1580 if (CR.getLower().isMinValue()) {
1581 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001582 Builder->getInt(CR.getUpper()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001583 } else if (CR.getUpper().isMinValue()) {
1584 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001585 Builder->getInt(CR.getLower()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001586 }
1587 }
David Majnemer53fc3992013-07-08 11:53:08 +00001588
David Majnemer11c29ba2013-07-09 07:58:32 +00001589 // X-C1 <u C2 -> (X & -C2) == C1
1590 // iff C1 & (C2-1) == 0
1591 // C2 is a power of 2
David Majnemer53fc3992013-07-08 11:53:08 +00001592 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
David Majnemer11c29ba2013-07-09 07:58:32 +00001593 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
David Majnemer53fc3992013-07-08 11:53:08 +00001594 return new ICmpInst(ICmpInst::ICMP_EQ,
1595 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
1596 ConstantExpr::getNeg(LHSC));
David Majnemer11c29ba2013-07-09 07:58:32 +00001597
David Majnemerfcb7b972013-07-09 09:24:35 +00001598 // X-C1 >u C2 -> (X & ~C2) != C1
David Majnemer11c29ba2013-07-09 07:58:32 +00001599 // iff C1 & C2 == 0
1600 // C2+1 is a power of 2
1601 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1602 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
1603 return new ICmpInst(ICmpInst::ICMP_NE,
1604 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
1605 ConstantExpr::getNeg(LHSC));
Chris Lattner02446fc2010-01-04 07:37:31 +00001606 }
1607 break;
1608 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001609
Chris Lattner02446fc2010-01-04 07:37:31 +00001610 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1611 if (ICI.isEquality()) {
1612 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001613
1614 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner02446fc2010-01-04 07:37:31 +00001615 // the second operand is a constant, simplify a bit.
1616 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1617 switch (BO->getOpcode()) {
1618 case Instruction::SRem:
1619 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1620 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1621 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohmane0567812010-04-08 23:03:40 +00001622 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001623 Value *NewRem =
1624 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1625 BO->getName());
1626 return new ICmpInst(ICI.getPredicate(), NewRem,
1627 Constant::getNullValue(BO->getType()));
1628 }
1629 }
1630 break;
1631 case Instruction::Add:
1632 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1633 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1634 if (BO->hasOneUse())
1635 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1636 ConstantExpr::getSub(RHS, BOp1C));
1637 } else if (RHSV == 0) {
1638 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1639 // efficiently invertible, or if the add has just this one use.
1640 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001641
Chris Lattner02446fc2010-01-04 07:37:31 +00001642 if (Value *NegVal = dyn_castNegVal(BOp1))
1643 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner5036ce42011-04-26 20:02:45 +00001644 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner02446fc2010-01-04 07:37:31 +00001645 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner5036ce42011-04-26 20:02:45 +00001646 if (BO->hasOneUse()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001647 Value *Neg = Builder->CreateNeg(BOp1);
1648 Neg->takeName(BO);
1649 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1650 }
1651 }
1652 break;
1653 case Instruction::Xor:
1654 // For the xor case, we can xor two constants together, eliminating
1655 // the explicit xor.
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001656 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1657 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner02446fc2010-01-04 07:37:31 +00001658 ConstantExpr::getXor(RHS, BOC));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001659 } else if (RHSV == 0) {
1660 // Replace ((xor A, B) != 0) with (A != B)
Chris Lattner02446fc2010-01-04 07:37:31 +00001661 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1662 BO->getOperand(1));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001663 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001664 break;
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001665 case Instruction::Sub:
1666 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1667 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1668 if (BO->hasOneUse())
1669 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1670 ConstantExpr::getSub(BOp0C, RHS));
1671 } else if (RHSV == 0) {
1672 // Replace ((sub A, B) != 0) with (A != B)
1673 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1674 BO->getOperand(1));
1675 }
1676 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001677 case Instruction::Or:
1678 // If bits are being or'd in that are not present in the constant we
1679 // are comparing against, then the comparison could never succeed!
Eli Friedman618898e2010-07-29 18:03:33 +00001680 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001681 Constant *NotCI = ConstantExpr::getNot(RHS);
1682 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Jakub Staszak3facc432013-06-06 20:18:46 +00001683 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Chris Lattner02446fc2010-01-04 07:37:31 +00001684 }
1685 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001686
Chris Lattner02446fc2010-01-04 07:37:31 +00001687 case Instruction::And:
1688 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1689 // If bits are being compared against that are and'd out, then the
1690 // comparison can never succeed!
1691 if ((RHSV & ~BOC->getValue()) != 0)
Jakub Staszak3facc432013-06-06 20:18:46 +00001692 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001693
Chris Lattner02446fc2010-01-04 07:37:31 +00001694 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1695 if (RHS == BOC && RHSV.isPowerOf2())
1696 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1697 ICmpInst::ICMP_NE, LHSI,
1698 Constant::getNullValue(RHS->getType()));
Benjamin Kramerfc87cdc2011-07-04 20:16:36 +00001699
1700 // Don't perform the following transforms if the AND has multiple uses
1701 if (!BO->hasOneUse())
1702 break;
1703
Chris Lattner02446fc2010-01-04 07:37:31 +00001704 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1705 if (BOC->getValue().isSignBit()) {
1706 Value *X = BO->getOperand(0);
1707 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001708 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001709 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1710 return new ICmpInst(pred, X, Zero);
1711 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001712
Chris Lattner02446fc2010-01-04 07:37:31 +00001713 // ((X & ~7) == 0) --> X < 8
1714 if (RHSV == 0 && isHighOnes(BOC)) {
1715 Value *X = BO->getOperand(0);
1716 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001717 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001718 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1719 return new ICmpInst(pred, X, NegX);
1720 }
1721 }
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001722 break;
1723 case Instruction::Mul:
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +00001724 if (RHSV == 0 && BO->hasNoSignedWrap()) {
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001725 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1726 // The trivial case (mul X, 0) is handled by InstSimplify
1727 // General case : (mul X, C) != 0 iff X != 0
1728 // (mul X, C) == 0 iff X == 0
1729 if (!BOC->isZero())
1730 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1731 Constant::getNullValue(RHS->getType()));
1732 }
1733 }
1734 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001735 default: break;
1736 }
1737 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1738 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner03357402010-01-05 18:09:56 +00001739 switch (II->getIntrinsicID()) {
1740 case Intrinsic::bswap:
Chris Lattner02446fc2010-01-04 07:37:31 +00001741 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001742 ICI.setOperand(0, II->getArgOperand(0));
Jakub Staszak3facc432013-06-06 20:18:46 +00001743 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001744 return &ICI;
Chris Lattner03357402010-01-05 18:09:56 +00001745 case Intrinsic::ctlz:
1746 case Intrinsic::cttz:
1747 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1748 if (RHSV == RHS->getType()->getBitWidth()) {
1749 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001750 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001751 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1752 return &ICI;
1753 }
1754 break;
1755 case Intrinsic::ctpop:
1756 // popcount(A) == 0 -> A == 0 and likewise for !=
1757 if (RHS->isZero()) {
1758 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001759 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001760 ICI.setOperand(1, RHS);
1761 return &ICI;
1762 }
1763 break;
1764 default:
Duncan Sands34727662010-07-12 08:16:59 +00001765 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001766 }
1767 }
1768 }
1769 return 0;
1770}
1771
1772/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1773/// We only handle extending casts so far.
1774///
1775Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1776 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1777 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001778 Type *SrcTy = LHSCIOp->getType();
1779 Type *DestTy = LHSCI->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00001780 Value *RHSCIOp;
1781
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001782 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner02446fc2010-01-04 07:37:31 +00001783 // integer type is the same size as the pointer type.
1784 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
Chandler Carruth426c2bf2012-11-01 09:14:31 +00001785 TD->getPointerSizeInBits() ==
Chris Lattner02446fc2010-01-04 07:37:31 +00001786 cast<IntegerType>(DestTy)->getBitWidth()) {
1787 Value *RHSOp = 0;
1788 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1789 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1790 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1791 RHSOp = RHSC->getOperand(0);
1792 // If the pointer types don't match, insert a bitcast.
1793 if (LHSCIOp->getType() != RHSOp->getType())
1794 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1795 }
1796
1797 if (RHSOp)
1798 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1799 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001800
Chris Lattner02446fc2010-01-04 07:37:31 +00001801 // The code below only handles extension cast instructions, so far.
1802 // Enforce this.
1803 if (LHSCI->getOpcode() != Instruction::ZExt &&
1804 LHSCI->getOpcode() != Instruction::SExt)
1805 return 0;
1806
1807 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1808 bool isSignedCmp = ICI.isSigned();
1809
1810 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1811 // Not an extension from the same type?
1812 RHSCIOp = CI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001813 if (RHSCIOp->getType() != LHSCIOp->getType())
Chris Lattner02446fc2010-01-04 07:37:31 +00001814 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001815
Chris Lattner02446fc2010-01-04 07:37:31 +00001816 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1817 // and the other is a zext), then we can't handle this.
1818 if (CI->getOpcode() != LHSCI->getOpcode())
1819 return 0;
1820
1821 // Deal with equality cases early.
1822 if (ICI.isEquality())
1823 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1824
1825 // A signed comparison of sign extended values simplifies into a
1826 // signed comparison.
1827 if (isSignedCmp && isSignedExt)
1828 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1829
1830 // The other three cases all fold into an unsigned comparison.
1831 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1832 }
1833
1834 // If we aren't dealing with a constant on the RHS, exit early
1835 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1836 if (!CI)
1837 return 0;
1838
1839 // Compute the constant that would happen if we truncated to SrcTy then
1840 // reextended to DestTy.
1841 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1842 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1843 Res1, DestTy);
1844
1845 // If the re-extended constant didn't change...
1846 if (Res2 == CI) {
1847 // Deal with equality cases early.
1848 if (ICI.isEquality())
1849 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1850
1851 // A signed comparison of sign extended values simplifies into a
1852 // signed comparison.
1853 if (isSignedExt && isSignedCmp)
1854 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1855
1856 // The other three cases all fold into an unsigned comparison.
1857 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1858 }
1859
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001860 // The re-extended constant changed so the constant cannot be represented
Chris Lattner02446fc2010-01-04 07:37:31 +00001861 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands9d32f602011-01-20 13:21:55 +00001862 // All the cases that fold to true or false will have already been handled
1863 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner02446fc2010-01-04 07:37:31 +00001864
Duncan Sands9d32f602011-01-20 13:21:55 +00001865 if (isSignedCmp || !isSignedExt)
1866 return 0;
Chris Lattner02446fc2010-01-04 07:37:31 +00001867
1868 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1869 // should have been folded away previously and not enter in here.
Duncan Sands9d32f602011-01-20 13:21:55 +00001870
1871 // We're performing an unsigned comp with a sign extended value.
1872 // This is true if the input is >= 0. [aka >s -1]
1873 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1874 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner02446fc2010-01-04 07:37:31 +00001875
1876 // Finally, return the value computed.
Duncan Sands9d32f602011-01-20 13:21:55 +00001877 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner02446fc2010-01-04 07:37:31 +00001878 return ReplaceInstUsesWith(ICI, Result);
1879
Duncan Sands9d32f602011-01-20 13:21:55 +00001880 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner02446fc2010-01-04 07:37:31 +00001881 return BinaryOperator::CreateNot(Result);
1882}
1883
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001884/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1885/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001886/// If this is of the form:
1887/// sum = a + b
1888/// if (sum+128 >u 255)
1889/// Then replace it with llvm.sadd.with.overflow.i8.
1890///
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001891static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1892 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001893 InstCombiner &IC) {
Chris Lattner368397b2010-12-19 17:59:02 +00001894 // The transformation we're trying to do here is to transform this into an
1895 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1896 // with a narrower add, and discard the add-with-constant that is part of the
1897 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001898
Chris Lattner368397b2010-12-19 17:59:02 +00001899 // In order to eliminate the add-with-constant, the compare can be its only
1900 // use.
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001901 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Chris Lattner368397b2010-12-19 17:59:02 +00001902 if (!AddWithCst->hasOneUse()) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001903
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001904 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1905 if (!CI2->getValue().isPowerOf2()) return 0;
1906 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1907 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001908
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001909 // The width of the new add formed is 1 more than the bias.
1910 ++NewWidth;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001911
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001912 // Check to see that CI1 is an all-ones value with NewWidth bits.
1913 if (CI1->getBitWidth() == NewWidth ||
1914 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1915 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001916
Eli Friedman54b92112011-11-28 23:32:19 +00001917 // This is only really a signed overflow check if the inputs have been
1918 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1919 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1920 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1921 if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1922 IC.ComputeNumSignBits(B) < NeededSignBits)
1923 return 0;
1924
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001925 // In order to replace the original add with a narrower
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001926 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1927 // and truncates that discard the high bits of the add. Verify that this is
1928 // the case.
1929 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1930 for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1931 UI != E; ++UI) {
1932 if (*UI == AddWithCst) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001933
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001934 // Only accept truncates for now. We would really like a nice recursive
1935 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1936 // chain to see which bits of a value are actually demanded. If the
1937 // original add had another add which was then immediately truncated, we
1938 // could still do the transformation.
1939 TruncInst *TI = dyn_cast<TruncInst>(*UI);
1940 if (TI == 0 ||
1941 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1942 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001943
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001944 // If the pattern matches, truncate the inputs to the narrower type and
1945 // use the sadd_with_overflow intrinsic to efficiently compute both the
1946 // result and the overflow bit.
Chris Lattner0a624742010-12-19 18:35:09 +00001947 Module *M = I.getParent()->getParent()->getParent();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001948
Jay Foad5fdd6c82011-07-12 14:06:48 +00001949 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Chris Lattner0a624742010-12-19 18:35:09 +00001950 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001951 NewType);
Chris Lattner0a624742010-12-19 18:35:09 +00001952
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001953 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001954
Chris Lattner0a624742010-12-19 18:35:09 +00001955 // Put the new code above the original add, in case there are any uses of the
1956 // add between the add and the compare.
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001957 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001958
Chris Lattner0a624742010-12-19 18:35:09 +00001959 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1960 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1961 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1962 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1963 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001964
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001965 // The inner add was the result of the narrow add, zero extended to the
1966 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001967 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001968
Chris Lattner0a624742010-12-19 18:35:09 +00001969 // The original icmp gets replaced with the overflow value.
1970 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001971}
Chris Lattner02446fc2010-01-04 07:37:31 +00001972
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001973static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1974 InstCombiner &IC) {
1975 // Don't bother doing this transformation for pointers, don't do it for
1976 // vectors.
1977 if (!isa<IntegerType>(OrigAddV->getType())) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001978
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001979 // If the add is a constant expr, then we don't bother transforming it.
1980 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1981 if (OrigAdd == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001982
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001983 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001984
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001985 // Put the new code above the original add, in case there are any uses of the
1986 // add between the add and the compare.
1987 InstCombiner::BuilderTy *Builder = IC.Builder;
1988 Builder->SetInsertPoint(OrigAdd);
1989
1990 Module *M = I.getParent()->getParent()->getParent();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001991 Type *Ty = LHS->getType();
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001992 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001993 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1994 Value *Add = Builder->CreateExtractValue(Call, 0);
1995
1996 IC.ReplaceInstUsesWith(*OrigAdd, Add);
1997
1998 // The original icmp gets replaced with the overflow value.
1999 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
2000}
2001
Owen Andersonda1c1222011-01-11 00:36:45 +00002002// DemandedBitsLHSMask - When performing a comparison against a constant,
2003// it is possible that not all the bits in the LHS are demanded. This helper
2004// method computes the mask that IS demanded.
2005static APInt DemandedBitsLHSMask(ICmpInst &I,
2006 unsigned BitWidth, bool isSignCheck) {
2007 if (isSignCheck)
2008 return APInt::getSignBit(BitWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002009
Owen Andersonda1c1222011-01-11 00:36:45 +00002010 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2011 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Andersona33b6252011-01-11 18:26:37 +00002012 const APInt &RHS = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002013
Owen Andersonda1c1222011-01-11 00:36:45 +00002014 switch (I.getPredicate()) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002015 // For a UGT comparison, we don't care about any bits that
Owen Andersonda1c1222011-01-11 00:36:45 +00002016 // correspond to the trailing ones of the comparand. The value of these
2017 // bits doesn't impact the outcome of the comparison, because any value
2018 // greater than the RHS must differ in a bit higher than these due to carry.
2019 case ICmpInst::ICMP_UGT: {
2020 unsigned trailingOnes = RHS.countTrailingOnes();
2021 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2022 return ~lowBitsSet;
2023 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002024
Owen Andersonda1c1222011-01-11 00:36:45 +00002025 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2026 // Any value less than the RHS must differ in a higher bit because of carries.
2027 case ICmpInst::ICMP_ULT: {
2028 unsigned trailingZeros = RHS.countTrailingZeros();
2029 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2030 return ~lowBitsSet;
2031 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002032
Owen Andersonda1c1222011-01-11 00:36:45 +00002033 default:
2034 return APInt::getAllOnesValue(BitWidth);
2035 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002036
Owen Andersonda1c1222011-01-11 00:36:45 +00002037}
Chris Lattner02446fc2010-01-04 07:37:31 +00002038
Quentin Colombet2c6ef1c2013-09-09 20:56:48 +00002039/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2040/// should be swapped.
2041/// The descision is based on how many times these two operands are reused
2042/// as subtract operands and their positions in those instructions.
2043/// The rational is that several architectures use the same instruction for
2044/// both subtract and cmp, thus it is better if the order of those operands
2045/// match.
2046/// \return true if Op0 and Op1 should be swapped.
2047static bool swapMayExposeCSEOpportunities(const Value * Op0,
2048 const Value * Op1) {
2049 // Filter out pointer value as those cannot appears directly in subtract.
2050 // FIXME: we may want to go through inttoptrs or bitcasts.
2051 if (Op0->getType()->isPointerTy())
2052 return false;
2053 // Count every uses of both Op0 and Op1 in a subtract.
2054 // Each time Op0 is the first operand, count -1: swapping is bad, the
2055 // subtract has already the same layout as the compare.
2056 // Each time Op0 is the second operand, count +1: swapping is good, the
2057 // subtract has a diffrent layout as the compare.
2058 // At the end, if the benefit is greater than 0, Op0 should come second to
2059 // expose more CSE opportunities.
2060 int GlobalSwapBenefits = 0;
2061 for (Value::const_use_iterator UI = Op0->use_begin(), UIEnd = Op0->use_end(); UI != UIEnd; ++UI) {
2062 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(*UI);
2063 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2064 continue;
2065 // If Op0 is the first argument, this is not beneficial to swap the
2066 // arguments.
2067 int LocalSwapBenefits = -1;
2068 unsigned Op1Idx = 1;
2069 if (BinOp->getOperand(Op1Idx) == Op0) {
2070 Op1Idx = 0;
2071 LocalSwapBenefits = 1;
2072 }
2073 if (BinOp->getOperand(Op1Idx) != Op1)
2074 continue;
2075 GlobalSwapBenefits += LocalSwapBenefits;
2076 }
2077 return GlobalSwapBenefits > 0;
2078}
2079
Chris Lattner02446fc2010-01-04 07:37:31 +00002080Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
2081 bool Changed = false;
Chris Lattner5f670d42010-02-01 19:54:45 +00002082 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet2c6ef1c2013-09-09 20:56:48 +00002083 unsigned Op0Cplxity = getComplexity(Op0);
2084 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002085
Chris Lattner02446fc2010-01-04 07:37:31 +00002086 /// Orders the operands of the compare so that they are listed from most
2087 /// complex to least complex. This puts constants before unary operators,
2088 /// before binary operators.
Quentin Colombet2c6ef1c2013-09-09 20:56:48 +00002089 if (Op0Cplxity < Op1Cplxity ||
2090 (Op0Cplxity == Op1Cplxity &&
2091 swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002092 I.swapOperands();
Chris Lattner5f670d42010-02-01 19:54:45 +00002093 std::swap(Op0, Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00002094 Changed = true;
2095 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002096
Chris Lattner02446fc2010-01-04 07:37:31 +00002097 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
2098 return ReplaceInstUsesWith(I, V);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002099
Pete Cooper65a6b572011-12-01 03:58:40 +00002100 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooper165695d2011-12-01 19:13:26 +00002101 // ie, abs(val) != 0 -> val != 0
Pete Cooper65a6b572011-12-01 03:58:40 +00002102 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
2103 {
Pete Cooper165695d2011-12-01 19:13:26 +00002104 Value *Cond, *SelectTrue, *SelectFalse;
2105 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooper65a6b572011-12-01 03:58:40 +00002106 m_Value(SelectFalse)))) {
Pete Cooper165695d2011-12-01 19:13:26 +00002107 if (Value *V = dyn_castNegVal(SelectTrue)) {
2108 if (V == SelectFalse)
2109 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2110 }
2111 else if (Value *V = dyn_castNegVal(SelectFalse)) {
2112 if (V == SelectTrue)
2113 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooper65a6b572011-12-01 03:58:40 +00002114 }
2115 }
2116 }
2117
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002118 Type *Ty = Op0->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00002119
2120 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002121 if (Ty->isIntegerTy(1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002122 switch (I.getPredicate()) {
2123 default: llvm_unreachable("Invalid icmp instruction!");
2124 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
2125 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
2126 return BinaryOperator::CreateNot(Xor);
2127 }
2128 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
2129 return BinaryOperator::CreateXor(Op0, Op1);
2130
2131 case ICmpInst::ICMP_UGT:
2132 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
2133 // FALL THROUGH
2134 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
2135 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2136 return BinaryOperator::CreateAnd(Not, Op1);
2137 }
2138 case ICmpInst::ICMP_SGT:
2139 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
2140 // FALL THROUGH
2141 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
2142 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2143 return BinaryOperator::CreateAnd(Not, Op0);
2144 }
2145 case ICmpInst::ICMP_UGE:
2146 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
2147 // FALL THROUGH
2148 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
2149 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2150 return BinaryOperator::CreateOr(Not, Op1);
2151 }
2152 case ICmpInst::ICMP_SGE:
2153 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
2154 // FALL THROUGH
2155 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
2156 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2157 return BinaryOperator::CreateOr(Not, Op0);
2158 }
2159 }
2160 }
2161
2162 unsigned BitWidth = 0;
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002163 if (Ty->isIntOrIntVectorTy())
Chris Lattner02446fc2010-01-04 07:37:31 +00002164 BitWidth = Ty->getScalarSizeInBits();
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002165 else if (TD) // Pointers require TD info to get their size.
2166 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002167
Chris Lattner02446fc2010-01-04 07:37:31 +00002168 bool isSignBit = false;
2169
2170 // See if we are doing a comparison with a constant.
2171 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2172 Value *A = 0, *B = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002173
Owen Andersone63dda52010-12-17 18:08:00 +00002174 // Match the following pattern, which is a common idiom when writing
2175 // overflow-safe integer arithmetic function. The source performs an
2176 // addition in wider type, and explicitly checks for overflow using
2177 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
2178 // sadd_with_overflow intrinsic.
Chris Lattnerf0f568b2010-12-19 17:52:50 +00002179 //
2180 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002181 // operations if we worked out the formulas to compute the appropriate
Owen Andersone63dda52010-12-17 18:08:00 +00002182 // magic constants.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002183 //
Chris Lattnerf0f568b2010-12-19 17:52:50 +00002184 // sum = a + b
2185 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Andersone63dda52010-12-17 18:08:00 +00002186 {
Chris Lattnerf0f568b2010-12-19 17:52:50 +00002187 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Andersone63dda52010-12-17 18:08:00 +00002188 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattnerf0f568b2010-12-19 17:52:50 +00002189 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattner0fe80bb2010-12-19 18:38:44 +00002190 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattnerf0f568b2010-12-19 17:52:50 +00002191 return Res;
Owen Andersone63dda52010-12-17 18:08:00 +00002192 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002193
Chris Lattner02446fc2010-01-04 07:37:31 +00002194 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2195 if (I.isEquality() && CI->isZero() &&
2196 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
2197 // (icmp cond A B) if cond is equality
2198 return new ICmpInst(I.getPredicate(), A, B);
2199 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002200
Chris Lattner02446fc2010-01-04 07:37:31 +00002201 // If we have an icmp le or icmp ge instruction, turn it into the
2202 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
2203 // them being folded in the code below. The SimplifyICmpInst code has
2204 // already handled the edge cases for us, so we just assert on them.
2205 switch (I.getPredicate()) {
2206 default: break;
2207 case ICmpInst::ICMP_ULE:
2208 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
2209 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002210 Builder->getInt(CI->getValue()+1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002211 case ICmpInst::ICMP_SLE:
2212 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
2213 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002214 Builder->getInt(CI->getValue()+1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002215 case ICmpInst::ICMP_UGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00002216 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00002217 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002218 Builder->getInt(CI->getValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002219 case ICmpInst::ICMP_SGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00002220 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00002221 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002222 Builder->getInt(CI->getValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002223 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002224
Chris Lattner02446fc2010-01-04 07:37:31 +00002225 // If this comparison is a normal comparison, it demands all
2226 // bits, if it is a sign bit comparison, it only demands the sign bit.
2227 bool UnusedBit;
2228 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2229 }
2230
2231 // See if we can fold the comparison based on range information we can get
2232 // by checking whether bits are known to be zero or one in the input.
2233 if (BitWidth != 0) {
2234 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2235 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2236
2237 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersonda1c1222011-01-11 00:36:45 +00002238 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner02446fc2010-01-04 07:37:31 +00002239 Op0KnownZero, Op0KnownOne, 0))
2240 return &I;
2241 if (SimplifyDemandedBits(I.getOperandUse(1),
2242 APInt::getAllOnesValue(BitWidth),
2243 Op1KnownZero, Op1KnownOne, 0))
2244 return &I;
2245
2246 // Given the known and unknown bits, compute a range that the LHS could be
2247 // in. Compute the Min, Max and RHS values based on the known bits. For the
2248 // EQ and NE we use unsigned values.
2249 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2250 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2251 if (I.isSigned()) {
2252 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2253 Op0Min, Op0Max);
2254 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2255 Op1Min, Op1Max);
2256 } else {
2257 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2258 Op0Min, Op0Max);
2259 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2260 Op1Min, Op1Max);
2261 }
2262
2263 // If Min and Max are known to be the same, then SimplifyDemandedBits
2264 // figured out that the LHS is a constant. Just constant fold this now so
2265 // that code below can assume that Min != Max.
2266 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2267 return new ICmpInst(I.getPredicate(),
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002268 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00002269 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2270 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002271 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner02446fc2010-01-04 07:37:31 +00002272
2273 // Based on the range information we know about the LHS, see if we can
Nick Lewyckyd8d15842011-02-28 06:20:05 +00002274 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner02446fc2010-01-04 07:37:31 +00002275 switch (I.getPredicate()) {
2276 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner75d8f592010-11-21 06:44:42 +00002277 case ICmpInst::ICMP_EQ: {
Chris Lattner02446fc2010-01-04 07:37:31 +00002278 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002279 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002280
Chris Lattner75d8f592010-11-21 06:44:42 +00002281 // If all bits are known zero except for one, then we know at most one
2282 // bit is set. If the comparison is against zero, then this is a check
2283 // to see if *that* bit is set.
2284 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2285 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2286 // If the LHS is an AND with the same constant, look through it.
2287 Value *LHS = 0;
2288 ConstantInt *LHSC = 0;
2289 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2290 LHSC->getValue() != Op0KnownZeroInverted)
2291 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002292
Chris Lattner75d8f592010-11-21 06:44:42 +00002293 // 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 +00002294 // then turn "((1 << x)&8) == 0" into "x != 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002295 Value *X = 0;
2296 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2297 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002298 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002299 ConstantInt::get(X->getType(), CmpVal));
2300 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002301
Chris Lattner75d8f592010-11-21 06:44:42 +00002302 // 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 +00002303 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002304 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002305 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002306 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002307 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002308 ConstantInt::get(X->getType(),
2309 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002310 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002311
Chris Lattner02446fc2010-01-04 07:37:31 +00002312 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002313 }
2314 case ICmpInst::ICMP_NE: {
Chris Lattner02446fc2010-01-04 07:37:31 +00002315 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002316 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002317
Chris Lattner75d8f592010-11-21 06:44:42 +00002318 // If all bits are known zero except for one, then we know at most one
2319 // bit is set. If the comparison is against zero, then this is a check
2320 // to see if *that* bit is set.
2321 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2322 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2323 // If the LHS is an AND with the same constant, look through it.
2324 Value *LHS = 0;
2325 ConstantInt *LHSC = 0;
2326 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2327 LHSC->getValue() != Op0KnownZeroInverted)
2328 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002329
Chris Lattner75d8f592010-11-21 06:44:42 +00002330 // 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 +00002331 // then turn "((1 << x)&8) != 0" into "x == 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002332 Value *X = 0;
2333 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2334 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002335 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002336 ConstantInt::get(X->getType(), CmpVal));
2337 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002338
Chris Lattner75d8f592010-11-21 06:44:42 +00002339 // 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 +00002340 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002341 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002342 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002343 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002344 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002345 ConstantInt::get(X->getType(),
2346 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002347 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002348
Chris Lattner02446fc2010-01-04 07:37:31 +00002349 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002350 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002351 case ICmpInst::ICMP_ULT:
2352 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002353 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002354 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002355 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002356 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2357 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2358 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2359 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2360 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002361 Builder->getInt(CI->getValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002362
2363 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2364 if (CI->isMinValue(true))
2365 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2366 Constant::getAllOnesValue(Op0->getType()));
2367 }
2368 break;
2369 case ICmpInst::ICMP_UGT:
2370 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002371 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002372 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002373 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002374
2375 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2376 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2377 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2378 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2379 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002380 Builder->getInt(CI->getValue()+1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002381
2382 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2383 if (CI->isMaxValue(true))
2384 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2385 Constant::getNullValue(Op0->getType()));
2386 }
2387 break;
2388 case ICmpInst::ICMP_SLT:
2389 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002390 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002391 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002392 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002393 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2394 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2395 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2396 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2397 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002398 Builder->getInt(CI->getValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002399 }
2400 break;
2401 case ICmpInst::ICMP_SGT:
2402 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002403 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002404 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002405 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002406
2407 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2408 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2409 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2410 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2411 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002412 Builder->getInt(CI->getValue()+1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002413 }
2414 break;
2415 case ICmpInst::ICMP_SGE:
2416 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2417 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002418 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002419 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002420 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002421 break;
2422 case ICmpInst::ICMP_SLE:
2423 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2424 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002425 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002426 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002427 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002428 break;
2429 case ICmpInst::ICMP_UGE:
2430 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2431 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002432 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002433 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002434 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002435 break;
2436 case ICmpInst::ICMP_ULE:
2437 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2438 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002439 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002440 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002441 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002442 break;
2443 }
2444
2445 // Turn a signed comparison into an unsigned one if both operands
2446 // are known to have the same sign.
2447 if (I.isSigned() &&
2448 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2449 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2450 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2451 }
2452
2453 // Test if the ICmpInst instruction is used exclusively by a select as
2454 // part of a minimum or maximum operation. If so, refrain from doing
2455 // any other folding. This helps out other analyses which understand
2456 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2457 // and CodeGen. And in this case, at least one of the comparison
2458 // operands has at least one user besides the compare (the select),
2459 // which would often largely negate the benefit of folding anyway.
2460 if (I.hasOneUse())
2461 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2462 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2463 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2464 return 0;
2465
2466 // See if we are doing a comparison between a constant and an instruction that
2467 // can be folded into the comparison.
2468 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002469 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2470 // instruction, see if that instruction also has constants so that the
2471 // instruction can be folded into the icmp
Chris Lattner02446fc2010-01-04 07:37:31 +00002472 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2473 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2474 return Res;
2475 }
2476
2477 // Handle icmp with constant (but not simple integer constant) RHS
2478 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2479 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2480 switch (LHSI->getOpcode()) {
2481 case Instruction::GetElementPtr:
2482 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2483 if (RHSC->isNullValue() &&
2484 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2485 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2486 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2487 break;
2488 case Instruction::PHI:
2489 // Only fold icmp into the PHI if the phi and icmp are in the same
2490 // block. If in the same block, we're encouraging jump threading. If
2491 // not, we are just pessimizing the code by making an i1 phi.
2492 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002493 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002494 return NV;
2495 break;
2496 case Instruction::Select: {
2497 // If either operand of the select is a constant, we can fold the
2498 // comparison into the select arms, which will cause one to be
2499 // constant folded and the select turned into a bitwise or.
2500 Value *Op1 = 0, *Op2 = 0;
2501 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2502 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2503 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2504 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2505
2506 // We only want to perform this transformation if it will not lead to
2507 // additional code. This is true if either both sides of the select
2508 // fold to a constant (in which case the icmp is replaced with a select
2509 // which will usually simplify) or this is the only user of the
2510 // select (in which case we are trading a select+icmp for a simpler
2511 // select+icmp).
2512 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2513 if (!Op1)
2514 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2515 RHSC, I.getName());
2516 if (!Op2)
2517 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2518 RHSC, I.getName());
2519 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2520 }
2521 break;
2522 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002523 case Instruction::IntToPtr:
2524 // icmp pred inttoptr(X), null -> icmp pred X, 0
2525 if (RHSC->isNullValue() && TD &&
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00002526 TD->getIntPtrType(RHSC->getType()) ==
Chris Lattner02446fc2010-01-04 07:37:31 +00002527 LHSI->getOperand(0)->getType())
2528 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2529 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2530 break;
2531
2532 case Instruction::Load:
2533 // Try to optimize things like "A[i] > 4" to index computations.
2534 if (GetElementPtrInst *GEP =
2535 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2536 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2537 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2538 !cast<LoadInst>(LHSI)->isVolatile())
2539 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2540 return Res;
2541 }
2542 break;
2543 }
2544 }
2545
2546 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2547 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2548 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2549 return NI;
2550 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2551 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2552 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2553 return NI;
2554
2555 // Test to see if the operands of the icmp are casted versions of other
2556 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
2557 // now.
2558 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002559 if (Op0->getType()->isPointerTy() &&
2560 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002561 // We keep moving the cast from the left operand over to the right
2562 // operand, where it can often be eliminated completely.
2563 Op0 = CI->getOperand(0);
2564
2565 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2566 // so eliminate it as well.
2567 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2568 Op1 = CI2->getOperand(0);
2569
2570 // If Op1 is a constant, we can fold the cast into the constant.
2571 if (Op0->getType() != Op1->getType()) {
2572 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2573 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2574 } else {
2575 // Otherwise, cast the RHS right before the icmp
2576 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2577 }
2578 }
2579 return new ICmpInst(I.getPredicate(), Op0, Op1);
2580 }
2581 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002582
Chris Lattner02446fc2010-01-04 07:37:31 +00002583 if (isa<CastInst>(Op0)) {
2584 // Handle the special case of: icmp (cast bool to X), <cst>
2585 // This comes up when you have code like
2586 // int X = A < B;
2587 // if (X) ...
2588 // For generality, we handle any zero-extension of any operand comparison
2589 // with a constant or another cast from the same type.
2590 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2591 if (Instruction *R = visitICmpInstWithCastAndCast(I))
2592 return R;
2593 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002594
Duncan Sandsa7724332011-02-17 07:46:37 +00002595 // Special logic for binary operators.
2596 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2597 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2598 if (BO0 || BO1) {
2599 CmpInst::Predicate Pred = I.getPredicate();
2600 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2601 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2602 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2603 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2604 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2605 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2606 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2607 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2608 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2609
2610 // Analyze the case when either Op0 or Op1 is an add instruction.
2611 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2612 Value *A = 0, *B = 0, *C = 0, *D = 0;
2613 if (BO0 && BO0->getOpcode() == Instruction::Add)
2614 A = BO0->getOperand(0), B = BO0->getOperand(1);
2615 if (BO1 && BO1->getOpcode() == Instruction::Add)
2616 C = BO1->getOperand(0), D = BO1->getOperand(1);
2617
2618 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2619 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2620 return new ICmpInst(Pred, A == Op1 ? B : A,
2621 Constant::getNullValue(Op1->getType()));
2622
2623 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2624 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2625 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2626 C == Op0 ? D : C);
2627
Duncan Sands39a7de72011-02-18 16:25:37 +00002628 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002629 if (A && C && (A == C || A == D || B == C || B == D) &&
2630 NoOp0WrapProblem && NoOp1WrapProblem &&
2631 // Try not to increase register pressure.
2632 BO0->hasOneUse() && BO1->hasOneUse()) {
2633 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsafe45392012-11-16 18:55:49 +00002634 Value *Y, *Z;
2635 if (A == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002636 // C + B == C + D -> B == D
Duncan Sandsafe45392012-11-16 18:55:49 +00002637 Y = B;
2638 Z = D;
2639 } else if (A == D) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002640 // D + B == C + D -> B == C
Duncan Sandsafe45392012-11-16 18:55:49 +00002641 Y = B;
2642 Z = C;
2643 } else if (B == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002644 // A + C == C + D -> A == D
Duncan Sandsafe45392012-11-16 18:55:49 +00002645 Y = A;
2646 Z = D;
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002647 } else {
2648 assert(B == D);
2649 // A + D == C + D -> A == C
Duncan Sandsafe45392012-11-16 18:55:49 +00002650 Y = A;
2651 Z = C;
2652 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002653 return new ICmpInst(Pred, Y, Z);
2654 }
2655
David Majnemer59b11c42013-04-11 20:05:46 +00002656 // icmp slt (X + -1), Y -> icmp sle X, Y
2657 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
2658 match(B, m_AllOnes()))
2659 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
2660
2661 // icmp sge (X + -1), Y -> icmp sgt X, Y
2662 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
2663 match(B, m_AllOnes()))
2664 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
2665
2666 // icmp sle (X + 1), Y -> icmp slt X, Y
2667 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
2668 match(B, m_One()))
2669 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
2670
2671 // icmp sgt (X + 1), Y -> icmp sge X, Y
2672 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
2673 match(B, m_One()))
2674 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
2675
2676 // if C1 has greater magnitude than C2:
2677 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
2678 // s.t. C3 = C1 - C2
2679 //
2680 // if C2 has greater magnitude than C1:
2681 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
2682 // s.t. C3 = C2 - C1
2683 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
2684 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
2685 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
2686 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
2687 const APInt &AP1 = C1->getValue();
2688 const APInt &AP2 = C2->getValue();
2689 if (AP1.isNegative() == AP2.isNegative()) {
2690 APInt AP1Abs = C1->getValue().abs();
2691 APInt AP2Abs = C2->getValue().abs();
2692 if (AP1Abs.uge(AP2Abs)) {
2693 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
2694 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
2695 return new ICmpInst(Pred, NewAdd, C);
2696 } else {
2697 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
2698 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
2699 return new ICmpInst(Pred, A, NewAdd);
2700 }
2701 }
2702 }
2703
2704
Duncan Sandsa7724332011-02-17 07:46:37 +00002705 // Analyze the case when either Op0 or Op1 is a sub instruction.
2706 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2707 A = 0; B = 0; C = 0; D = 0;
2708 if (BO0 && BO0->getOpcode() == Instruction::Sub)
2709 A = BO0->getOperand(0), B = BO0->getOperand(1);
2710 if (BO1 && BO1->getOpcode() == Instruction::Sub)
2711 C = BO1->getOperand(0), D = BO1->getOperand(1);
2712
Duncan Sands39a7de72011-02-18 16:25:37 +00002713 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2714 if (A == Op1 && NoOp0WrapProblem)
2715 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2716
2717 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2718 if (C == Op0 && NoOp1WrapProblem)
2719 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2720
2721 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002722 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2723 // Try not to increase register pressure.
2724 BO0->hasOneUse() && BO1->hasOneUse())
2725 return new ICmpInst(Pred, A, C);
2726
Duncan Sands39a7de72011-02-18 16:25:37 +00002727 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2728 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2729 // Try not to increase register pressure.
2730 BO0->hasOneUse() && BO1->hasOneUse())
2731 return new ICmpInst(Pred, D, B);
2732
Nick Lewycky9feda172011-03-05 04:28:48 +00002733 BinaryOperator *SRem = NULL;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002734 // icmp (srem X, Y), Y
Nick Lewycky9feda172011-03-05 04:28:48 +00002735 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2736 Op1 == BO0->getOperand(1))
2737 SRem = BO0;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002738 // icmp Y, (srem X, Y)
Nick Lewycky9feda172011-03-05 04:28:48 +00002739 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2740 Op0 == BO1->getOperand(1))
2741 SRem = BO1;
2742 if (SRem) {
2743 // We don't check hasOneUse to avoid increasing register pressure because
2744 // the value we use is the same value this instruction was already using.
2745 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2746 default: break;
2747 case ICmpInst::ICMP_EQ:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002748 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002749 case ICmpInst::ICMP_NE:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002750 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002751 case ICmpInst::ICMP_SGT:
2752 case ICmpInst::ICMP_SGE:
2753 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2754 Constant::getAllOnesValue(SRem->getType()));
2755 case ICmpInst::ICMP_SLT:
2756 case ICmpInst::ICMP_SLE:
2757 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2758 Constant::getNullValue(SRem->getType()));
2759 }
2760 }
2761
Duncan Sandsa7724332011-02-17 07:46:37 +00002762 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2763 BO0->hasOneUse() && BO1->hasOneUse() &&
2764 BO0->getOperand(1) == BO1->getOperand(1)) {
2765 switch (BO0->getOpcode()) {
2766 default: break;
2767 case Instruction::Add:
2768 case Instruction::Sub:
2769 case Instruction::Xor:
2770 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
2771 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2772 BO1->getOperand(0));
2773 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2774 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2775 if (CI->getValue().isSignBit()) {
2776 ICmpInst::Predicate Pred = I.isSigned()
2777 ? I.getUnsignedPredicate()
2778 : I.getSignedPredicate();
2779 return new ICmpInst(Pred, BO0->getOperand(0),
2780 BO1->getOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00002781 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002782
Chris Lattnerc73b24d2011-07-15 06:08:15 +00002783 if (CI->isMaxValue(true)) {
Duncan Sandsa7724332011-02-17 07:46:37 +00002784 ICmpInst::Predicate Pred = I.isSigned()
2785 ? I.getUnsignedPredicate()
2786 : I.getSignedPredicate();
2787 Pred = I.getSwappedPredicate(Pred);
2788 return new ICmpInst(Pred, BO0->getOperand(0),
2789 BO1->getOperand(0));
2790 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002791 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002792 break;
2793 case Instruction::Mul:
2794 if (!I.isEquality())
2795 break;
2796
2797 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2798 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2799 // Mask = -1 >> count-trailing-zeros(Cst).
2800 if (!CI->isZero() && !CI->isOne()) {
2801 const APInt &AP = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002802 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandsa7724332011-02-17 07:46:37 +00002803 APInt::getLowBitsSet(AP.getBitWidth(),
2804 AP.getBitWidth() -
2805 AP.countTrailingZeros()));
2806 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2807 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2808 return new ICmpInst(I.getPredicate(), And1, And2);
2809 }
2810 }
2811 break;
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002812 case Instruction::UDiv:
2813 case Instruction::LShr:
2814 if (I.isSigned())
2815 break;
2816 // fall-through
2817 case Instruction::SDiv:
2818 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002819 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002820 break;
2821 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2822 BO1->getOperand(0));
2823 case Instruction::Shl: {
2824 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2825 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2826 if (!NUW && !NSW)
2827 break;
2828 if (!NSW && I.isSigned())
2829 break;
2830 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2831 BO1->getOperand(0));
2832 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002833 }
2834 }
2835 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002836
Chris Lattner02446fc2010-01-04 07:37:31 +00002837 { Value *A, *B;
David Majnemerfb1cd692013-04-12 17:25:07 +00002838 // Transform (A & ~B) == 0 --> (A & B) != 0
2839 // and (A & ~B) != 0 --> (A & B) == 0
2840 // if A is a power of 2.
2841 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2842 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A) && I.isEquality())
2843 return new ICmpInst(I.getInversePredicate(),
2844 Builder->CreateAnd(A, B),
2845 Op1);
2846
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002847 // ~x < ~y --> y < x
2848 // ~x < cst --> ~cst < x
2849 if (match(Op0, m_Not(m_Value(A)))) {
2850 if (match(Op1, m_Not(m_Value(B))))
2851 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner27a98482011-01-15 05:42:47 +00002852 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002853 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2854 }
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002855
2856 // (a+b) <u a --> llvm.uadd.with.overflow.
2857 // (a+b) <u b --> llvm.uadd.with.overflow.
2858 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002859 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002860 (Op1 == A || Op1 == B))
2861 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2862 return R;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002863
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002864 // a >u (a+b) --> llvm.uadd.with.overflow.
2865 // b >u (a+b) --> llvm.uadd.with.overflow.
2866 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2867 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2868 (Op0 == A || Op0 == B))
2869 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2870 return R;
Chris Lattner02446fc2010-01-04 07:37:31 +00002871 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002872
Chris Lattner02446fc2010-01-04 07:37:31 +00002873 if (I.isEquality()) {
2874 Value *A, *B, *C, *D;
Duncan Sands39a7de72011-02-18 16:25:37 +00002875
Chris Lattner02446fc2010-01-04 07:37:31 +00002876 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2877 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
2878 Value *OtherVal = A == Op1 ? B : A;
2879 return new ICmpInst(I.getPredicate(), OtherVal,
2880 Constant::getNullValue(A->getType()));
2881 }
2882
2883 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2884 // A^c1 == C^c2 --> A == C^(c1^c2)
2885 ConstantInt *C1, *C2;
2886 if (match(B, m_ConstantInt(C1)) &&
2887 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszak3facc432013-06-06 20:18:46 +00002888 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramera9390a42011-09-27 20:39:19 +00002889 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner02446fc2010-01-04 07:37:31 +00002890 return new ICmpInst(I.getPredicate(), A, Xor);
2891 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002892
Chris Lattner02446fc2010-01-04 07:37:31 +00002893 // A^B == A^D -> B == D
2894 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2895 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2896 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2897 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2898 }
2899 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002900
Chris Lattner02446fc2010-01-04 07:37:31 +00002901 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2902 (A == Op0 || B == Op0)) {
2903 // A == (A^B) -> B == 0
2904 Value *OtherVal = A == Op0 ? B : A;
2905 return new ICmpInst(I.getPredicate(), OtherVal,
2906 Constant::getNullValue(A->getType()));
2907 }
2908
Chris Lattner02446fc2010-01-04 07:37:31 +00002909 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002910 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner5036ce42011-04-26 20:02:45 +00002911 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002912 Value *X = 0, *Y = 0, *Z = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002913
Chris Lattner02446fc2010-01-04 07:37:31 +00002914 if (A == C) {
2915 X = B; Y = D; Z = A;
2916 } else if (A == D) {
2917 X = B; Y = C; Z = A;
2918 } else if (B == C) {
2919 X = A; Y = D; Z = B;
2920 } else if (B == D) {
2921 X = A; Y = C; Z = B;
2922 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002923
Chris Lattner02446fc2010-01-04 07:37:31 +00002924 if (X) { // Build (X^Y) & Z
Benjamin Kramera9390a42011-09-27 20:39:19 +00002925 Op1 = Builder->CreateXor(X, Y);
2926 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner02446fc2010-01-04 07:37:31 +00002927 I.setOperand(0, Op1);
2928 I.setOperand(1, Constant::getNullValue(Op1->getType()));
2929 return &I;
2930 }
2931 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002932
Benjamin Kramer66821d92012-06-10 20:35:00 +00002933 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer7a99b462012-06-11 08:01:25 +00002934 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer66821d92012-06-10 20:35:00 +00002935 ConstantInt *Cst1;
Benjamin Kramer7a99b462012-06-11 08:01:25 +00002936 if ((Op0->hasOneUse() &&
2937 match(Op0, m_ZExt(m_Value(A))) &&
2938 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
2939 (Op1->hasOneUse() &&
2940 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
2941 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer66821d92012-06-10 20:35:00 +00002942 APInt Pow2 = Cst1->getValue() + 1;
2943 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
2944 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
2945 return new ICmpInst(I.getPredicate(), A,
2946 Builder->CreateTrunc(B, A->getType()));
2947 }
2948
Chris Lattner325eeb12011-04-26 20:18:20 +00002949 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2950 // "icmp (and X, mask), cst"
2951 uint64_t ShAmt = 0;
Chris Lattner325eeb12011-04-26 20:18:20 +00002952 if (Op0->hasOneUse() &&
2953 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2954 m_ConstantInt(ShAmt))))) &&
2955 match(Op1, m_ConstantInt(Cst1)) &&
2956 // Only do this when A has multiple uses. This is most important to do
2957 // when it exposes other optimizations.
2958 !A->hasOneUse()) {
2959 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002960
Chris Lattner325eeb12011-04-26 20:18:20 +00002961 if (ShAmt < ASize) {
2962 APInt MaskV =
2963 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2964 MaskV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002965
Chris Lattner325eeb12011-04-26 20:18:20 +00002966 APInt CmpV = Cst1->getValue().zext(ASize);
2967 CmpV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002968
Chris Lattner325eeb12011-04-26 20:18:20 +00002969 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2970 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2971 }
2972 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002973 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002974
Chris Lattner02446fc2010-01-04 07:37:31 +00002975 {
2976 Value *X; ConstantInt *Cst;
2977 // icmp X+Cst, X
2978 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Benjamin Kramer19a6f112013-09-20 22:12:42 +00002979 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
Chris Lattner02446fc2010-01-04 07:37:31 +00002980
2981 // icmp X, X+Cst
2982 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Benjamin Kramer19a6f112013-09-20 22:12:42 +00002983 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner02446fc2010-01-04 07:37:31 +00002984 }
2985 return Changed ? &I : 0;
2986}
2987
Chris Lattner02446fc2010-01-04 07:37:31 +00002988/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2989///
2990Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2991 Instruction *LHSI,
2992 Constant *RHSC) {
2993 if (!isa<ConstantFP>(RHSC)) return 0;
2994 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002995
Chris Lattner02446fc2010-01-04 07:37:31 +00002996 // Get the width of the mantissa. We don't want to hack on conversions that
2997 // might lose information from the integer, e.g. "i64 -> float"
2998 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2999 if (MantissaWidth == -1) return 0; // Unknown.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003000
Chris Lattner02446fc2010-01-04 07:37:31 +00003001 // Check to see that the input is converted from an integer type that is small
3002 // enough that preserves all bits. TODO: check here for "known" sign bits.
3003 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
3004 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003005
Chris Lattner02446fc2010-01-04 07:37:31 +00003006 // If this is a uitofp instruction, we need an extra bit to hold the sign.
3007 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
3008 if (LHSUnsigned)
3009 ++InputSize;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003010
Chris Lattner02446fc2010-01-04 07:37:31 +00003011 // If the conversion would lose info, don't hack on this.
3012 if ((int)InputSize > MantissaWidth)
3013 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003014
Chris Lattner02446fc2010-01-04 07:37:31 +00003015 // Otherwise, we can potentially simplify the comparison. We know that it
3016 // will always come through as an integer value and we know the constant is
3017 // not a NAN (it would have been previously simplified).
3018 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003019
Chris Lattner02446fc2010-01-04 07:37:31 +00003020 ICmpInst::Predicate Pred;
3021 switch (I.getPredicate()) {
3022 default: llvm_unreachable("Unexpected predicate!");
3023 case FCmpInst::FCMP_UEQ:
3024 case FCmpInst::FCMP_OEQ:
3025 Pred = ICmpInst::ICMP_EQ;
3026 break;
3027 case FCmpInst::FCMP_UGT:
3028 case FCmpInst::FCMP_OGT:
3029 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
3030 break;
3031 case FCmpInst::FCMP_UGE:
3032 case FCmpInst::FCMP_OGE:
3033 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
3034 break;
3035 case FCmpInst::FCMP_ULT:
3036 case FCmpInst::FCMP_OLT:
3037 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
3038 break;
3039 case FCmpInst::FCMP_ULE:
3040 case FCmpInst::FCMP_OLE:
3041 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
3042 break;
3043 case FCmpInst::FCMP_UNE:
3044 case FCmpInst::FCMP_ONE:
3045 Pred = ICmpInst::ICMP_NE;
3046 break;
3047 case FCmpInst::FCMP_ORD:
Jakub Staszak3facc432013-06-06 20:18:46 +00003048 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +00003049 case FCmpInst::FCMP_UNO:
Jakub Staszak3facc432013-06-06 20:18:46 +00003050 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003051 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003052
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003053 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003054
Chris Lattner02446fc2010-01-04 07:37:31 +00003055 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003056
Chris Lattner02446fc2010-01-04 07:37:31 +00003057 // See if the FP constant is too large for the integer. For example,
3058 // comparing an i8 to 300.0.
3059 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003060
Chris Lattner02446fc2010-01-04 07:37:31 +00003061 if (!LHSUnsigned) {
3062 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
3063 // and large values.
Michael Gottesman4dfc2572013-06-27 21:58:19 +00003064 APFloat SMax(RHS.getSemantics());
Chris Lattner02446fc2010-01-04 07:37:31 +00003065 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
3066 APFloat::rmNearestTiesToEven);
3067 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
3068 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
3069 Pred == ICmpInst::ICMP_SLE)
Jakub Staszak3facc432013-06-06 20:18:46 +00003070 return ReplaceInstUsesWith(I, Builder->getTrue());
3071 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003072 }
3073 } else {
3074 // If the RHS value is > UnsignedMax, fold the comparison. This handles
3075 // +INF and large values.
Michael Gottesman4dfc2572013-06-27 21:58:19 +00003076 APFloat UMax(RHS.getSemantics());
Chris Lattner02446fc2010-01-04 07:37:31 +00003077 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
3078 APFloat::rmNearestTiesToEven);
3079 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
3080 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
3081 Pred == ICmpInst::ICMP_ULE)
Jakub Staszak3facc432013-06-06 20:18:46 +00003082 return ReplaceInstUsesWith(I, Builder->getTrue());
3083 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003084 }
3085 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003086
Chris Lattner02446fc2010-01-04 07:37:31 +00003087 if (!LHSUnsigned) {
3088 // See if the RHS value is < SignedMin.
Michael Gottesman4dfc2572013-06-27 21:58:19 +00003089 APFloat SMin(RHS.getSemantics());
Chris Lattner02446fc2010-01-04 07:37:31 +00003090 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
3091 APFloat::rmNearestTiesToEven);
3092 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
3093 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
3094 Pred == ICmpInst::ICMP_SGE)
Jakub Staszak3facc432013-06-06 20:18:46 +00003095 return ReplaceInstUsesWith(I, Builder->getTrue());
3096 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003097 }
Devang Patela2e0f6b2012-02-13 23:05:18 +00003098 } else {
3099 // See if the RHS value is < UnsignedMin.
Michael Gottesman4dfc2572013-06-27 21:58:19 +00003100 APFloat SMin(RHS.getSemantics());
Devang Patela2e0f6b2012-02-13 23:05:18 +00003101 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
3102 APFloat::rmNearestTiesToEven);
3103 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
3104 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
3105 Pred == ICmpInst::ICMP_UGE)
Jakub Staszak3facc432013-06-06 20:18:46 +00003106 return ReplaceInstUsesWith(I, Builder->getTrue());
3107 return ReplaceInstUsesWith(I, Builder->getFalse());
Devang Patela2e0f6b2012-02-13 23:05:18 +00003108 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003109 }
3110
3111 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
3112 // [0, UMAX], but it may still be fractional. See if it is fractional by
3113 // casting the FP value to the integer value and back, checking for equality.
3114 // Don't do this for zero, because -0.0 is not fractional.
3115 Constant *RHSInt = LHSUnsigned
3116 ? ConstantExpr::getFPToUI(RHSC, IntTy)
3117 : ConstantExpr::getFPToSI(RHSC, IntTy);
3118 if (!RHS.isZero()) {
3119 bool Equal = LHSUnsigned
3120 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
3121 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
3122 if (!Equal) {
3123 // If we had a comparison against a fractional value, we have to adjust
3124 // the compare predicate and sometimes the value. RHSC is rounded towards
3125 // zero at this point.
3126 switch (Pred) {
3127 default: llvm_unreachable("Unexpected integer comparison!");
3128 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Jakub Staszak3facc432013-06-06 20:18:46 +00003129 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +00003130 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Jakub Staszak3facc432013-06-06 20:18:46 +00003131 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003132 case ICmpInst::ICMP_ULE:
3133 // (float)int <= 4.4 --> int <= 4
3134 // (float)int <= -4.4 --> false
3135 if (RHS.isNegative())
Jakub Staszak3facc432013-06-06 20:18:46 +00003136 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003137 break;
3138 case ICmpInst::ICMP_SLE:
3139 // (float)int <= 4.4 --> int <= 4
3140 // (float)int <= -4.4 --> int < -4
3141 if (RHS.isNegative())
3142 Pred = ICmpInst::ICMP_SLT;
3143 break;
3144 case ICmpInst::ICMP_ULT:
3145 // (float)int < -4.4 --> false
3146 // (float)int < 4.4 --> int <= 4
3147 if (RHS.isNegative())
Jakub Staszak3facc432013-06-06 20:18:46 +00003148 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003149 Pred = ICmpInst::ICMP_ULE;
3150 break;
3151 case ICmpInst::ICMP_SLT:
3152 // (float)int < -4.4 --> int < -4
3153 // (float)int < 4.4 --> int <= 4
3154 if (!RHS.isNegative())
3155 Pred = ICmpInst::ICMP_SLE;
3156 break;
3157 case ICmpInst::ICMP_UGT:
3158 // (float)int > 4.4 --> int > 4
3159 // (float)int > -4.4 --> true
3160 if (RHS.isNegative())
Jakub Staszak3facc432013-06-06 20:18:46 +00003161 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +00003162 break;
3163 case ICmpInst::ICMP_SGT:
3164 // (float)int > 4.4 --> int > 4
3165 // (float)int > -4.4 --> int >= -4
3166 if (RHS.isNegative())
3167 Pred = ICmpInst::ICMP_SGE;
3168 break;
3169 case ICmpInst::ICMP_UGE:
3170 // (float)int >= -4.4 --> true
3171 // (float)int >= 4.4 --> int > 4
Bob Wilsonf12c95a2012-08-07 22:35:16 +00003172 if (RHS.isNegative())
Jakub Staszak3facc432013-06-06 20:18:46 +00003173 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +00003174 Pred = ICmpInst::ICMP_UGT;
3175 break;
3176 case ICmpInst::ICMP_SGE:
3177 // (float)int >= -4.4 --> int >= -4
3178 // (float)int >= 4.4 --> int > 4
3179 if (!RHS.isNegative())
3180 Pred = ICmpInst::ICMP_SGT;
3181 break;
3182 }
3183 }
3184 }
3185
3186 // Lower this FP comparison into an appropriate integer version of the
3187 // comparison.
3188 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
3189}
3190
3191Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
3192 bool Changed = false;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003193
Chris Lattner02446fc2010-01-04 07:37:31 +00003194 /// Orders the operands of the compare so that they are listed from most
3195 /// complex to least complex. This puts constants before unary operators,
3196 /// before binary operators.
3197 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
3198 I.swapOperands();
3199 Changed = true;
3200 }
3201
3202 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003203
Chris Lattner02446fc2010-01-04 07:37:31 +00003204 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
3205 return ReplaceInstUsesWith(I, V);
3206
3207 // Simplify 'fcmp pred X, X'
3208 if (Op0 == Op1) {
3209 switch (I.getPredicate()) {
3210 default: llvm_unreachable("Unknown predicate!");
3211 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
3212 case FCmpInst::FCMP_ULT: // True if unordered or less than
3213 case FCmpInst::FCMP_UGT: // True if unordered or greater than
3214 case FCmpInst::FCMP_UNE: // True if unordered or not equal
3215 // Canonicalize these to be 'fcmp uno %X, 0.0'.
3216 I.setPredicate(FCmpInst::FCMP_UNO);
3217 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3218 return &I;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003219
Chris Lattner02446fc2010-01-04 07:37:31 +00003220 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
3221 case FCmpInst::FCMP_OEQ: // True if ordered and equal
3222 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
3223 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
3224 // Canonicalize these to be 'fcmp ord %X, 0.0'.
3225 I.setPredicate(FCmpInst::FCMP_ORD);
3226 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3227 return &I;
3228 }
3229 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003230
Chris Lattner02446fc2010-01-04 07:37:31 +00003231 // Handle fcmp with constant RHS
3232 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3233 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3234 switch (LHSI->getOpcode()) {
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00003235 case Instruction::FPExt: {
3236 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
3237 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
3238 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
3239 if (!RHSF)
3240 break;
3241
3242 const fltSemantics *Sem;
3243 // FIXME: This shouldn't be here.
Dan Gohmance163392011-12-17 00:04:22 +00003244 if (LHSExt->getSrcTy()->isHalfTy())
3245 Sem = &APFloat::IEEEhalf;
3246 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00003247 Sem = &APFloat::IEEEsingle;
3248 else if (LHSExt->getSrcTy()->isDoubleTy())
3249 Sem = &APFloat::IEEEdouble;
3250 else if (LHSExt->getSrcTy()->isFP128Ty())
3251 Sem = &APFloat::IEEEquad;
3252 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
3253 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand3467b9f2012-10-30 12:33:18 +00003254 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
3255 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00003256 else
3257 break;
3258
3259 bool Lossy;
3260 APFloat F = RHSF->getValueAPF();
3261 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
3262
Jim Grosbachcbf676b2011-09-30 18:45:50 +00003263 // Avoid lossy conversions and denormals. Zero is a special case
3264 // that's OK to convert.
Jim Grosbach68e05fb2011-09-30 19:58:46 +00003265 APFloat Fabs = F;
3266 Fabs.clearSign();
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00003267 if (!Lossy &&
Jim Grosbach68e05fb2011-09-30 19:58:46 +00003268 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
3269 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbachcbf676b2011-09-30 18:45:50 +00003270
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00003271 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3272 ConstantFP::get(RHSC->getContext(), F));
3273 break;
3274 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003275 case Instruction::PHI:
3276 // Only fold fcmp into the PHI if the phi and fcmp are in the same
3277 // block. If in the same block, we're encouraging jump threading. If
3278 // not, we are just pessimizing the code by making an i1 phi.
3279 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00003280 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00003281 return NV;
3282 break;
3283 case Instruction::SIToFP:
3284 case Instruction::UIToFP:
3285 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
3286 return NV;
3287 break;
3288 case Instruction::Select: {
3289 // If either operand of the select is a constant, we can fold the
3290 // comparison into the select arms, which will cause one to be
3291 // constant folded and the select turned into a bitwise or.
3292 Value *Op1 = 0, *Op2 = 0;
3293 if (LHSI->hasOneUse()) {
3294 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3295 // Fold the known value into the constant operand.
3296 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3297 // Insert a new FCmp of the other select operand.
3298 Op2 = Builder->CreateFCmp(I.getPredicate(),
3299 LHSI->getOperand(2), RHSC, I.getName());
3300 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3301 // Fold the known value into the constant operand.
3302 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3303 // Insert a new FCmp of the other select operand.
3304 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
3305 RHSC, I.getName());
3306 }
3307 }
3308
3309 if (Op1)
3310 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3311 break;
3312 }
Benjamin Kramer0db50182011-03-31 10:12:15 +00003313 case Instruction::FSub: {
3314 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3315 Value *Op;
3316 if (match(LHSI, m_FNeg(m_Value(Op))))
3317 return new FCmpInst(I.getSwappedPredicate(), Op,
3318 ConstantExpr::getFNeg(RHSC));
3319 break;
3320 }
Dan Gohman39516a62010-02-24 06:46:09 +00003321 case Instruction::Load:
3322 if (GetElementPtrInst *GEP =
3323 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3324 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3325 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3326 !cast<LoadInst>(LHSI)->isVolatile())
3327 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3328 return Res;
3329 }
3330 break;
Benjamin Kramer00abcd32012-08-18 20:06:47 +00003331 case Instruction::Call: {
3332 CallInst *CI = cast<CallInst>(LHSI);
3333 LibFunc::Func Func;
3334 // Various optimization for fabs compared with zero.
Benjamin Kramera4b57172012-08-18 22:04:34 +00003335 if (RHSC->isNullValue() && CI->getCalledFunction() &&
Benjamin Kramer00abcd32012-08-18 20:06:47 +00003336 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3337 TLI->has(Func)) {
3338 if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3339 Func == LibFunc::fabsl) {
3340 switch (I.getPredicate()) {
3341 default: break;
3342 // fabs(x) < 0 --> false
3343 case FCmpInst::FCMP_OLT:
3344 return ReplaceInstUsesWith(I, Builder->getFalse());
3345 // fabs(x) > 0 --> x != 0
3346 case FCmpInst::FCMP_OGT:
3347 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3348 RHSC);
3349 // fabs(x) <= 0 --> x == 0
3350 case FCmpInst::FCMP_OLE:
3351 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3352 RHSC);
3353 // fabs(x) >= 0 --> !isnan(x)
3354 case FCmpInst::FCMP_OGE:
3355 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3356 RHSC);
3357 // fabs(x) == 0 --> x == 0
3358 // fabs(x) != 0 --> x != 0
3359 case FCmpInst::FCMP_OEQ:
3360 case FCmpInst::FCMP_UEQ:
3361 case FCmpInst::FCMP_ONE:
3362 case FCmpInst::FCMP_UNE:
3363 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3364 RHSC);
3365 }
3366 }
3367 }
3368 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003369 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003370 }
3371
Benjamin Kramer00e00d62011-03-31 10:46:03 +00003372 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00003373 Value *X, *Y;
3374 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramer00e00d62011-03-31 10:46:03 +00003375 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00003376
Benjamin Kramercd0274c2011-03-31 10:11:58 +00003377 // fcmp (fpext x), (fpext y) -> fcmp x, y
3378 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3379 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3380 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3381 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3382 RHSExt->getOperand(0));
3383
Chris Lattner02446fc2010-01-04 07:37:31 +00003384 return Changed ? &I : 0;
3385}