blob: 226126b39ed733f48cde3d50261817d07638d107 [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.
Matt Arsenault3ca8f2e2013-09-30 21:11:01 +0000397 if (!GEP->isInBounds()) {
398 Type *IntPtrTy = TD->getIntPtrType(GEP->getType());
399 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
400 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
401 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
402 }
Matt Arsenault89062b82013-08-19 21:40:31 +0000403
Chris Lattner02446fc2010-01-04 07:37:31 +0000404 // If the comparison is only true for one or two elements, emit direct
405 // comparisons.
406 if (SecondTrueElement != Overdefined) {
407 // None true -> false.
408 if (FirstTrueElement == Undefined)
Jakub Staszak3facc432013-06-06 20:18:46 +0000409 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000410
Chris Lattner02446fc2010-01-04 07:37:31 +0000411 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000412
Chris Lattner02446fc2010-01-04 07:37:31 +0000413 // True for one element -> 'i == 47'.
414 if (SecondTrueElement == Undefined)
415 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000416
Chris Lattner02446fc2010-01-04 07:37:31 +0000417 // True for two elements -> 'i == 47 | i == 72'.
418 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
419 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
420 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
421 return BinaryOperator::CreateOr(C1, C2);
422 }
423
424 // If the comparison is only false for one or two elements, emit direct
425 // comparisons.
426 if (SecondFalseElement != Overdefined) {
427 // None false -> true.
428 if (FirstFalseElement == Undefined)
Jakub Staszak3facc432013-06-06 20:18:46 +0000429 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000430
Chris Lattner02446fc2010-01-04 07:37:31 +0000431 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
432
433 // False for one element -> 'i != 47'.
434 if (SecondFalseElement == Undefined)
435 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000436
Chris Lattner02446fc2010-01-04 07:37:31 +0000437 // False for two elements -> 'i != 47 & i != 72'.
438 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
439 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
440 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
441 return BinaryOperator::CreateAnd(C1, C2);
442 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000443
Chris Lattner02446fc2010-01-04 07:37:31 +0000444 // If the comparison can be replaced with a range comparison for the elements
445 // where it is true, emit the range check.
446 if (TrueRangeEnd != Overdefined) {
447 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000448
Chris Lattner02446fc2010-01-04 07:37:31 +0000449 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
450 if (FirstTrueElement) {
451 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
452 Idx = Builder->CreateAdd(Idx, Offs);
453 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000454
Chris Lattner02446fc2010-01-04 07:37:31 +0000455 Value *End = ConstantInt::get(Idx->getType(),
456 TrueRangeEnd-FirstTrueElement+1);
457 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
458 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000459
Chris Lattner02446fc2010-01-04 07:37:31 +0000460 // False range check.
461 if (FalseRangeEnd != Overdefined) {
462 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
463 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
464 if (FirstFalseElement) {
465 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
466 Idx = Builder->CreateAdd(Idx, Offs);
467 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000468
Chris Lattner02446fc2010-01-04 07:37:31 +0000469 Value *End = ConstantInt::get(Idx->getType(),
470 FalseRangeEnd-FirstFalseElement);
471 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
472 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000473
474
Arnaud A. de Grandmaison2be921a2013-03-22 08:25:01 +0000475 // If a magic bitvector captures the entire comparison state
Chris Lattner02446fc2010-01-04 07:37:31 +0000476 // of this load, replace it with computation that does:
477 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaison2be921a2013-03-22 08:25:01 +0000478 {
479 Type *Ty = 0;
480
481 // Look for an appropriate type:
482 // - The type of Idx if the magic fits
483 // - The smallest fitting legal type if we have a DataLayout
484 // - Default to i32
485 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
486 Ty = Idx->getType();
487 else if (TD)
488 Ty = TD->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
489 else if (ArrayElementCount <= 32)
Chris Lattner02446fc2010-01-04 07:37:31 +0000490 Ty = Type::getInt32Ty(Init->getContext());
Arnaud A. de Grandmaison2be921a2013-03-22 08:25:01 +0000491
492 if (Ty != 0) {
493 Value *V = Builder->CreateIntCast(Idx, Ty, false);
494 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
495 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
496 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
497 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000498 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000499
Chris Lattner02446fc2010-01-04 07:37:31 +0000500 return 0;
501}
502
503
504/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
505/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
506/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
507/// be complex, and scales are involved. The above expression would also be
508/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
509/// This later form is less amenable to optimization though, and we are allowed
510/// to generate the first by knowing that pointer arithmetic doesn't overflow.
511///
512/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000513///
Eli Friedman107ffd52011-05-18 23:11:30 +0000514static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000515 DataLayout &TD = *IC.getDataLayout();
Chris Lattner02446fc2010-01-04 07:37:31 +0000516 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000517
Chris Lattner02446fc2010-01-04 07:37:31 +0000518 // Check to see if this gep only has a single variable index. If so, and if
519 // any constant indices are a multiple of its scale, then we can compute this
520 // in terms of the scale of the variable index. For example, if the GEP
521 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
522 // because the expression will cross zero at the same point.
523 unsigned i, e = GEP->getNumOperands();
524 int64_t Offset = 0;
525 for (i = 1; i != e; ++i, ++GTI) {
526 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
527 // Compute the aggregate offset of constant indices.
528 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000529
Chris Lattner02446fc2010-01-04 07:37:31 +0000530 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000531 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000532 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
533 } else {
534 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
535 Offset += Size*CI->getSExtValue();
536 }
537 } else {
538 // Found our variable index.
539 break;
540 }
541 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000542
Chris Lattner02446fc2010-01-04 07:37:31 +0000543 // If there are no variable indices, we must have a constant offset, just
544 // evaluate it the general way.
545 if (i == e) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000546
Chris Lattner02446fc2010-01-04 07:37:31 +0000547 Value *VariableIdx = GEP->getOperand(i);
548 // Determine the scale factor of the variable element. For example, this is
549 // 4 if the variable index is into an array of i32.
550 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000551
Chris Lattner02446fc2010-01-04 07:37:31 +0000552 // Verify that there are no other variable indices. If so, emit the hard way.
553 for (++i, ++GTI; i != e; ++i, ++GTI) {
554 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
555 if (!CI) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000556
Chris Lattner02446fc2010-01-04 07:37:31 +0000557 // Compute the aggregate offset of constant indices.
558 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000559
Chris Lattner02446fc2010-01-04 07:37:31 +0000560 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000561 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000562 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
563 } else {
564 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
565 Offset += Size*CI->getSExtValue();
566 }
567 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000568
Matt Arsenault52c7d8e2013-08-21 19:53:10 +0000569
570
Chris Lattner02446fc2010-01-04 07:37:31 +0000571 // Okay, we know we have a single variable index, which must be a
572 // pointer/array/vector index. If there is no offset, life is simple, return
573 // the index.
Matt Arsenault52c7d8e2013-08-21 19:53:10 +0000574 Type *IntPtrTy = TD.getIntPtrType(GEP->getOperand(0)->getType());
575 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner02446fc2010-01-04 07:37:31 +0000576 if (Offset == 0) {
577 // Cast to intptrty in case a truncation occurs. If an extension is needed,
578 // we don't need to bother extending: the extension won't affect where the
579 // computation crosses zero.
Eli Friedman107ffd52011-05-18 23:11:30 +0000580 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman107ffd52011-05-18 23:11:30 +0000581 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
582 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000583 return VariableIdx;
584 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000585
Chris Lattner02446fc2010-01-04 07:37:31 +0000586 // Otherwise, there is an index. The computation we will do will be modulo
587 // the pointer size, so get it.
588 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000589
Chris Lattner02446fc2010-01-04 07:37:31 +0000590 Offset &= PtrSizeMask;
591 VariableScale &= PtrSizeMask;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000592
Chris Lattner02446fc2010-01-04 07:37:31 +0000593 // To do this transformation, any constant index must be a multiple of the
594 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
595 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
596 // multiple of the variable scale.
597 int64_t NewOffs = Offset / (int64_t)VariableScale;
598 if (Offset != NewOffs*(int64_t)VariableScale)
599 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000600
Chris Lattner02446fc2010-01-04 07:37:31 +0000601 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner02446fc2010-01-04 07:37:31 +0000602 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman107ffd52011-05-18 23:11:30 +0000603 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
604 true /*Signed*/);
Chris Lattner02446fc2010-01-04 07:37:31 +0000605 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman107ffd52011-05-18 23:11:30 +0000606 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner02446fc2010-01-04 07:37:31 +0000607}
608
609/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
610/// else. At this point we know that the GEP is on the LHS of the comparison.
611Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
612 ICmpInst::Predicate Cond,
613 Instruction &I) {
Benjamin Kramer8294eb52012-02-21 13:31:09 +0000614 // Don't transform signed compares of GEPs into index compares. Even if the
615 // GEP is inbounds, the final add of the base pointer can have signed overflow
616 // and would change the result of the icmp.
617 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramera42d5c42012-02-21 13:40:06 +0000618 // the maximum signed value for the pointer type.
Benjamin Kramer8294eb52012-02-21 13:31:09 +0000619 if (ICmpInst::isSigned(Cond))
620 return 0;
621
Chris Lattner02446fc2010-01-04 07:37:31 +0000622 // Look through bitcasts.
623 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
624 RHS = BCI->getOperand(0);
625
626 Value *PtrBase = GEPLHS->getOperand(0);
627 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
628 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
629 // This transformation (ignoring the base and scales) is valid because we
630 // know pointers can't overflow since the gep is inbounds. See if we can
631 // output an optimized form.
Eli Friedman107ffd52011-05-18 23:11:30 +0000632 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000633
Chris Lattner02446fc2010-01-04 07:37:31 +0000634 // If not, synthesize the offset the hard way.
635 if (Offset == 0)
636 Offset = EmitGEPOffset(GEPLHS);
637 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
638 Constant::getNullValue(Offset->getType()));
639 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
640 // If the base pointers are different, but the indices are the same, just
641 // compare the base pointer.
642 if (PtrBase != GEPRHS->getOperand(0)) {
643 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
644 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
645 GEPRHS->getOperand(0)->getType();
646 if (IndicesTheSame)
647 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
648 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
649 IndicesTheSame = false;
650 break;
651 }
652
653 // If all indices are the same, just compare the base pointers.
654 if (IndicesTheSame)
David Majnemerc22a4ee2013-06-29 10:28:04 +0000655 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +0000656
Benjamin Kramer9bb40852012-02-20 15:07:47 +0000657 // If we're comparing GEPs with two base pointers that only differ in type
658 // and both GEPs have only constant indices or just one use, then fold
659 // the compare with the adjusted indices.
Benjamin Kramer6ad48f42012-02-20 18:45:10 +0000660 if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer9bb40852012-02-20 15:07:47 +0000661 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
662 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
663 PtrBase->stripPointerCasts() ==
664 GEPRHS->getOperand(0)->stripPointerCasts()) {
665 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
666 EmitGEPOffset(GEPLHS),
667 EmitGEPOffset(GEPRHS));
668 return ReplaceInstUsesWith(I, Cmp);
669 }
670
Chris Lattner02446fc2010-01-04 07:37:31 +0000671 // Otherwise, the base pointers are different and the indices are
672 // different, bail out.
673 return 0;
674 }
675
676 // If one of the GEPs has all zero indices, recurse.
677 bool AllZeros = true;
678 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
679 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
680 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
681 AllZeros = false;
682 break;
683 }
684 if (AllZeros)
685 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemerdf703252013-06-29 09:45:35 +0000686 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner02446fc2010-01-04 07:37:31 +0000687
688 // If the other GEP has all zero indices, recurse.
689 AllZeros = true;
690 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
691 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
692 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
693 AllZeros = false;
694 break;
695 }
696 if (AllZeros)
697 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
698
Stuart Hastings67f071e2011-05-14 05:55:10 +0000699 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner02446fc2010-01-04 07:37:31 +0000700 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
701 // If the GEPs only differ by one index, compare it.
702 unsigned NumDifferences = 0; // Keep track of # differences.
703 unsigned DiffOperand = 0; // The operand that differs.
704 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
705 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
706 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
707 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
708 // Irreconcilable differences.
709 NumDifferences = 2;
710 break;
711 } else {
712 if (NumDifferences++) break;
713 DiffOperand = i;
714 }
715 }
716
Rafael Espindola7de80e02013-06-06 17:03:05 +0000717 if (NumDifferences == 0) // SAME GEP?
718 return ReplaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszak3facc432013-06-06 20:18:46 +0000719 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner02446fc2010-01-04 07:37:31 +0000720
Stuart Hastings67f071e2011-05-14 05:55:10 +0000721 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000722 Value *LHSV = GEPLHS->getOperand(DiffOperand);
723 Value *RHSV = GEPRHS->getOperand(DiffOperand);
724 // Make sure we do a signed comparison here.
725 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
726 }
727 }
728
729 // Only lower this if the icmp is the only user of the GEP or if we expect
730 // the result to fold to a constant!
731 if (TD &&
Stuart Hastings67f071e2011-05-14 05:55:10 +0000732 GEPsInBounds &&
Chris Lattner02446fc2010-01-04 07:37:31 +0000733 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
734 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
735 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
736 Value *L = EmitGEPOffset(GEPLHS);
737 Value *R = EmitGEPOffset(GEPRHS);
738 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
739 }
740 }
741 return 0;
742}
743
744/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
Benjamin Kramer19a6f112013-09-20 22:12:42 +0000745Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
Chris Lattner02446fc2010-01-04 07:37:31 +0000746 Value *X, ConstantInt *CI,
Benjamin Kramer19a6f112013-09-20 22:12:42 +0000747 ICmpInst::Predicate Pred) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000748 // If we have X+0, exit early (simplifying logic below) and let it get folded
749 // elsewhere. icmp X+0, X -> icmp X, X
750 if (CI->isZero()) {
751 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
752 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
753 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000754
Chris Lattner02446fc2010-01-04 07:37:31 +0000755 // (X+4) == X -> false.
756 if (Pred == ICmpInst::ICMP_EQ)
Jakub Staszak3facc432013-06-06 20:18:46 +0000757 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +0000758
759 // (X+4) != X -> true.
760 if (Pred == ICmpInst::ICMP_NE)
Jakub Staszak3facc432013-06-06 20:18:46 +0000761 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +0000762
Chris Lattner02446fc2010-01-04 07:37:31 +0000763 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000764 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner02446fc2010-01-04 07:37:31 +0000765 // operators.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000766
Chris Lattner9aa1e242010-01-08 17:48:19 +0000767 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner02446fc2010-01-04 07:37:31 +0000768 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
769 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
770 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000771 Value *R =
Chris Lattner9aa1e242010-01-08 17:48:19 +0000772 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner02446fc2010-01-04 07:37:31 +0000773 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
774 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000775
Chris Lattner02446fc2010-01-04 07:37:31 +0000776 // (X+1) >u X --> X <u (0-1) --> X != 255
777 // (X+2) >u X --> X <u (0-2) --> X <u 254
778 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandsa7724332011-02-17 07:46:37 +0000779 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000780 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000781
Chris Lattner02446fc2010-01-04 07:37:31 +0000782 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
783 ConstantInt *SMax = ConstantInt::get(X->getContext(),
784 APInt::getSignedMaxValue(BitWidth));
785
786 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
787 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
788 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
789 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
790 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
791 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandsa7724332011-02-17 07:46:37 +0000792 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000793 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000794
Chris Lattner02446fc2010-01-04 07:37:31 +0000795 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
796 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
797 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
798 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
799 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
800 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000801
Chris Lattner02446fc2010-01-04 07:37:31 +0000802 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszak3facc432013-06-06 20:18:46 +0000803 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner02446fc2010-01-04 07:37:31 +0000804 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
805}
806
807/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
808/// and CmpRHS are both known to be integer constants.
809Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
810 ConstantInt *DivRHS) {
811 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
812 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000813
814 // FIXME: If the operand types don't match the type of the divide
Chris Lattner02446fc2010-01-04 07:37:31 +0000815 // then don't attempt this transform. The code below doesn't have the
816 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000817 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner02446fc2010-01-04 07:37:31 +0000818 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000819 // (x /u C1) <u C2. Simply casting the operands and result won't
820 // work. :( The if statement below tests that condition and bails
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000821 // if it finds it.
Chris Lattner02446fc2010-01-04 07:37:31 +0000822 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
823 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
824 return 0;
825 if (DivRHS->isZero())
826 return 0; // The ProdOV computation fails on divide by zero.
827 if (DivIsSigned && DivRHS->isAllOnesValue())
828 return 0; // The overflow computation also screws up here
Chris Lattnerbb75d332011-02-13 08:07:21 +0000829 if (DivRHS->isOne()) {
830 // This eliminates some funny cases with INT_MIN.
831 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
832 return &ICI;
833 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000834
835 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000836 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
837 // C2 (CI). By solving for X we can turn this into a range check
838 // instead of computing a divide.
Chris Lattner02446fc2010-01-04 07:37:31 +0000839 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
840
841 // Determine if the product overflows by seeing if the product is
842 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000843 // as in the LHS instruction that we're folding.
Chris Lattner02446fc2010-01-04 07:37:31 +0000844 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
845 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
846
847 // Get the ICmp opcode
848 ICmpInst::Predicate Pred = ICI.getPredicate();
849
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000850 /// If the division is known to be exact, then there is no remainder from the
851 /// divide, so the covered range size is unit, otherwise it is the divisor.
852 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000853
Chris Lattner02446fc2010-01-04 07:37:31 +0000854 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000855 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner02446fc2010-01-04 07:37:31 +0000856 // Compute this interval based on the constants involved and the signedness of
857 // the compare/divide. This computes a half-open interval, keeping track of
858 // whether either value in the interval overflows. After analysis each
859 // overflow variable is set to 0 if it's corresponding bound variable is valid
860 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
861 int LoOverflow = 0, HiOverflow = 0;
862 Constant *LoBound = 0, *HiBound = 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000863
Chris Lattner02446fc2010-01-04 07:37:31 +0000864 if (!DivIsSigned) { // udiv
865 // e.g. X/5 op 3 --> [15, 20)
866 LoBound = Prod;
867 HiOverflow = LoOverflow = ProdOV;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000868 if (!HiOverflow) {
869 // If this is not an exact divide, then many values in the range collapse
870 // to the same result value.
871 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
872 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000873
Chris Lattner02446fc2010-01-04 07:37:31 +0000874 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
875 if (CmpRHSV == 0) { // (X / pos) op 0
876 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000877 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
878 HiBound = RangeSize;
Chris Lattner02446fc2010-01-04 07:37:31 +0000879 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
880 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
881 HiOverflow = LoOverflow = ProdOV;
882 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000883 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000884 } else { // (X / pos) op neg
885 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
886 HiBound = AddOne(Prod);
887 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
888 if (!LoOverflow) {
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000889 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000890 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000891 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000892 }
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000893 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000894 if (DivI->isExact())
895 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000896 if (CmpRHSV == 0) { // (X / neg) op 0
897 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000898 LoBound = AddOne(RangeSize);
899 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000900 if (HiBound == DivRHS) { // -INTMIN = INTMIN
901 HiOverflow = 1; // [INTMIN+1, overflow)
902 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
903 }
904 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
905 // e.g. X/-5 op 3 --> [-19, -14)
906 HiBound = AddOne(Prod);
907 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
908 if (!LoOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000909 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner02446fc2010-01-04 07:37:31 +0000910 } else { // (X / neg) op neg
911 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
912 LoOverflow = HiOverflow = ProdOV;
913 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000914 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000915 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000916
Chris Lattner02446fc2010-01-04 07:37:31 +0000917 // Dividing by a negative swaps the condition. LT <-> GT
918 Pred = ICmpInst::getSwappedPredicate(Pred);
919 }
920
921 Value *X = DivI->getOperand(0);
922 switch (Pred) {
923 default: llvm_unreachable("Unhandled icmp opcode!");
924 case ICmpInst::ICMP_EQ:
925 if (LoOverflow && HiOverflow)
Jakub Staszak3facc432013-06-06 20:18:46 +0000926 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000927 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000928 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
929 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000930 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000931 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
932 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000933 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
934 DivIsSigned, true));
Chris Lattner02446fc2010-01-04 07:37:31 +0000935 case ICmpInst::ICMP_NE:
936 if (LoOverflow && HiOverflow)
Jakub Staszak3facc432013-06-06 20:18:46 +0000937 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000938 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000939 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
940 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000941 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000942 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
943 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000944 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
945 DivIsSigned, false));
Chris Lattner02446fc2010-01-04 07:37:31 +0000946 case ICmpInst::ICMP_ULT:
947 case ICmpInst::ICMP_SLT:
948 if (LoOverflow == +1) // Low bound is greater than input range.
Jakub Staszak3facc432013-06-06 20:18:46 +0000949 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +0000950 if (LoOverflow == -1) // Low bound is less than input range.
Jakub Staszak3facc432013-06-06 20:18:46 +0000951 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +0000952 return new ICmpInst(Pred, X, LoBound);
953 case ICmpInst::ICMP_UGT:
954 case ICmpInst::ICMP_SGT:
955 if (HiOverflow == +1) // High bound greater than input range.
Jakub Staszak3facc432013-06-06 20:18:46 +0000956 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000957 if (HiOverflow == -1) // High bound less than input range.
Jakub Staszak3facc432013-06-06 20:18:46 +0000958 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +0000959 if (Pred == ICmpInst::ICMP_UGT)
960 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000961 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner02446fc2010-01-04 07:37:31 +0000962 }
963}
964
Chris Lattner74542aa2011-02-13 07:43:07 +0000965/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
966Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
967 ConstantInt *ShAmt) {
Chris Lattner74542aa2011-02-13 07:43:07 +0000968 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000969
Chris Lattner74542aa2011-02-13 07:43:07 +0000970 // Check that the shift amount is in range. If not, don't perform
971 // undefined shifts. When the shift is visited it will be
972 // simplified.
973 uint32_t TypeBits = CmpRHSV.getBitWidth();
974 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnerbb75d332011-02-13 08:07:21 +0000975 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Chris Lattner74542aa2011-02-13 07:43:07 +0000976 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000977
Chris Lattnerbb75d332011-02-13 08:07:21 +0000978 if (!ICI.isEquality()) {
979 // If we have an unsigned comparison and an ashr, we can't simplify this.
980 // Similarly for signed comparisons with lshr.
981 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
982 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000983
Eli Friedmana831a9b2011-05-25 23:26:20 +0000984 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
985 // by a power of 2. Since we already have logic to simplify these,
986 // transform to div and then simplify the resultant comparison.
Chris Lattnerbb75d332011-02-13 08:07:21 +0000987 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedmana831a9b2011-05-25 23:26:20 +0000988 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Chris Lattnerbb75d332011-02-13 08:07:21 +0000989 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000990
Chris Lattnerbb75d332011-02-13 08:07:21 +0000991 // Revisit the shift (to delete it).
992 Worklist.Add(Shr);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000993
Chris Lattnerbb75d332011-02-13 08:07:21 +0000994 Constant *DivCst =
995 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000996
Chris Lattnerbb75d332011-02-13 08:07:21 +0000997 Value *Tmp =
998 Shr->getOpcode() == Instruction::AShr ?
999 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
1000 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001001
Chris Lattnerbb75d332011-02-13 08:07:21 +00001002 ICI.setOperand(0, Tmp);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001003
Chris Lattnerbb75d332011-02-13 08:07:21 +00001004 // If the builder folded the binop, just return it.
1005 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
1006 if (TheDiv == 0)
1007 return &ICI;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001008
Chris Lattnerbb75d332011-02-13 08:07:21 +00001009 // Otherwise, fold this div/compare.
1010 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1011 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001012
Chris Lattnerbb75d332011-02-13 08:07:21 +00001013 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1014 assert(Res && "This div/cst should have folded!");
1015 return Res;
1016 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001017
1018
Chris Lattner74542aa2011-02-13 07:43:07 +00001019 // If we are comparing against bits always shifted out, the
1020 // comparison cannot succeed.
1021 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszak3facc432013-06-06 20:18:46 +00001022 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattner74542aa2011-02-13 07:43:07 +00001023 if (Shr->getOpcode() == Instruction::LShr)
1024 Comp = Comp.lshr(ShAmtVal);
1025 else
1026 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001027
Chris Lattner74542aa2011-02-13 07:43:07 +00001028 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1029 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszak3facc432013-06-06 20:18:46 +00001030 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattner74542aa2011-02-13 07:43:07 +00001031 return ReplaceInstUsesWith(ICI, Cst);
1032 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001033
Chris Lattner74542aa2011-02-13 07:43:07 +00001034 // Otherwise, check to see if the bits shifted out are known to be zero.
1035 // If so, we can compare against the unshifted value:
1036 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattnere5116f82011-02-13 18:30:09 +00001037 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattner74542aa2011-02-13 07:43:07 +00001038 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001039
Chris Lattner74542aa2011-02-13 07:43:07 +00001040 if (Shr->hasOneUse()) {
1041 // Otherwise strength reduce the shift into an and.
1042 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszak3facc432013-06-06 20:18:46 +00001043 Constant *Mask = Builder->getInt(Val);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001044
Chris Lattner74542aa2011-02-13 07:43:07 +00001045 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1046 Mask, Shr->getName()+".mask");
1047 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1048 }
1049 return 0;
1050}
1051
Chris Lattner02446fc2010-01-04 07:37:31 +00001052
1053/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1054///
1055Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1056 Instruction *LHSI,
1057 ConstantInt *RHS) {
1058 const APInt &RHSV = RHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001059
Chris Lattner02446fc2010-01-04 07:37:31 +00001060 switch (LHSI->getOpcode()) {
1061 case Instruction::Trunc:
1062 if (ICI.isEquality() && LHSI->hasOneUse()) {
1063 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1064 // of the high bits truncated out of x are known.
1065 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1066 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner02446fc2010-01-04 07:37:31 +00001067 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001068 ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001069
Chris Lattner02446fc2010-01-04 07:37:31 +00001070 // If all the high bits are known, we can do this xform.
1071 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1072 // Pull in the high bits from known-ones set.
Jay Foad40f8f622010-12-07 08:25:19 +00001073 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedman5b6dfee2012-05-11 01:32:59 +00001074 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner02446fc2010-01-04 07:37:31 +00001075 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001076 Builder->getInt(NewRHS));
Chris Lattner02446fc2010-01-04 07:37:31 +00001077 }
1078 }
1079 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001080
Chris Lattner02446fc2010-01-04 07:37:31 +00001081 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
1082 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1083 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1084 // fold the xor.
1085 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1086 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1087 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001088
Chris Lattner02446fc2010-01-04 07:37:31 +00001089 // If the sign bit of the XorCST is not set, there is no change to
1090 // the operation, just stop using the Xor.
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001091 if (!XorCST->isNegative()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001092 ICI.setOperand(0, CompareVal);
1093 Worklist.Add(LHSI);
1094 return &ICI;
1095 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001096
Chris Lattner02446fc2010-01-04 07:37:31 +00001097 // Was the old condition true if the operand is positive?
1098 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001099
Chris Lattner02446fc2010-01-04 07:37:31 +00001100 // If so, the new one isn't.
1101 isTrueIfPositive ^= true;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001102
Chris Lattner02446fc2010-01-04 07:37:31 +00001103 if (isTrueIfPositive)
1104 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1105 SubOne(RHS));
1106 else
1107 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1108 AddOne(RHS));
1109 }
1110
1111 if (LHSI->hasOneUse()) {
1112 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1113 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
1114 const APInt &SignBit = XorCST->getValue();
1115 ICmpInst::Predicate Pred = ICI.isSigned()
1116 ? ICI.getUnsignedPredicate()
1117 : ICI.getSignedPredicate();
1118 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001119 Builder->getInt(RHSV ^ SignBit));
Chris Lattner02446fc2010-01-04 07:37:31 +00001120 }
1121
1122 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001123 if (!ICI.isEquality() && XorCST->isMaxValue(true)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001124 const APInt &NotSignBit = XorCST->getValue();
1125 ICmpInst::Predicate Pred = ICI.isSigned()
1126 ? ICI.getUnsignedPredicate()
1127 : ICI.getSignedPredicate();
1128 Pred = ICI.getSwappedPredicate(Pred);
1129 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001130 Builder->getInt(RHSV ^ NotSignBit));
Chris Lattner02446fc2010-01-04 07:37:31 +00001131 }
1132 }
David Majnemerfecf0d72013-07-09 09:20:58 +00001133
1134 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1135 // iff -C is a power of 2
1136 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
1137 XorCST->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1138 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCST);
1139
1140 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1141 // iff -C is a power of 2
1142 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
1143 XorCST->getValue() == -RHSV && RHSV.isPowerOf2())
1144 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCST);
Chris Lattner02446fc2010-01-04 07:37:31 +00001145 }
1146 break;
1147 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
1148 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1149 LHSI->getOperand(0)->hasOneUse()) {
1150 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001151
Chris Lattner02446fc2010-01-04 07:37:31 +00001152 // If the LHS is an AND of a truncating cast, we can widen the
1153 // and/compare to be the input width without changing the value
1154 // produced, eliminating a cast.
1155 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1156 // We can do this transformation if either the AND constant does not
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001157 // have its sign bit set or if it is an equality comparison.
Chris Lattner02446fc2010-01-04 07:37:31 +00001158 // Extending a relational comparison when we're checking the sign
1159 // bit would not work.
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001160 if (ICI.isEquality() ||
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001161 (!AndCST->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001162 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001163 Builder->CreateAnd(Cast->getOperand(0),
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001164 ConstantExpr::getZExt(AndCST, Cast->getSrcTy()));
1165 NewAnd->takeName(LHSI);
Chris Lattner02446fc2010-01-04 07:37:31 +00001166 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001167 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001168 }
1169 }
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001170
1171 // If the LHS is an AND of a zext, and we have an equality compare, we can
1172 // shrink the and/compare to the smaller type, eliminating the cast.
1173 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001174 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001175 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1176 // should fold the icmp to true/false in that case.
1177 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1178 Value *NewAnd =
1179 Builder->CreateAnd(Cast->getOperand(0),
1180 ConstantExpr::getTrunc(AndCST, Ty));
1181 NewAnd->takeName(LHSI);
1182 return new ICmpInst(ICI.getPredicate(), NewAnd,
1183 ConstantExpr::getTrunc(RHS, Ty));
1184 }
1185 }
1186
Chris Lattner02446fc2010-01-04 07:37:31 +00001187 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1188 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1189 // happens a LOT in code produced by the C front-end, for bitfield
1190 // access.
1191 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1192 if (Shift && !Shift->isShift())
1193 Shift = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001194
Chris Lattner02446fc2010-01-04 07:37:31 +00001195 ConstantInt *ShAmt;
1196 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001197 Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
1198 Type *AndTy = AndCST->getType(); // Type of the and.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001199
Chris Lattner02446fc2010-01-04 07:37:31 +00001200 // We can fold this as long as we can't shift unknown bits
1201 // into the mask. This can only happen with signed shift
1202 // rights, as they sign-extend.
1203 if (ShAmt) {
1204 bool CanFold = Shift->isLogicalShift();
1205 if (!CanFold) {
1206 // To test for the bad case of the signed shr, see if any
1207 // of the bits shifted in could be tested after the mask.
1208 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1209 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001210
Chris Lattner02446fc2010-01-04 07:37:31 +00001211 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001212 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
Chris Lattner02446fc2010-01-04 07:37:31 +00001213 AndCST->getValue()) == 0)
1214 CanFold = true;
1215 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001216
Chris Lattner02446fc2010-01-04 07:37:31 +00001217 if (CanFold) {
1218 Constant *NewCst;
1219 if (Shift->getOpcode() == Instruction::Shl)
1220 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1221 else
1222 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001223
Chris Lattner02446fc2010-01-04 07:37:31 +00001224 // Check to see if we are shifting out any of the bits being
1225 // compared.
1226 if (ConstantExpr::get(Shift->getOpcode(),
1227 NewCst, ShAmt) != RHS) {
1228 // If we shifted bits out, the fold is not going to work out.
1229 // As a special case, check to see if this means that the
1230 // result is always true or false now.
1231 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Jakub Staszak3facc432013-06-06 20:18:46 +00001232 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00001233 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Jakub Staszak3facc432013-06-06 20:18:46 +00001234 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +00001235 } else {
1236 ICI.setOperand(1, NewCst);
1237 Constant *NewAndCST;
1238 if (Shift->getOpcode() == Instruction::Shl)
1239 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1240 else
1241 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1242 LHSI->setOperand(1, NewAndCST);
1243 LHSI->setOperand(0, Shift->getOperand(0));
1244 Worklist.Add(Shift); // Shift is dead.
1245 return &ICI;
1246 }
1247 }
1248 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001249
Chris Lattner02446fc2010-01-04 07:37:31 +00001250 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1251 // preferable because it allows the C<<Y expression to be hoisted out
1252 // of a loop if Y is invariant and X is not.
1253 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1254 ICI.isEquality() && !Shift->isArithmeticShift() &&
1255 !isa<Constant>(Shift->getOperand(0))) {
1256 // Compute C << Y.
1257 Value *NS;
1258 if (Shift->getOpcode() == Instruction::LShr) {
Benjamin Kramera9390a42011-09-27 20:39:19 +00001259 NS = Builder->CreateShl(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001260 } else {
1261 // Insert a logical shift.
Benjamin Kramera9390a42011-09-27 20:39:19 +00001262 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001263 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001264
Chris Lattner02446fc2010-01-04 07:37:31 +00001265 // Compute X & (C << Y).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001266 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001267 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001268
Chris Lattner02446fc2010-01-04 07:37:31 +00001269 ICI.setOperand(0, NewAnd);
1270 return &ICI;
1271 }
Paul Redmond6da2e222012-12-19 19:47:13 +00001272
1273 // Replace ((X & AndCST) > RHSV) with ((X & AndCST) != 0), if any
1274 // bit set in (X & AndCST) will produce a result greater than RHSV.
1275 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
1276 unsigned NTZ = AndCST->getValue().countTrailingZeros();
1277 if ((NTZ < AndCST->getBitWidth()) &&
1278 APInt::getOneBitSet(AndCST->getBitWidth(), NTZ).ugt(RHSV))
1279 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1280 Constant::getNullValue(RHS->getType()));
1281 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001282 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001283
Chris Lattner02446fc2010-01-04 07:37:31 +00001284 // Try to optimize things like "A[i]&42 == 0" to index computations.
1285 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1286 if (GetElementPtrInst *GEP =
1287 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1288 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1289 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1290 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1291 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1292 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1293 return Res;
1294 }
1295 }
David Majnemer36b6f742013-07-09 08:09:32 +00001296
1297 // X & -C == -C -> X > u ~C
1298 // X & -C != -C -> X <= u ~C
1299 // iff C is a power of 2
1300 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1301 return new ICmpInst(
1302 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1303 : ICmpInst::ICMP_ULE,
1304 LHSI->getOperand(0), SubOne(RHS));
Chris Lattner02446fc2010-01-04 07:37:31 +00001305 break;
1306
1307 case Instruction::Or: {
1308 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1309 break;
1310 Value *P, *Q;
1311 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1312 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1313 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner02446fc2010-01-04 07:37:31 +00001314 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1315 Constant::getNullValue(P->getType()));
1316 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1317 Constant::getNullValue(Q->getType()));
1318 Instruction *Op;
1319 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1320 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1321 else
1322 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1323 return Op;
1324 }
1325 break;
1326 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001327
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001328 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1329 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1330 if (!Val) break;
1331
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +00001332 // If this is a signed comparison to 0 and the mul is sign preserving,
1333 // use the mul LHS operand instead.
1334 ICmpInst::Predicate pred = ICI.getPredicate();
1335 if (isSignTest(pred, RHS) && !Val->isZero() &&
1336 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1337 return new ICmpInst(Val->isNegative() ?
1338 ICmpInst::getSwappedPredicate(pred) : pred,
1339 LHSI->getOperand(0),
1340 Constant::getNullValue(RHS->getType()));
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001341
1342 break;
1343 }
1344
Chris Lattner02446fc2010-01-04 07:37:31 +00001345 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
Chris Lattner02446fc2010-01-04 07:37:31 +00001346 uint32_t TypeBits = RHSV.getBitWidth();
David Majnemerb41f4bb2013-06-28 23:42:03 +00001347 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1348 if (!ShAmt) {
1349 Value *X;
1350 // (1 << X) pred P2 -> X pred Log2(P2)
1351 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1352 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1353 ICmpInst::Predicate Pred = ICI.getPredicate();
1354 if (ICI.isUnsigned()) {
1355 if (!RHSVIsPowerOf2) {
1356 // (1 << X) < 30 -> X <= 4
1357 // (1 << X) <= 30 -> X <= 4
1358 // (1 << X) >= 30 -> X > 4
1359 // (1 << X) > 30 -> X > 4
1360 if (Pred == ICmpInst::ICMP_ULT)
1361 Pred = ICmpInst::ICMP_ULE;
1362 else if (Pred == ICmpInst::ICMP_UGE)
1363 Pred = ICmpInst::ICMP_UGT;
1364 }
1365 unsigned RHSLog2 = RHSV.logBase2();
1366
1367 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
1368 // (1 << X) > 2147483648 -> X > 31 -> false
1369 // (1 << X) <= 2147483648 -> X <= 31 -> true
1370 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1371 if (RHSLog2 == TypeBits-1) {
1372 if (Pred == ICmpInst::ICMP_UGE)
1373 Pred = ICmpInst::ICMP_EQ;
1374 else if (Pred == ICmpInst::ICMP_UGT)
1375 return ReplaceInstUsesWith(ICI, Builder->getFalse());
1376 else if (Pred == ICmpInst::ICMP_ULE)
1377 return ReplaceInstUsesWith(ICI, Builder->getTrue());
1378 else if (Pred == ICmpInst::ICMP_ULT)
1379 Pred = ICmpInst::ICMP_NE;
1380 }
1381
1382 return new ICmpInst(Pred, X,
1383 ConstantInt::get(RHS->getType(), RHSLog2));
1384 } else if (ICI.isSigned()) {
1385 if (RHSV.isAllOnesValue()) {
1386 // (1 << X) <= -1 -> X == 31
1387 if (Pred == ICmpInst::ICMP_SLE)
1388 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1389 ConstantInt::get(RHS->getType(), TypeBits-1));
1390
1391 // (1 << X) > -1 -> X != 31
1392 if (Pred == ICmpInst::ICMP_SGT)
1393 return new ICmpInst(ICmpInst::ICMP_NE, X,
1394 ConstantInt::get(RHS->getType(), TypeBits-1));
1395 } else if (!RHSV) {
1396 // (1 << X) < 0 -> X == 31
1397 // (1 << X) <= 0 -> X == 31
1398 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1399 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1400 ConstantInt::get(RHS->getType(), TypeBits-1));
1401
1402 // (1 << X) >= 0 -> X != 31
1403 // (1 << X) > 0 -> X != 31
1404 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1405 return new ICmpInst(ICmpInst::ICMP_NE, X,
1406 ConstantInt::get(RHS->getType(), TypeBits-1));
1407 }
1408 } else if (ICI.isEquality()) {
1409 if (RHSVIsPowerOf2)
1410 return new ICmpInst(
1411 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
1412
1413 return ReplaceInstUsesWith(
1414 ICI, Pred == ICmpInst::ICMP_EQ ? Builder->getFalse()
1415 : Builder->getTrue());
1416 }
1417 }
1418 break;
1419 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001420
Chris Lattner02446fc2010-01-04 07:37:31 +00001421 // Check that the shift amount is in range. If not, don't perform
1422 // undefined shifts. When the shift is visited it will be
1423 // simplified.
1424 if (ShAmt->uge(TypeBits))
1425 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001426
Chris Lattner02446fc2010-01-04 07:37:31 +00001427 if (ICI.isEquality()) {
1428 // If we are comparing against bits always shifted out, the
1429 // comparison cannot succeed.
1430 Constant *Comp =
1431 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1432 ShAmt);
1433 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1434 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszak3facc432013-06-06 20:18:46 +00001435 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattner02446fc2010-01-04 07:37:31 +00001436 return ReplaceInstUsesWith(ICI, Cst);
1437 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001438
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001439 // If the shift is NUW, then it is just shifting out zeros, no need for an
1440 // AND.
1441 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1442 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1443 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001444
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001445 // If the shift is NSW and we compare to 0, then it is just shifting out
1446 // sign bits, no need for an AND either.
1447 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1448 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1449 ConstantExpr::getLShr(RHS, ShAmt));
1450
Chris Lattner02446fc2010-01-04 07:37:31 +00001451 if (LHSI->hasOneUse()) {
1452 // Otherwise strength reduce the shift into an and.
1453 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Jakub Staszak3facc432013-06-06 20:18:46 +00001454 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
1455 TypeBits - ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001456
Chris Lattner02446fc2010-01-04 07:37:31 +00001457 Value *And =
1458 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1459 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001460 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner02446fc2010-01-04 07:37:31 +00001461 }
1462 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001463
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001464 // If this is a signed comparison to 0 and the shift is sign preserving,
1465 // use the shift LHS operand instead.
1466 ICmpInst::Predicate pred = ICI.getPredicate();
1467 if (isSignTest(pred, RHS) &&
1468 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1469 return new ICmpInst(pred,
1470 LHSI->getOperand(0),
1471 Constant::getNullValue(RHS->getType()));
1472
Chris Lattner02446fc2010-01-04 07:37:31 +00001473 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1474 bool TrueIfSigned = false;
1475 if (LHSI->hasOneUse() &&
1476 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1477 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattnerbb75d332011-02-13 08:07:21 +00001478 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001479 APInt::getOneBitSet(TypeBits,
Chris Lattnerbb75d332011-02-13 08:07:21 +00001480 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001481 Value *And =
1482 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1483 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1484 And, Constant::getNullValue(And->getType()));
1485 }
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001486
1487 // Transform (icmp pred iM (shl iM %v, N), CI)
Arnaud A. de Grandmaisonbdd2d982013-03-13 14:40:37 +00001488 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1489 // 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 +00001490 // This enables to get rid of the shift in favor of a trunc which can be
1491 // free on the target. It has the additional benefit of comparing to a
1492 // smaller constant, which will be target friendly.
1493 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
Arnaud A. de Grandmaisonbdd2d982013-03-13 14:40:37 +00001494 if (LHSI->hasOneUse() &&
1495 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001496 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1497 Constant *NCI = ConstantExpr::getTrunc(
1498 ConstantExpr::getAShr(RHS,
1499 ConstantInt::get(RHS->getType(), Amt)),
1500 NTy);
1501 return new ICmpInst(ICI.getPredicate(),
1502 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaisonad079b22013-02-15 15:18:17 +00001503 NCI);
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001504 }
1505
Chris Lattner02446fc2010-01-04 07:37:31 +00001506 break;
1507 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001508
Chris Lattner02446fc2010-01-04 07:37:31 +00001509 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001510 case Instruction::AShr: {
1511 // Handle equality comparisons of shift-by-constant.
1512 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1513 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1514 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattner74542aa2011-02-13 07:43:07 +00001515 return Res;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001516 }
1517
1518 // Handle exact shr's.
1519 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1520 if (RHSV.isMinValue())
1521 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1522 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001523 break;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001524 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001525
Chris Lattner02446fc2010-01-04 07:37:31 +00001526 case Instruction::SDiv:
1527 case Instruction::UDiv:
1528 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001529 // Fold this div into the comparison, producing a range check.
1530 // Determine, based on the divide type, what the range is being
1531 // checked. If there is an overflow on the low or high side, remember
Chris Lattner02446fc2010-01-04 07:37:31 +00001532 // it, otherwise compute the range [low, hi) bounding the new value.
1533 // See: InsertRangeTest above for the kinds of replacements possible.
1534 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1535 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1536 DivRHS))
1537 return R;
1538 break;
1539
David Majnemer377a5c12013-07-09 07:50:59 +00001540 case Instruction::Sub: {
1541 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
1542 if (!LHSC) break;
1543 const APInt &LHSV = LHSC->getValue();
1544
1545 // C1-X <u C2 -> (X|(C2-1)) == C1
1546 // iff C1 & (C2-1) == C2-1
1547 // C2 is a power of 2
1548 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1549 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
1550 return new ICmpInst(ICmpInst::ICMP_EQ,
1551 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
1552 LHSC);
1553
David Majnemerfcb7b972013-07-09 09:24:35 +00001554 // C1-X >u C2 -> (X|C2) != C1
David Majnemer377a5c12013-07-09 07:50:59 +00001555 // iff C1 & C2 == C2
1556 // C2+1 is a power of 2
1557 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1558 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
1559 return new ICmpInst(ICmpInst::ICMP_NE,
1560 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
1561 break;
1562 }
1563
Chris Lattner02446fc2010-01-04 07:37:31 +00001564 case Instruction::Add:
1565 // Fold: icmp pred (add X, C1), C2
1566 if (!ICI.isEquality()) {
1567 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1568 if (!LHSC) break;
1569 const APInt &LHSV = LHSC->getValue();
1570
1571 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1572 .subtract(LHSV);
1573
1574 if (ICI.isSigned()) {
1575 if (CR.getLower().isSignBit()) {
1576 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001577 Builder->getInt(CR.getUpper()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001578 } else if (CR.getUpper().isSignBit()) {
1579 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001580 Builder->getInt(CR.getLower()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001581 }
1582 } else {
1583 if (CR.getLower().isMinValue()) {
1584 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001585 Builder->getInt(CR.getUpper()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001586 } else if (CR.getUpper().isMinValue()) {
1587 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001588 Builder->getInt(CR.getLower()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001589 }
1590 }
David Majnemer53fc3992013-07-08 11:53:08 +00001591
David Majnemer11c29ba2013-07-09 07:58:32 +00001592 // X-C1 <u C2 -> (X & -C2) == C1
1593 // iff C1 & (C2-1) == 0
1594 // C2 is a power of 2
David Majnemer53fc3992013-07-08 11:53:08 +00001595 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
David Majnemer11c29ba2013-07-09 07:58:32 +00001596 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
David Majnemer53fc3992013-07-08 11:53:08 +00001597 return new ICmpInst(ICmpInst::ICMP_EQ,
1598 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
1599 ConstantExpr::getNeg(LHSC));
David Majnemer11c29ba2013-07-09 07:58:32 +00001600
David Majnemerfcb7b972013-07-09 09:24:35 +00001601 // X-C1 >u C2 -> (X & ~C2) != C1
David Majnemer11c29ba2013-07-09 07:58:32 +00001602 // iff C1 & C2 == 0
1603 // C2+1 is a power of 2
1604 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1605 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
1606 return new ICmpInst(ICmpInst::ICMP_NE,
1607 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
1608 ConstantExpr::getNeg(LHSC));
Chris Lattner02446fc2010-01-04 07:37:31 +00001609 }
1610 break;
1611 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001612
Chris Lattner02446fc2010-01-04 07:37:31 +00001613 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1614 if (ICI.isEquality()) {
1615 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001616
1617 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner02446fc2010-01-04 07:37:31 +00001618 // the second operand is a constant, simplify a bit.
1619 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1620 switch (BO->getOpcode()) {
1621 case Instruction::SRem:
1622 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1623 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1624 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohmane0567812010-04-08 23:03:40 +00001625 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001626 Value *NewRem =
1627 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1628 BO->getName());
1629 return new ICmpInst(ICI.getPredicate(), NewRem,
1630 Constant::getNullValue(BO->getType()));
1631 }
1632 }
1633 break;
1634 case Instruction::Add:
1635 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1636 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1637 if (BO->hasOneUse())
1638 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1639 ConstantExpr::getSub(RHS, BOp1C));
1640 } else if (RHSV == 0) {
1641 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1642 // efficiently invertible, or if the add has just this one use.
1643 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001644
Chris Lattner02446fc2010-01-04 07:37:31 +00001645 if (Value *NegVal = dyn_castNegVal(BOp1))
1646 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner5036ce42011-04-26 20:02:45 +00001647 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner02446fc2010-01-04 07:37:31 +00001648 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner5036ce42011-04-26 20:02:45 +00001649 if (BO->hasOneUse()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001650 Value *Neg = Builder->CreateNeg(BOp1);
1651 Neg->takeName(BO);
1652 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1653 }
1654 }
1655 break;
1656 case Instruction::Xor:
1657 // For the xor case, we can xor two constants together, eliminating
1658 // the explicit xor.
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001659 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1660 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner02446fc2010-01-04 07:37:31 +00001661 ConstantExpr::getXor(RHS, BOC));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001662 } else if (RHSV == 0) {
1663 // Replace ((xor A, B) != 0) with (A != B)
Chris Lattner02446fc2010-01-04 07:37:31 +00001664 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1665 BO->getOperand(1));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001666 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001667 break;
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001668 case Instruction::Sub:
1669 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1670 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1671 if (BO->hasOneUse())
1672 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1673 ConstantExpr::getSub(BOp0C, RHS));
1674 } else if (RHSV == 0) {
1675 // Replace ((sub A, B) != 0) with (A != B)
1676 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1677 BO->getOperand(1));
1678 }
1679 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001680 case Instruction::Or:
1681 // If bits are being or'd in that are not present in the constant we
1682 // are comparing against, then the comparison could never succeed!
Eli Friedman618898e2010-07-29 18:03:33 +00001683 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001684 Constant *NotCI = ConstantExpr::getNot(RHS);
1685 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Jakub Staszak3facc432013-06-06 20:18:46 +00001686 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Chris Lattner02446fc2010-01-04 07:37:31 +00001687 }
1688 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001689
Chris Lattner02446fc2010-01-04 07:37:31 +00001690 case Instruction::And:
1691 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1692 // If bits are being compared against that are and'd out, then the
1693 // comparison can never succeed!
1694 if ((RHSV & ~BOC->getValue()) != 0)
Jakub Staszak3facc432013-06-06 20:18:46 +00001695 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001696
Chris Lattner02446fc2010-01-04 07:37:31 +00001697 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1698 if (RHS == BOC && RHSV.isPowerOf2())
1699 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1700 ICmpInst::ICMP_NE, LHSI,
1701 Constant::getNullValue(RHS->getType()));
Benjamin Kramerfc87cdc2011-07-04 20:16:36 +00001702
1703 // Don't perform the following transforms if the AND has multiple uses
1704 if (!BO->hasOneUse())
1705 break;
1706
Chris Lattner02446fc2010-01-04 07:37:31 +00001707 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1708 if (BOC->getValue().isSignBit()) {
1709 Value *X = BO->getOperand(0);
1710 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001711 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001712 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1713 return new ICmpInst(pred, X, Zero);
1714 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001715
Chris Lattner02446fc2010-01-04 07:37:31 +00001716 // ((X & ~7) == 0) --> X < 8
1717 if (RHSV == 0 && isHighOnes(BOC)) {
1718 Value *X = BO->getOperand(0);
1719 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001720 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001721 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1722 return new ICmpInst(pred, X, NegX);
1723 }
1724 }
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001725 break;
1726 case Instruction::Mul:
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +00001727 if (RHSV == 0 && BO->hasNoSignedWrap()) {
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001728 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1729 // The trivial case (mul X, 0) is handled by InstSimplify
1730 // General case : (mul X, C) != 0 iff X != 0
1731 // (mul X, C) == 0 iff X == 0
1732 if (!BOC->isZero())
1733 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1734 Constant::getNullValue(RHS->getType()));
1735 }
1736 }
1737 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001738 default: break;
1739 }
1740 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1741 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner03357402010-01-05 18:09:56 +00001742 switch (II->getIntrinsicID()) {
1743 case Intrinsic::bswap:
Chris Lattner02446fc2010-01-04 07:37:31 +00001744 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001745 ICI.setOperand(0, II->getArgOperand(0));
Jakub Staszak3facc432013-06-06 20:18:46 +00001746 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001747 return &ICI;
Chris Lattner03357402010-01-05 18:09:56 +00001748 case Intrinsic::ctlz:
1749 case Intrinsic::cttz:
1750 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1751 if (RHSV == RHS->getType()->getBitWidth()) {
1752 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001753 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001754 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1755 return &ICI;
1756 }
1757 break;
1758 case Intrinsic::ctpop:
1759 // popcount(A) == 0 -> A == 0 and likewise for !=
1760 if (RHS->isZero()) {
1761 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001762 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001763 ICI.setOperand(1, RHS);
1764 return &ICI;
1765 }
1766 break;
1767 default:
Duncan Sands34727662010-07-12 08:16:59 +00001768 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001769 }
1770 }
1771 }
1772 return 0;
1773}
1774
1775/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1776/// We only handle extending casts so far.
1777///
1778Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1779 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1780 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001781 Type *SrcTy = LHSCIOp->getType();
1782 Type *DestTy = LHSCI->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00001783 Value *RHSCIOp;
1784
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001785 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner02446fc2010-01-04 07:37:31 +00001786 // integer type is the same size as the pointer type.
1787 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
Matt Arsenaultf9dd19f2013-09-30 21:06:18 +00001788 TD->getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001789 Value *RHSOp = 0;
1790 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1791 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1792 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1793 RHSOp = RHSC->getOperand(0);
1794 // If the pointer types don't match, insert a bitcast.
1795 if (LHSCIOp->getType() != RHSOp->getType())
1796 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1797 }
1798
1799 if (RHSOp)
1800 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1801 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001802
Chris Lattner02446fc2010-01-04 07:37:31 +00001803 // The code below only handles extension cast instructions, so far.
1804 // Enforce this.
1805 if (LHSCI->getOpcode() != Instruction::ZExt &&
1806 LHSCI->getOpcode() != Instruction::SExt)
1807 return 0;
1808
1809 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1810 bool isSignedCmp = ICI.isSigned();
1811
1812 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1813 // Not an extension from the same type?
1814 RHSCIOp = CI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001815 if (RHSCIOp->getType() != LHSCIOp->getType())
Chris Lattner02446fc2010-01-04 07:37:31 +00001816 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001817
Chris Lattner02446fc2010-01-04 07:37:31 +00001818 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1819 // and the other is a zext), then we can't handle this.
1820 if (CI->getOpcode() != LHSCI->getOpcode())
1821 return 0;
1822
1823 // Deal with equality cases early.
1824 if (ICI.isEquality())
1825 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1826
1827 // A signed comparison of sign extended values simplifies into a
1828 // signed comparison.
1829 if (isSignedCmp && isSignedExt)
1830 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1831
1832 // The other three cases all fold into an unsigned comparison.
1833 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1834 }
1835
1836 // If we aren't dealing with a constant on the RHS, exit early
1837 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1838 if (!CI)
1839 return 0;
1840
1841 // Compute the constant that would happen if we truncated to SrcTy then
1842 // reextended to DestTy.
1843 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1844 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1845 Res1, DestTy);
1846
1847 // If the re-extended constant didn't change...
1848 if (Res2 == CI) {
1849 // Deal with equality cases early.
1850 if (ICI.isEquality())
1851 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1852
1853 // A signed comparison of sign extended values simplifies into a
1854 // signed comparison.
1855 if (isSignedExt && isSignedCmp)
1856 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1857
1858 // The other three cases all fold into an unsigned comparison.
1859 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1860 }
1861
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001862 // The re-extended constant changed so the constant cannot be represented
Chris Lattner02446fc2010-01-04 07:37:31 +00001863 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands9d32f602011-01-20 13:21:55 +00001864 // All the cases that fold to true or false will have already been handled
1865 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner02446fc2010-01-04 07:37:31 +00001866
Duncan Sands9d32f602011-01-20 13:21:55 +00001867 if (isSignedCmp || !isSignedExt)
1868 return 0;
Chris Lattner02446fc2010-01-04 07:37:31 +00001869
1870 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1871 // should have been folded away previously and not enter in here.
Duncan Sands9d32f602011-01-20 13:21:55 +00001872
1873 // We're performing an unsigned comp with a sign extended value.
1874 // This is true if the input is >= 0. [aka >s -1]
1875 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1876 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner02446fc2010-01-04 07:37:31 +00001877
1878 // Finally, return the value computed.
Duncan Sands9d32f602011-01-20 13:21:55 +00001879 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner02446fc2010-01-04 07:37:31 +00001880 return ReplaceInstUsesWith(ICI, Result);
1881
Duncan Sands9d32f602011-01-20 13:21:55 +00001882 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner02446fc2010-01-04 07:37:31 +00001883 return BinaryOperator::CreateNot(Result);
1884}
1885
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001886/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1887/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001888/// If this is of the form:
1889/// sum = a + b
1890/// if (sum+128 >u 255)
1891/// Then replace it with llvm.sadd.with.overflow.i8.
1892///
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001893static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1894 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001895 InstCombiner &IC) {
Chris Lattner368397b2010-12-19 17:59:02 +00001896 // The transformation we're trying to do here is to transform this into an
1897 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1898 // with a narrower add, and discard the add-with-constant that is part of the
1899 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001900
Chris Lattner368397b2010-12-19 17:59:02 +00001901 // In order to eliminate the add-with-constant, the compare can be its only
1902 // use.
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001903 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Chris Lattner368397b2010-12-19 17:59:02 +00001904 if (!AddWithCst->hasOneUse()) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001905
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001906 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1907 if (!CI2->getValue().isPowerOf2()) return 0;
1908 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1909 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001910
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001911 // The width of the new add formed is 1 more than the bias.
1912 ++NewWidth;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001913
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001914 // Check to see that CI1 is an all-ones value with NewWidth bits.
1915 if (CI1->getBitWidth() == NewWidth ||
1916 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1917 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001918
Eli Friedman54b92112011-11-28 23:32:19 +00001919 // This is only really a signed overflow check if the inputs have been
1920 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1921 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1922 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1923 if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1924 IC.ComputeNumSignBits(B) < NeededSignBits)
1925 return 0;
1926
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001927 // In order to replace the original add with a narrower
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001928 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1929 // and truncates that discard the high bits of the add. Verify that this is
1930 // the case.
1931 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1932 for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1933 UI != E; ++UI) {
1934 if (*UI == AddWithCst) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001935
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001936 // Only accept truncates for now. We would really like a nice recursive
1937 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1938 // chain to see which bits of a value are actually demanded. If the
1939 // original add had another add which was then immediately truncated, we
1940 // could still do the transformation.
1941 TruncInst *TI = dyn_cast<TruncInst>(*UI);
1942 if (TI == 0 ||
1943 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1944 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001945
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001946 // If the pattern matches, truncate the inputs to the narrower type and
1947 // use the sadd_with_overflow intrinsic to efficiently compute both the
1948 // result and the overflow bit.
Chris Lattner0a624742010-12-19 18:35:09 +00001949 Module *M = I.getParent()->getParent()->getParent();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001950
Jay Foad5fdd6c82011-07-12 14:06:48 +00001951 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Chris Lattner0a624742010-12-19 18:35:09 +00001952 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001953 NewType);
Chris Lattner0a624742010-12-19 18:35:09 +00001954
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001955 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001956
Chris Lattner0a624742010-12-19 18:35:09 +00001957 // Put the new code above the original add, in case there are any uses of the
1958 // add between the add and the compare.
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001959 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001960
Chris Lattner0a624742010-12-19 18:35:09 +00001961 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1962 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1963 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1964 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1965 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001966
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001967 // The inner add was the result of the narrow add, zero extended to the
1968 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001969 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001970
Chris Lattner0a624742010-12-19 18:35:09 +00001971 // The original icmp gets replaced with the overflow value.
1972 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001973}
Chris Lattner02446fc2010-01-04 07:37:31 +00001974
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001975static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1976 InstCombiner &IC) {
1977 // Don't bother doing this transformation for pointers, don't do it for
1978 // vectors.
1979 if (!isa<IntegerType>(OrigAddV->getType())) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001980
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001981 // If the add is a constant expr, then we don't bother transforming it.
1982 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1983 if (OrigAdd == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001984
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001985 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001986
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001987 // Put the new code above the original add, in case there are any uses of the
1988 // add between the add and the compare.
1989 InstCombiner::BuilderTy *Builder = IC.Builder;
1990 Builder->SetInsertPoint(OrigAdd);
1991
1992 Module *M = I.getParent()->getParent()->getParent();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001993 Type *Ty = LHS->getType();
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001994 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001995 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1996 Value *Add = Builder->CreateExtractValue(Call, 0);
1997
1998 IC.ReplaceInstUsesWith(*OrigAdd, Add);
1999
2000 // The original icmp gets replaced with the overflow value.
2001 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
2002}
2003
Owen Andersonda1c1222011-01-11 00:36:45 +00002004// DemandedBitsLHSMask - When performing a comparison against a constant,
2005// it is possible that not all the bits in the LHS are demanded. This helper
2006// method computes the mask that IS demanded.
2007static APInt DemandedBitsLHSMask(ICmpInst &I,
2008 unsigned BitWidth, bool isSignCheck) {
2009 if (isSignCheck)
2010 return APInt::getSignBit(BitWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002011
Owen Andersonda1c1222011-01-11 00:36:45 +00002012 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2013 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Andersona33b6252011-01-11 18:26:37 +00002014 const APInt &RHS = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002015
Owen Andersonda1c1222011-01-11 00:36:45 +00002016 switch (I.getPredicate()) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002017 // For a UGT comparison, we don't care about any bits that
Owen Andersonda1c1222011-01-11 00:36:45 +00002018 // correspond to the trailing ones of the comparand. The value of these
2019 // bits doesn't impact the outcome of the comparison, because any value
2020 // greater than the RHS must differ in a bit higher than these due to carry.
2021 case ICmpInst::ICMP_UGT: {
2022 unsigned trailingOnes = RHS.countTrailingOnes();
2023 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2024 return ~lowBitsSet;
2025 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002026
Owen Andersonda1c1222011-01-11 00:36:45 +00002027 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2028 // Any value less than the RHS must differ in a higher bit because of carries.
2029 case ICmpInst::ICMP_ULT: {
2030 unsigned trailingZeros = RHS.countTrailingZeros();
2031 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2032 return ~lowBitsSet;
2033 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002034
Owen Andersonda1c1222011-01-11 00:36:45 +00002035 default:
2036 return APInt::getAllOnesValue(BitWidth);
2037 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002038
Owen Andersonda1c1222011-01-11 00:36:45 +00002039}
Chris Lattner02446fc2010-01-04 07:37:31 +00002040
Quentin Colombet2c6ef1c2013-09-09 20:56:48 +00002041/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2042/// should be swapped.
2043/// The descision is based on how many times these two operands are reused
2044/// as subtract operands and their positions in those instructions.
2045/// The rational is that several architectures use the same instruction for
2046/// both subtract and cmp, thus it is better if the order of those operands
2047/// match.
2048/// \return true if Op0 and Op1 should be swapped.
2049static bool swapMayExposeCSEOpportunities(const Value * Op0,
2050 const Value * Op1) {
2051 // Filter out pointer value as those cannot appears directly in subtract.
2052 // FIXME: we may want to go through inttoptrs or bitcasts.
2053 if (Op0->getType()->isPointerTy())
2054 return false;
2055 // Count every uses of both Op0 and Op1 in a subtract.
2056 // Each time Op0 is the first operand, count -1: swapping is bad, the
2057 // subtract has already the same layout as the compare.
2058 // Each time Op0 is the second operand, count +1: swapping is good, the
2059 // subtract has a diffrent layout as the compare.
2060 // At the end, if the benefit is greater than 0, Op0 should come second to
2061 // expose more CSE opportunities.
2062 int GlobalSwapBenefits = 0;
2063 for (Value::const_use_iterator UI = Op0->use_begin(), UIEnd = Op0->use_end(); UI != UIEnd; ++UI) {
2064 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(*UI);
2065 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2066 continue;
2067 // If Op0 is the first argument, this is not beneficial to swap the
2068 // arguments.
2069 int LocalSwapBenefits = -1;
2070 unsigned Op1Idx = 1;
2071 if (BinOp->getOperand(Op1Idx) == Op0) {
2072 Op1Idx = 0;
2073 LocalSwapBenefits = 1;
2074 }
2075 if (BinOp->getOperand(Op1Idx) != Op1)
2076 continue;
2077 GlobalSwapBenefits += LocalSwapBenefits;
2078 }
2079 return GlobalSwapBenefits > 0;
2080}
2081
Chris Lattner02446fc2010-01-04 07:37:31 +00002082Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
2083 bool Changed = false;
Chris Lattner5f670d42010-02-01 19:54:45 +00002084 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet2c6ef1c2013-09-09 20:56:48 +00002085 unsigned Op0Cplxity = getComplexity(Op0);
2086 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002087
Chris Lattner02446fc2010-01-04 07:37:31 +00002088 /// Orders the operands of the compare so that they are listed from most
2089 /// complex to least complex. This puts constants before unary operators,
2090 /// before binary operators.
Quentin Colombet2c6ef1c2013-09-09 20:56:48 +00002091 if (Op0Cplxity < Op1Cplxity ||
2092 (Op0Cplxity == Op1Cplxity &&
2093 swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002094 I.swapOperands();
Chris Lattner5f670d42010-02-01 19:54:45 +00002095 std::swap(Op0, Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00002096 Changed = true;
2097 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002098
Chris Lattner02446fc2010-01-04 07:37:31 +00002099 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
2100 return ReplaceInstUsesWith(I, V);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002101
Pete Cooper65a6b572011-12-01 03:58:40 +00002102 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooper165695d2011-12-01 19:13:26 +00002103 // ie, abs(val) != 0 -> val != 0
Pete Cooper65a6b572011-12-01 03:58:40 +00002104 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
2105 {
Pete Cooper165695d2011-12-01 19:13:26 +00002106 Value *Cond, *SelectTrue, *SelectFalse;
2107 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooper65a6b572011-12-01 03:58:40 +00002108 m_Value(SelectFalse)))) {
Pete Cooper165695d2011-12-01 19:13:26 +00002109 if (Value *V = dyn_castNegVal(SelectTrue)) {
2110 if (V == SelectFalse)
2111 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2112 }
2113 else if (Value *V = dyn_castNegVal(SelectFalse)) {
2114 if (V == SelectTrue)
2115 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooper65a6b572011-12-01 03:58:40 +00002116 }
2117 }
2118 }
2119
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002120 Type *Ty = Op0->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00002121
2122 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002123 if (Ty->isIntegerTy(1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002124 switch (I.getPredicate()) {
2125 default: llvm_unreachable("Invalid icmp instruction!");
2126 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
2127 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
2128 return BinaryOperator::CreateNot(Xor);
2129 }
2130 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
2131 return BinaryOperator::CreateXor(Op0, Op1);
2132
2133 case ICmpInst::ICMP_UGT:
2134 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
2135 // FALL THROUGH
2136 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
2137 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2138 return BinaryOperator::CreateAnd(Not, Op1);
2139 }
2140 case ICmpInst::ICMP_SGT:
2141 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
2142 // FALL THROUGH
2143 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
2144 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2145 return BinaryOperator::CreateAnd(Not, Op0);
2146 }
2147 case ICmpInst::ICMP_UGE:
2148 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
2149 // FALL THROUGH
2150 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
2151 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2152 return BinaryOperator::CreateOr(Not, Op1);
2153 }
2154 case ICmpInst::ICMP_SGE:
2155 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
2156 // FALL THROUGH
2157 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
2158 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2159 return BinaryOperator::CreateOr(Not, Op0);
2160 }
2161 }
2162 }
2163
2164 unsigned BitWidth = 0;
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002165 if (Ty->isIntOrIntVectorTy())
Chris Lattner02446fc2010-01-04 07:37:31 +00002166 BitWidth = Ty->getScalarSizeInBits();
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002167 else if (TD) // Pointers require TD info to get their size.
2168 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002169
Chris Lattner02446fc2010-01-04 07:37:31 +00002170 bool isSignBit = false;
2171
2172 // See if we are doing a comparison with a constant.
2173 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2174 Value *A = 0, *B = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002175
Owen Andersone63dda52010-12-17 18:08:00 +00002176 // Match the following pattern, which is a common idiom when writing
2177 // overflow-safe integer arithmetic function. The source performs an
2178 // addition in wider type, and explicitly checks for overflow using
2179 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
2180 // sadd_with_overflow intrinsic.
Chris Lattnerf0f568b2010-12-19 17:52:50 +00002181 //
2182 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002183 // operations if we worked out the formulas to compute the appropriate
Owen Andersone63dda52010-12-17 18:08:00 +00002184 // magic constants.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002185 //
Chris Lattnerf0f568b2010-12-19 17:52:50 +00002186 // sum = a + b
2187 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Andersone63dda52010-12-17 18:08:00 +00002188 {
Chris Lattnerf0f568b2010-12-19 17:52:50 +00002189 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Andersone63dda52010-12-17 18:08:00 +00002190 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattnerf0f568b2010-12-19 17:52:50 +00002191 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattner0fe80bb2010-12-19 18:38:44 +00002192 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattnerf0f568b2010-12-19 17:52:50 +00002193 return Res;
Owen Andersone63dda52010-12-17 18:08:00 +00002194 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002195
Chris Lattner02446fc2010-01-04 07:37:31 +00002196 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2197 if (I.isEquality() && CI->isZero() &&
2198 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
2199 // (icmp cond A B) if cond is equality
2200 return new ICmpInst(I.getPredicate(), A, B);
2201 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002202
Chris Lattner02446fc2010-01-04 07:37:31 +00002203 // If we have an icmp le or icmp ge instruction, turn it into the
2204 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
2205 // them being folded in the code below. The SimplifyICmpInst code has
2206 // already handled the edge cases for us, so we just assert on them.
2207 switch (I.getPredicate()) {
2208 default: break;
2209 case ICmpInst::ICMP_ULE:
2210 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
2211 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002212 Builder->getInt(CI->getValue()+1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002213 case ICmpInst::ICMP_SLE:
2214 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
2215 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002216 Builder->getInt(CI->getValue()+1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002217 case ICmpInst::ICMP_UGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00002218 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00002219 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002220 Builder->getInt(CI->getValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002221 case ICmpInst::ICMP_SGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00002222 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00002223 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002224 Builder->getInt(CI->getValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002225 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002226
Chris Lattner02446fc2010-01-04 07:37:31 +00002227 // If this comparison is a normal comparison, it demands all
2228 // bits, if it is a sign bit comparison, it only demands the sign bit.
2229 bool UnusedBit;
2230 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2231 }
2232
2233 // See if we can fold the comparison based on range information we can get
2234 // by checking whether bits are known to be zero or one in the input.
2235 if (BitWidth != 0) {
2236 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2237 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2238
2239 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersonda1c1222011-01-11 00:36:45 +00002240 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner02446fc2010-01-04 07:37:31 +00002241 Op0KnownZero, Op0KnownOne, 0))
2242 return &I;
2243 if (SimplifyDemandedBits(I.getOperandUse(1),
2244 APInt::getAllOnesValue(BitWidth),
2245 Op1KnownZero, Op1KnownOne, 0))
2246 return &I;
2247
2248 // Given the known and unknown bits, compute a range that the LHS could be
2249 // in. Compute the Min, Max and RHS values based on the known bits. For the
2250 // EQ and NE we use unsigned values.
2251 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2252 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2253 if (I.isSigned()) {
2254 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2255 Op0Min, Op0Max);
2256 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2257 Op1Min, Op1Max);
2258 } else {
2259 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2260 Op0Min, Op0Max);
2261 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2262 Op1Min, Op1Max);
2263 }
2264
2265 // If Min and Max are known to be the same, then SimplifyDemandedBits
2266 // figured out that the LHS is a constant. Just constant fold this now so
2267 // that code below can assume that Min != Max.
2268 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2269 return new ICmpInst(I.getPredicate(),
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002270 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00002271 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2272 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002273 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner02446fc2010-01-04 07:37:31 +00002274
2275 // Based on the range information we know about the LHS, see if we can
Nick Lewyckyd8d15842011-02-28 06:20:05 +00002276 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner02446fc2010-01-04 07:37:31 +00002277 switch (I.getPredicate()) {
2278 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner75d8f592010-11-21 06:44:42 +00002279 case ICmpInst::ICMP_EQ: {
Chris Lattner02446fc2010-01-04 07:37:31 +00002280 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002281 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002282
Chris Lattner75d8f592010-11-21 06:44:42 +00002283 // If all bits are known zero except for one, then we know at most one
2284 // bit is set. If the comparison is against zero, then this is a check
2285 // to see if *that* bit is set.
2286 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2287 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2288 // If the LHS is an AND with the same constant, look through it.
2289 Value *LHS = 0;
2290 ConstantInt *LHSC = 0;
2291 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2292 LHSC->getValue() != Op0KnownZeroInverted)
2293 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002294
Chris Lattner75d8f592010-11-21 06:44:42 +00002295 // 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 +00002296 // then turn "((1 << x)&8) == 0" into "x != 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002297 Value *X = 0;
2298 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2299 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002300 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002301 ConstantInt::get(X->getType(), CmpVal));
2302 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002303
Chris Lattner75d8f592010-11-21 06:44:42 +00002304 // 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 +00002305 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002306 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002307 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002308 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002309 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002310 ConstantInt::get(X->getType(),
2311 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002312 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002313
Chris Lattner02446fc2010-01-04 07:37:31 +00002314 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002315 }
2316 case ICmpInst::ICMP_NE: {
Chris Lattner02446fc2010-01-04 07:37:31 +00002317 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002318 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002319
Chris Lattner75d8f592010-11-21 06:44:42 +00002320 // If all bits are known zero except for one, then we know at most one
2321 // bit is set. If the comparison is against zero, then this is a check
2322 // to see if *that* bit is set.
2323 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2324 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2325 // If the LHS is an AND with the same constant, look through it.
2326 Value *LHS = 0;
2327 ConstantInt *LHSC = 0;
2328 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2329 LHSC->getValue() != Op0KnownZeroInverted)
2330 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002331
Chris Lattner75d8f592010-11-21 06:44:42 +00002332 // 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 +00002333 // then turn "((1 << x)&8) != 0" into "x == 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002334 Value *X = 0;
2335 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2336 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002337 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002338 ConstantInt::get(X->getType(), CmpVal));
2339 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002340
Chris Lattner75d8f592010-11-21 06:44:42 +00002341 // 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 +00002342 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002343 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002344 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002345 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002346 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002347 ConstantInt::get(X->getType(),
2348 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002349 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002350
Chris Lattner02446fc2010-01-04 07:37:31 +00002351 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002352 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002353 case ICmpInst::ICMP_ULT:
2354 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002355 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002356 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002357 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002358 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2359 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2360 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2361 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2362 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002363 Builder->getInt(CI->getValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002364
2365 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2366 if (CI->isMinValue(true))
2367 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2368 Constant::getAllOnesValue(Op0->getType()));
2369 }
2370 break;
2371 case ICmpInst::ICMP_UGT:
2372 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002373 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002374 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002375 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002376
2377 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2378 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2379 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2380 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2381 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002382 Builder->getInt(CI->getValue()+1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002383
2384 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2385 if (CI->isMaxValue(true))
2386 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2387 Constant::getNullValue(Op0->getType()));
2388 }
2389 break;
2390 case ICmpInst::ICMP_SLT:
2391 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002392 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002393 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002394 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002395 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2396 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2397 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2398 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2399 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002400 Builder->getInt(CI->getValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002401 }
2402 break;
2403 case ICmpInst::ICMP_SGT:
2404 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002405 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002406 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002407 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002408
2409 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2410 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2411 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2412 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2413 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002414 Builder->getInt(CI->getValue()+1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002415 }
2416 break;
2417 case ICmpInst::ICMP_SGE:
2418 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2419 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002420 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002421 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002422 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002423 break;
2424 case ICmpInst::ICMP_SLE:
2425 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2426 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002427 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002428 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002429 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002430 break;
2431 case ICmpInst::ICMP_UGE:
2432 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2433 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002434 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002435 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002436 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002437 break;
2438 case ICmpInst::ICMP_ULE:
2439 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2440 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002441 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002442 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002443 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002444 break;
2445 }
2446
2447 // Turn a signed comparison into an unsigned one if both operands
2448 // are known to have the same sign.
2449 if (I.isSigned() &&
2450 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2451 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2452 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2453 }
2454
2455 // Test if the ICmpInst instruction is used exclusively by a select as
2456 // part of a minimum or maximum operation. If so, refrain from doing
2457 // any other folding. This helps out other analyses which understand
2458 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2459 // and CodeGen. And in this case, at least one of the comparison
2460 // operands has at least one user besides the compare (the select),
2461 // which would often largely negate the benefit of folding anyway.
2462 if (I.hasOneUse())
2463 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2464 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2465 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2466 return 0;
2467
2468 // See if we are doing a comparison between a constant and an instruction that
2469 // can be folded into the comparison.
2470 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002471 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2472 // instruction, see if that instruction also has constants so that the
2473 // instruction can be folded into the icmp
Chris Lattner02446fc2010-01-04 07:37:31 +00002474 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2475 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2476 return Res;
2477 }
2478
2479 // Handle icmp with constant (but not simple integer constant) RHS
2480 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2481 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2482 switch (LHSI->getOpcode()) {
2483 case Instruction::GetElementPtr:
2484 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2485 if (RHSC->isNullValue() &&
2486 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2487 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2488 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2489 break;
2490 case Instruction::PHI:
2491 // Only fold icmp into the PHI if the phi and icmp are in the same
2492 // block. If in the same block, we're encouraging jump threading. If
2493 // not, we are just pessimizing the code by making an i1 phi.
2494 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002495 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002496 return NV;
2497 break;
2498 case Instruction::Select: {
2499 // If either operand of the select is a constant, we can fold the
2500 // comparison into the select arms, which will cause one to be
2501 // constant folded and the select turned into a bitwise or.
2502 Value *Op1 = 0, *Op2 = 0;
2503 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2504 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2505 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2506 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2507
2508 // We only want to perform this transformation if it will not lead to
2509 // additional code. This is true if either both sides of the select
2510 // fold to a constant (in which case the icmp is replaced with a select
2511 // which will usually simplify) or this is the only user of the
2512 // select (in which case we are trading a select+icmp for a simpler
2513 // select+icmp).
2514 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2515 if (!Op1)
2516 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2517 RHSC, I.getName());
2518 if (!Op2)
2519 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2520 RHSC, I.getName());
2521 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2522 }
2523 break;
2524 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002525 case Instruction::IntToPtr:
2526 // icmp pred inttoptr(X), null -> icmp pred X, 0
2527 if (RHSC->isNullValue() && TD &&
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00002528 TD->getIntPtrType(RHSC->getType()) ==
Chris Lattner02446fc2010-01-04 07:37:31 +00002529 LHSI->getOperand(0)->getType())
2530 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2531 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2532 break;
2533
2534 case Instruction::Load:
2535 // Try to optimize things like "A[i] > 4" to index computations.
2536 if (GetElementPtrInst *GEP =
2537 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2538 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2539 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2540 !cast<LoadInst>(LHSI)->isVolatile())
2541 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2542 return Res;
2543 }
2544 break;
2545 }
2546 }
2547
2548 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2549 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2550 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2551 return NI;
2552 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2553 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2554 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2555 return NI;
2556
2557 // Test to see if the operands of the icmp are casted versions of other
2558 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
2559 // now.
2560 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002561 if (Op0->getType()->isPointerTy() &&
2562 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002563 // We keep moving the cast from the left operand over to the right
2564 // operand, where it can often be eliminated completely.
2565 Op0 = CI->getOperand(0);
2566
2567 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2568 // so eliminate it as well.
2569 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2570 Op1 = CI2->getOperand(0);
2571
2572 // If Op1 is a constant, we can fold the cast into the constant.
2573 if (Op0->getType() != Op1->getType()) {
2574 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2575 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2576 } else {
2577 // Otherwise, cast the RHS right before the icmp
2578 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2579 }
2580 }
2581 return new ICmpInst(I.getPredicate(), Op0, Op1);
2582 }
2583 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002584
Chris Lattner02446fc2010-01-04 07:37:31 +00002585 if (isa<CastInst>(Op0)) {
2586 // Handle the special case of: icmp (cast bool to X), <cst>
2587 // This comes up when you have code like
2588 // int X = A < B;
2589 // if (X) ...
2590 // For generality, we handle any zero-extension of any operand comparison
2591 // with a constant or another cast from the same type.
2592 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2593 if (Instruction *R = visitICmpInstWithCastAndCast(I))
2594 return R;
2595 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002596
Duncan Sandsa7724332011-02-17 07:46:37 +00002597 // Special logic for binary operators.
2598 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2599 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2600 if (BO0 || BO1) {
2601 CmpInst::Predicate Pred = I.getPredicate();
2602 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2603 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2604 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2605 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2606 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2607 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2608 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2609 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2610 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2611
2612 // Analyze the case when either Op0 or Op1 is an add instruction.
2613 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2614 Value *A = 0, *B = 0, *C = 0, *D = 0;
2615 if (BO0 && BO0->getOpcode() == Instruction::Add)
2616 A = BO0->getOperand(0), B = BO0->getOperand(1);
2617 if (BO1 && BO1->getOpcode() == Instruction::Add)
2618 C = BO1->getOperand(0), D = BO1->getOperand(1);
2619
2620 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2621 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2622 return new ICmpInst(Pred, A == Op1 ? B : A,
2623 Constant::getNullValue(Op1->getType()));
2624
2625 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2626 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2627 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2628 C == Op0 ? D : C);
2629
Duncan Sands39a7de72011-02-18 16:25:37 +00002630 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002631 if (A && C && (A == C || A == D || B == C || B == D) &&
2632 NoOp0WrapProblem && NoOp1WrapProblem &&
2633 // Try not to increase register pressure.
2634 BO0->hasOneUse() && BO1->hasOneUse()) {
2635 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsafe45392012-11-16 18:55:49 +00002636 Value *Y, *Z;
2637 if (A == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002638 // C + B == C + D -> B == D
Duncan Sandsafe45392012-11-16 18:55:49 +00002639 Y = B;
2640 Z = D;
2641 } else if (A == D) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002642 // D + B == C + D -> B == C
Duncan Sandsafe45392012-11-16 18:55:49 +00002643 Y = B;
2644 Z = C;
2645 } else if (B == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002646 // A + C == C + D -> A == D
Duncan Sandsafe45392012-11-16 18:55:49 +00002647 Y = A;
2648 Z = D;
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002649 } else {
2650 assert(B == D);
2651 // A + D == C + D -> A == C
Duncan Sandsafe45392012-11-16 18:55:49 +00002652 Y = A;
2653 Z = C;
2654 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002655 return new ICmpInst(Pred, Y, Z);
2656 }
2657
David Majnemer59b11c42013-04-11 20:05:46 +00002658 // icmp slt (X + -1), Y -> icmp sle X, Y
2659 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
2660 match(B, m_AllOnes()))
2661 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
2662
2663 // icmp sge (X + -1), Y -> icmp sgt X, Y
2664 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
2665 match(B, m_AllOnes()))
2666 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
2667
2668 // icmp sle (X + 1), Y -> icmp slt X, Y
2669 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
2670 match(B, m_One()))
2671 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
2672
2673 // icmp sgt (X + 1), Y -> icmp sge X, Y
2674 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
2675 match(B, m_One()))
2676 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
2677
2678 // if C1 has greater magnitude than C2:
2679 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
2680 // s.t. C3 = C1 - C2
2681 //
2682 // if C2 has greater magnitude than C1:
2683 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
2684 // s.t. C3 = C2 - C1
2685 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
2686 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
2687 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
2688 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
2689 const APInt &AP1 = C1->getValue();
2690 const APInt &AP2 = C2->getValue();
2691 if (AP1.isNegative() == AP2.isNegative()) {
2692 APInt AP1Abs = C1->getValue().abs();
2693 APInt AP2Abs = C2->getValue().abs();
2694 if (AP1Abs.uge(AP2Abs)) {
2695 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
2696 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
2697 return new ICmpInst(Pred, NewAdd, C);
2698 } else {
2699 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
2700 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
2701 return new ICmpInst(Pred, A, NewAdd);
2702 }
2703 }
2704 }
2705
2706
Duncan Sandsa7724332011-02-17 07:46:37 +00002707 // Analyze the case when either Op0 or Op1 is a sub instruction.
2708 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2709 A = 0; B = 0; C = 0; D = 0;
2710 if (BO0 && BO0->getOpcode() == Instruction::Sub)
2711 A = BO0->getOperand(0), B = BO0->getOperand(1);
2712 if (BO1 && BO1->getOpcode() == Instruction::Sub)
2713 C = BO1->getOperand(0), D = BO1->getOperand(1);
2714
Duncan Sands39a7de72011-02-18 16:25:37 +00002715 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2716 if (A == Op1 && NoOp0WrapProblem)
2717 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2718
2719 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2720 if (C == Op0 && NoOp1WrapProblem)
2721 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2722
2723 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002724 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2725 // Try not to increase register pressure.
2726 BO0->hasOneUse() && BO1->hasOneUse())
2727 return new ICmpInst(Pred, A, C);
2728
Duncan Sands39a7de72011-02-18 16:25:37 +00002729 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2730 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2731 // Try not to increase register pressure.
2732 BO0->hasOneUse() && BO1->hasOneUse())
2733 return new ICmpInst(Pred, D, B);
2734
Nick Lewycky9feda172011-03-05 04:28:48 +00002735 BinaryOperator *SRem = NULL;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002736 // icmp (srem X, Y), Y
Nick Lewycky9feda172011-03-05 04:28:48 +00002737 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2738 Op1 == BO0->getOperand(1))
2739 SRem = BO0;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002740 // icmp Y, (srem X, Y)
Nick Lewycky9feda172011-03-05 04:28:48 +00002741 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2742 Op0 == BO1->getOperand(1))
2743 SRem = BO1;
2744 if (SRem) {
2745 // We don't check hasOneUse to avoid increasing register pressure because
2746 // the value we use is the same value this instruction was already using.
2747 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2748 default: break;
2749 case ICmpInst::ICMP_EQ:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002750 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002751 case ICmpInst::ICMP_NE:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002752 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002753 case ICmpInst::ICMP_SGT:
2754 case ICmpInst::ICMP_SGE:
2755 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2756 Constant::getAllOnesValue(SRem->getType()));
2757 case ICmpInst::ICMP_SLT:
2758 case ICmpInst::ICMP_SLE:
2759 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2760 Constant::getNullValue(SRem->getType()));
2761 }
2762 }
2763
Duncan Sandsa7724332011-02-17 07:46:37 +00002764 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2765 BO0->hasOneUse() && BO1->hasOneUse() &&
2766 BO0->getOperand(1) == BO1->getOperand(1)) {
2767 switch (BO0->getOpcode()) {
2768 default: break;
2769 case Instruction::Add:
2770 case Instruction::Sub:
2771 case Instruction::Xor:
2772 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
2773 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2774 BO1->getOperand(0));
2775 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2776 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2777 if (CI->getValue().isSignBit()) {
2778 ICmpInst::Predicate Pred = I.isSigned()
2779 ? I.getUnsignedPredicate()
2780 : I.getSignedPredicate();
2781 return new ICmpInst(Pred, BO0->getOperand(0),
2782 BO1->getOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00002783 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002784
Chris Lattnerc73b24d2011-07-15 06:08:15 +00002785 if (CI->isMaxValue(true)) {
Duncan Sandsa7724332011-02-17 07:46:37 +00002786 ICmpInst::Predicate Pred = I.isSigned()
2787 ? I.getUnsignedPredicate()
2788 : I.getSignedPredicate();
2789 Pred = I.getSwappedPredicate(Pred);
2790 return new ICmpInst(Pred, BO0->getOperand(0),
2791 BO1->getOperand(0));
2792 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002793 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002794 break;
2795 case Instruction::Mul:
2796 if (!I.isEquality())
2797 break;
2798
2799 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2800 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2801 // Mask = -1 >> count-trailing-zeros(Cst).
2802 if (!CI->isZero() && !CI->isOne()) {
2803 const APInt &AP = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002804 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandsa7724332011-02-17 07:46:37 +00002805 APInt::getLowBitsSet(AP.getBitWidth(),
2806 AP.getBitWidth() -
2807 AP.countTrailingZeros()));
2808 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2809 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2810 return new ICmpInst(I.getPredicate(), And1, And2);
2811 }
2812 }
2813 break;
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002814 case Instruction::UDiv:
2815 case Instruction::LShr:
2816 if (I.isSigned())
2817 break;
2818 // fall-through
2819 case Instruction::SDiv:
2820 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002821 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002822 break;
2823 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2824 BO1->getOperand(0));
2825 case Instruction::Shl: {
2826 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2827 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2828 if (!NUW && !NSW)
2829 break;
2830 if (!NSW && I.isSigned())
2831 break;
2832 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2833 BO1->getOperand(0));
2834 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002835 }
2836 }
2837 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002838
Chris Lattner02446fc2010-01-04 07:37:31 +00002839 { Value *A, *B;
David Majnemerfb1cd692013-04-12 17:25:07 +00002840 // Transform (A & ~B) == 0 --> (A & B) != 0
2841 // and (A & ~B) != 0 --> (A & B) == 0
2842 // if A is a power of 2.
2843 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2844 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A) && I.isEquality())
2845 return new ICmpInst(I.getInversePredicate(),
2846 Builder->CreateAnd(A, B),
2847 Op1);
2848
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002849 // ~x < ~y --> y < x
2850 // ~x < cst --> ~cst < x
2851 if (match(Op0, m_Not(m_Value(A)))) {
2852 if (match(Op1, m_Not(m_Value(B))))
2853 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner27a98482011-01-15 05:42:47 +00002854 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002855 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2856 }
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002857
2858 // (a+b) <u a --> llvm.uadd.with.overflow.
2859 // (a+b) <u b --> llvm.uadd.with.overflow.
2860 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002861 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002862 (Op1 == A || Op1 == B))
2863 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2864 return R;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002865
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002866 // a >u (a+b) --> llvm.uadd.with.overflow.
2867 // b >u (a+b) --> llvm.uadd.with.overflow.
2868 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2869 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2870 (Op0 == A || Op0 == B))
2871 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2872 return R;
Chris Lattner02446fc2010-01-04 07:37:31 +00002873 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002874
Chris Lattner02446fc2010-01-04 07:37:31 +00002875 if (I.isEquality()) {
2876 Value *A, *B, *C, *D;
Duncan Sands39a7de72011-02-18 16:25:37 +00002877
Chris Lattner02446fc2010-01-04 07:37:31 +00002878 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2879 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
2880 Value *OtherVal = A == Op1 ? B : A;
2881 return new ICmpInst(I.getPredicate(), OtherVal,
2882 Constant::getNullValue(A->getType()));
2883 }
2884
2885 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2886 // A^c1 == C^c2 --> A == C^(c1^c2)
2887 ConstantInt *C1, *C2;
2888 if (match(B, m_ConstantInt(C1)) &&
2889 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszak3facc432013-06-06 20:18:46 +00002890 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramera9390a42011-09-27 20:39:19 +00002891 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner02446fc2010-01-04 07:37:31 +00002892 return new ICmpInst(I.getPredicate(), A, Xor);
2893 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002894
Chris Lattner02446fc2010-01-04 07:37:31 +00002895 // A^B == A^D -> B == D
2896 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2897 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2898 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2899 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2900 }
2901 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002902
Chris Lattner02446fc2010-01-04 07:37:31 +00002903 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2904 (A == Op0 || B == Op0)) {
2905 // A == (A^B) -> B == 0
2906 Value *OtherVal = A == Op0 ? B : A;
2907 return new ICmpInst(I.getPredicate(), OtherVal,
2908 Constant::getNullValue(A->getType()));
2909 }
2910
Chris Lattner02446fc2010-01-04 07:37:31 +00002911 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002912 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner5036ce42011-04-26 20:02:45 +00002913 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002914 Value *X = 0, *Y = 0, *Z = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002915
Chris Lattner02446fc2010-01-04 07:37:31 +00002916 if (A == C) {
2917 X = B; Y = D; Z = A;
2918 } else if (A == D) {
2919 X = B; Y = C; Z = A;
2920 } else if (B == C) {
2921 X = A; Y = D; Z = B;
2922 } else if (B == D) {
2923 X = A; Y = C; Z = B;
2924 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002925
Chris Lattner02446fc2010-01-04 07:37:31 +00002926 if (X) { // Build (X^Y) & Z
Benjamin Kramera9390a42011-09-27 20:39:19 +00002927 Op1 = Builder->CreateXor(X, Y);
2928 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner02446fc2010-01-04 07:37:31 +00002929 I.setOperand(0, Op1);
2930 I.setOperand(1, Constant::getNullValue(Op1->getType()));
2931 return &I;
2932 }
2933 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002934
Benjamin Kramer66821d92012-06-10 20:35:00 +00002935 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer7a99b462012-06-11 08:01:25 +00002936 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer66821d92012-06-10 20:35:00 +00002937 ConstantInt *Cst1;
Benjamin Kramer7a99b462012-06-11 08:01:25 +00002938 if ((Op0->hasOneUse() &&
2939 match(Op0, m_ZExt(m_Value(A))) &&
2940 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
2941 (Op1->hasOneUse() &&
2942 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
2943 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer66821d92012-06-10 20:35:00 +00002944 APInt Pow2 = Cst1->getValue() + 1;
2945 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
2946 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
2947 return new ICmpInst(I.getPredicate(), A,
2948 Builder->CreateTrunc(B, A->getType()));
2949 }
2950
Benjamin Kramere9cdbf62013-11-16 16:00:48 +00002951 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
2952 // For lshr and ashr pairs.
2953 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
2954 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
2955 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
2956 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
2957 unsigned TypeBits = Cst1->getBitWidth();
2958 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
2959 if (ShAmt < TypeBits && ShAmt != 0) {
2960 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
2961 ? ICmpInst::ICMP_UGE
2962 : ICmpInst::ICMP_ULT;
2963 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
2964 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
2965 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
2966 }
2967 }
2968
Chris Lattner325eeb12011-04-26 20:18:20 +00002969 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2970 // "icmp (and X, mask), cst"
2971 uint64_t ShAmt = 0;
Chris Lattner325eeb12011-04-26 20:18:20 +00002972 if (Op0->hasOneUse() &&
2973 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2974 m_ConstantInt(ShAmt))))) &&
2975 match(Op1, m_ConstantInt(Cst1)) &&
2976 // Only do this when A has multiple uses. This is most important to do
2977 // when it exposes other optimizations.
2978 !A->hasOneUse()) {
2979 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002980
Chris Lattner325eeb12011-04-26 20:18:20 +00002981 if (ShAmt < ASize) {
2982 APInt MaskV =
2983 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2984 MaskV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002985
Chris Lattner325eeb12011-04-26 20:18:20 +00002986 APInt CmpV = Cst1->getValue().zext(ASize);
2987 CmpV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002988
Chris Lattner325eeb12011-04-26 20:18:20 +00002989 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2990 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2991 }
2992 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002993 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002994
Chris Lattner02446fc2010-01-04 07:37:31 +00002995 {
2996 Value *X; ConstantInt *Cst;
2997 // icmp X+Cst, X
2998 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Benjamin Kramer19a6f112013-09-20 22:12:42 +00002999 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
Chris Lattner02446fc2010-01-04 07:37:31 +00003000
3001 // icmp X, X+Cst
3002 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Benjamin Kramer19a6f112013-09-20 22:12:42 +00003003 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner02446fc2010-01-04 07:37:31 +00003004 }
3005 return Changed ? &I : 0;
3006}
3007
Chris Lattner02446fc2010-01-04 07:37:31 +00003008/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
3009///
3010Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
3011 Instruction *LHSI,
3012 Constant *RHSC) {
3013 if (!isa<ConstantFP>(RHSC)) return 0;
3014 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003015
Chris Lattner02446fc2010-01-04 07:37:31 +00003016 // Get the width of the mantissa. We don't want to hack on conversions that
3017 // might lose information from the integer, e.g. "i64 -> float"
3018 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
3019 if (MantissaWidth == -1) return 0; // Unknown.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003020
Chris Lattner02446fc2010-01-04 07:37:31 +00003021 // Check to see that the input is converted from an integer type that is small
3022 // enough that preserves all bits. TODO: check here for "known" sign bits.
3023 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
3024 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003025
Chris Lattner02446fc2010-01-04 07:37:31 +00003026 // If this is a uitofp instruction, we need an extra bit to hold the sign.
3027 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
3028 if (LHSUnsigned)
3029 ++InputSize;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003030
Chris Lattner02446fc2010-01-04 07:37:31 +00003031 // If the conversion would lose info, don't hack on this.
3032 if ((int)InputSize > MantissaWidth)
3033 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003034
Chris Lattner02446fc2010-01-04 07:37:31 +00003035 // Otherwise, we can potentially simplify the comparison. We know that it
3036 // will always come through as an integer value and we know the constant is
3037 // not a NAN (it would have been previously simplified).
3038 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003039
Chris Lattner02446fc2010-01-04 07:37:31 +00003040 ICmpInst::Predicate Pred;
3041 switch (I.getPredicate()) {
3042 default: llvm_unreachable("Unexpected predicate!");
3043 case FCmpInst::FCMP_UEQ:
3044 case FCmpInst::FCMP_OEQ:
3045 Pred = ICmpInst::ICMP_EQ;
3046 break;
3047 case FCmpInst::FCMP_UGT:
3048 case FCmpInst::FCMP_OGT:
3049 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
3050 break;
3051 case FCmpInst::FCMP_UGE:
3052 case FCmpInst::FCMP_OGE:
3053 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
3054 break;
3055 case FCmpInst::FCMP_ULT:
3056 case FCmpInst::FCMP_OLT:
3057 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
3058 break;
3059 case FCmpInst::FCMP_ULE:
3060 case FCmpInst::FCMP_OLE:
3061 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
3062 break;
3063 case FCmpInst::FCMP_UNE:
3064 case FCmpInst::FCMP_ONE:
3065 Pred = ICmpInst::ICMP_NE;
3066 break;
3067 case FCmpInst::FCMP_ORD:
Jakub Staszak3facc432013-06-06 20:18:46 +00003068 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +00003069 case FCmpInst::FCMP_UNO:
Jakub Staszak3facc432013-06-06 20:18:46 +00003070 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003071 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003072
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003073 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003074
Chris Lattner02446fc2010-01-04 07:37:31 +00003075 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003076
Chris Lattner02446fc2010-01-04 07:37:31 +00003077 // See if the FP constant is too large for the integer. For example,
3078 // comparing an i8 to 300.0.
3079 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003080
Chris Lattner02446fc2010-01-04 07:37:31 +00003081 if (!LHSUnsigned) {
3082 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
3083 // and large values.
Michael Gottesman4dfc2572013-06-27 21:58:19 +00003084 APFloat SMax(RHS.getSemantics());
Chris Lattner02446fc2010-01-04 07:37:31 +00003085 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
3086 APFloat::rmNearestTiesToEven);
3087 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
3088 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
3089 Pred == ICmpInst::ICMP_SLE)
Jakub Staszak3facc432013-06-06 20:18:46 +00003090 return ReplaceInstUsesWith(I, Builder->getTrue());
3091 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003092 }
3093 } else {
3094 // If the RHS value is > UnsignedMax, fold the comparison. This handles
3095 // +INF and large values.
Michael Gottesman4dfc2572013-06-27 21:58:19 +00003096 APFloat UMax(RHS.getSemantics());
Chris Lattner02446fc2010-01-04 07:37:31 +00003097 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
3098 APFloat::rmNearestTiesToEven);
3099 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
3100 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
3101 Pred == ICmpInst::ICMP_ULE)
Jakub Staszak3facc432013-06-06 20:18:46 +00003102 return ReplaceInstUsesWith(I, Builder->getTrue());
3103 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003104 }
3105 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003106
Chris Lattner02446fc2010-01-04 07:37:31 +00003107 if (!LHSUnsigned) {
3108 // See if the RHS value is < SignedMin.
Michael Gottesman4dfc2572013-06-27 21:58:19 +00003109 APFloat SMin(RHS.getSemantics());
Chris Lattner02446fc2010-01-04 07:37:31 +00003110 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
3111 APFloat::rmNearestTiesToEven);
3112 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
3113 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
3114 Pred == ICmpInst::ICMP_SGE)
Jakub Staszak3facc432013-06-06 20:18:46 +00003115 return ReplaceInstUsesWith(I, Builder->getTrue());
3116 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003117 }
Devang Patela2e0f6b2012-02-13 23:05:18 +00003118 } else {
3119 // See if the RHS value is < UnsignedMin.
Michael Gottesman4dfc2572013-06-27 21:58:19 +00003120 APFloat SMin(RHS.getSemantics());
Devang Patela2e0f6b2012-02-13 23:05:18 +00003121 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
3122 APFloat::rmNearestTiesToEven);
3123 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
3124 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
3125 Pred == ICmpInst::ICMP_UGE)
Jakub Staszak3facc432013-06-06 20:18:46 +00003126 return ReplaceInstUsesWith(I, Builder->getTrue());
3127 return ReplaceInstUsesWith(I, Builder->getFalse());
Devang Patela2e0f6b2012-02-13 23:05:18 +00003128 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003129 }
3130
3131 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
3132 // [0, UMAX], but it may still be fractional. See if it is fractional by
3133 // casting the FP value to the integer value and back, checking for equality.
3134 // Don't do this for zero, because -0.0 is not fractional.
3135 Constant *RHSInt = LHSUnsigned
3136 ? ConstantExpr::getFPToUI(RHSC, IntTy)
3137 : ConstantExpr::getFPToSI(RHSC, IntTy);
3138 if (!RHS.isZero()) {
3139 bool Equal = LHSUnsigned
3140 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
3141 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
3142 if (!Equal) {
3143 // If we had a comparison against a fractional value, we have to adjust
3144 // the compare predicate and sometimes the value. RHSC is rounded towards
3145 // zero at this point.
3146 switch (Pred) {
3147 default: llvm_unreachable("Unexpected integer comparison!");
3148 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Jakub Staszak3facc432013-06-06 20:18:46 +00003149 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +00003150 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Jakub Staszak3facc432013-06-06 20:18:46 +00003151 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003152 case ICmpInst::ICMP_ULE:
3153 // (float)int <= 4.4 --> int <= 4
3154 // (float)int <= -4.4 --> false
3155 if (RHS.isNegative())
Jakub Staszak3facc432013-06-06 20:18:46 +00003156 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003157 break;
3158 case ICmpInst::ICMP_SLE:
3159 // (float)int <= 4.4 --> int <= 4
3160 // (float)int <= -4.4 --> int < -4
3161 if (RHS.isNegative())
3162 Pred = ICmpInst::ICMP_SLT;
3163 break;
3164 case ICmpInst::ICMP_ULT:
3165 // (float)int < -4.4 --> false
3166 // (float)int < 4.4 --> int <= 4
3167 if (RHS.isNegative())
Jakub Staszak3facc432013-06-06 20:18:46 +00003168 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003169 Pred = ICmpInst::ICMP_ULE;
3170 break;
3171 case ICmpInst::ICMP_SLT:
3172 // (float)int < -4.4 --> int < -4
3173 // (float)int < 4.4 --> int <= 4
3174 if (!RHS.isNegative())
3175 Pred = ICmpInst::ICMP_SLE;
3176 break;
3177 case ICmpInst::ICMP_UGT:
3178 // (float)int > 4.4 --> int > 4
3179 // (float)int > -4.4 --> true
3180 if (RHS.isNegative())
Jakub Staszak3facc432013-06-06 20:18:46 +00003181 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +00003182 break;
3183 case ICmpInst::ICMP_SGT:
3184 // (float)int > 4.4 --> int > 4
3185 // (float)int > -4.4 --> int >= -4
3186 if (RHS.isNegative())
3187 Pred = ICmpInst::ICMP_SGE;
3188 break;
3189 case ICmpInst::ICMP_UGE:
3190 // (float)int >= -4.4 --> true
3191 // (float)int >= 4.4 --> int > 4
Bob Wilsonf12c95a2012-08-07 22:35:16 +00003192 if (RHS.isNegative())
Jakub Staszak3facc432013-06-06 20:18:46 +00003193 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +00003194 Pred = ICmpInst::ICMP_UGT;
3195 break;
3196 case ICmpInst::ICMP_SGE:
3197 // (float)int >= -4.4 --> int >= -4
3198 // (float)int >= 4.4 --> int > 4
3199 if (!RHS.isNegative())
3200 Pred = ICmpInst::ICMP_SGT;
3201 break;
3202 }
3203 }
3204 }
3205
3206 // Lower this FP comparison into an appropriate integer version of the
3207 // comparison.
3208 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
3209}
3210
3211Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
3212 bool Changed = false;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003213
Chris Lattner02446fc2010-01-04 07:37:31 +00003214 /// Orders the operands of the compare so that they are listed from most
3215 /// complex to least complex. This puts constants before unary operators,
3216 /// before binary operators.
3217 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
3218 I.swapOperands();
3219 Changed = true;
3220 }
3221
3222 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003223
Chris Lattner02446fc2010-01-04 07:37:31 +00003224 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
3225 return ReplaceInstUsesWith(I, V);
3226
3227 // Simplify 'fcmp pred X, X'
3228 if (Op0 == Op1) {
3229 switch (I.getPredicate()) {
3230 default: llvm_unreachable("Unknown predicate!");
3231 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
3232 case FCmpInst::FCMP_ULT: // True if unordered or less than
3233 case FCmpInst::FCMP_UGT: // True if unordered or greater than
3234 case FCmpInst::FCMP_UNE: // True if unordered or not equal
3235 // Canonicalize these to be 'fcmp uno %X, 0.0'.
3236 I.setPredicate(FCmpInst::FCMP_UNO);
3237 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3238 return &I;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003239
Chris Lattner02446fc2010-01-04 07:37:31 +00003240 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
3241 case FCmpInst::FCMP_OEQ: // True if ordered and equal
3242 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
3243 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
3244 // Canonicalize these to be 'fcmp ord %X, 0.0'.
3245 I.setPredicate(FCmpInst::FCMP_ORD);
3246 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3247 return &I;
3248 }
3249 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003250
Chris Lattner02446fc2010-01-04 07:37:31 +00003251 // Handle fcmp with constant RHS
3252 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3253 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3254 switch (LHSI->getOpcode()) {
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00003255 case Instruction::FPExt: {
3256 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
3257 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
3258 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
3259 if (!RHSF)
3260 break;
3261
3262 const fltSemantics *Sem;
3263 // FIXME: This shouldn't be here.
Dan Gohmance163392011-12-17 00:04:22 +00003264 if (LHSExt->getSrcTy()->isHalfTy())
3265 Sem = &APFloat::IEEEhalf;
3266 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00003267 Sem = &APFloat::IEEEsingle;
3268 else if (LHSExt->getSrcTy()->isDoubleTy())
3269 Sem = &APFloat::IEEEdouble;
3270 else if (LHSExt->getSrcTy()->isFP128Ty())
3271 Sem = &APFloat::IEEEquad;
3272 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
3273 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand3467b9f2012-10-30 12:33:18 +00003274 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
3275 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00003276 else
3277 break;
3278
3279 bool Lossy;
3280 APFloat F = RHSF->getValueAPF();
3281 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
3282
Jim Grosbachcbf676b2011-09-30 18:45:50 +00003283 // Avoid lossy conversions and denormals. Zero is a special case
3284 // that's OK to convert.
Jim Grosbach68e05fb2011-09-30 19:58:46 +00003285 APFloat Fabs = F;
3286 Fabs.clearSign();
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00003287 if (!Lossy &&
Jim Grosbach68e05fb2011-09-30 19:58:46 +00003288 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
3289 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbachcbf676b2011-09-30 18:45:50 +00003290
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00003291 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3292 ConstantFP::get(RHSC->getContext(), F));
3293 break;
3294 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003295 case Instruction::PHI:
3296 // Only fold fcmp into the PHI if the phi and fcmp are in the same
3297 // block. If in the same block, we're encouraging jump threading. If
3298 // not, we are just pessimizing the code by making an i1 phi.
3299 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00003300 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00003301 return NV;
3302 break;
3303 case Instruction::SIToFP:
3304 case Instruction::UIToFP:
3305 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
3306 return NV;
3307 break;
3308 case Instruction::Select: {
3309 // If either operand of the select is a constant, we can fold the
3310 // comparison into the select arms, which will cause one to be
3311 // constant folded and the select turned into a bitwise or.
3312 Value *Op1 = 0, *Op2 = 0;
3313 if (LHSI->hasOneUse()) {
3314 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3315 // Fold the known value into the constant operand.
3316 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3317 // Insert a new FCmp of the other select operand.
3318 Op2 = Builder->CreateFCmp(I.getPredicate(),
3319 LHSI->getOperand(2), RHSC, I.getName());
3320 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3321 // Fold the known value into the constant operand.
3322 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3323 // Insert a new FCmp of the other select operand.
3324 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
3325 RHSC, I.getName());
3326 }
3327 }
3328
3329 if (Op1)
3330 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3331 break;
3332 }
Benjamin Kramer0db50182011-03-31 10:12:15 +00003333 case Instruction::FSub: {
3334 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3335 Value *Op;
3336 if (match(LHSI, m_FNeg(m_Value(Op))))
3337 return new FCmpInst(I.getSwappedPredicate(), Op,
3338 ConstantExpr::getFNeg(RHSC));
3339 break;
3340 }
Dan Gohman39516a62010-02-24 06:46:09 +00003341 case Instruction::Load:
3342 if (GetElementPtrInst *GEP =
3343 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3344 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3345 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3346 !cast<LoadInst>(LHSI)->isVolatile())
3347 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3348 return Res;
3349 }
3350 break;
Benjamin Kramer00abcd32012-08-18 20:06:47 +00003351 case Instruction::Call: {
3352 CallInst *CI = cast<CallInst>(LHSI);
3353 LibFunc::Func Func;
3354 // Various optimization for fabs compared with zero.
Benjamin Kramera4b57172012-08-18 22:04:34 +00003355 if (RHSC->isNullValue() && CI->getCalledFunction() &&
Benjamin Kramer00abcd32012-08-18 20:06:47 +00003356 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3357 TLI->has(Func)) {
3358 if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3359 Func == LibFunc::fabsl) {
3360 switch (I.getPredicate()) {
3361 default: break;
3362 // fabs(x) < 0 --> false
3363 case FCmpInst::FCMP_OLT:
3364 return ReplaceInstUsesWith(I, Builder->getFalse());
3365 // fabs(x) > 0 --> x != 0
3366 case FCmpInst::FCMP_OGT:
3367 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3368 RHSC);
3369 // fabs(x) <= 0 --> x == 0
3370 case FCmpInst::FCMP_OLE:
3371 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3372 RHSC);
3373 // fabs(x) >= 0 --> !isnan(x)
3374 case FCmpInst::FCMP_OGE:
3375 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3376 RHSC);
3377 // fabs(x) == 0 --> x == 0
3378 // fabs(x) != 0 --> x != 0
3379 case FCmpInst::FCMP_OEQ:
3380 case FCmpInst::FCMP_UEQ:
3381 case FCmpInst::FCMP_ONE:
3382 case FCmpInst::FCMP_UNE:
3383 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3384 RHSC);
3385 }
3386 }
3387 }
3388 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003389 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003390 }
3391
Benjamin Kramer00e00d62011-03-31 10:46:03 +00003392 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00003393 Value *X, *Y;
3394 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramer00e00d62011-03-31 10:46:03 +00003395 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00003396
Benjamin Kramercd0274c2011-03-31 10:11:58 +00003397 // fcmp (fpext x), (fpext y) -> fcmp x, y
3398 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3399 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3400 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3401 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3402 RHSExt->getOperand(0));
3403
Chris Lattner02446fc2010-01-04 07:37:31 +00003404 return Changed ? &I : 0;
3405}