blob: 7085a55fd262b479a0b530c6af40204e4281d7e9 [file] [log] [blame]
Chris Lattner2188e402010-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 Friedman911e12f2011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2188e402010-01-04 07:37:31 +000016#include "llvm/Analysis/InstructionSimplify.h"
17#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000018#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000020#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000022#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner2188e402010-01-04 07:37:31 +000024using namespace llvm;
25using namespace PatternMatch;
26
Chris Lattner98457102011-02-10 05:23:05 +000027static ConstantInt *getOne(Constant *C) {
28 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
29}
30
Chris Lattner2188e402010-01-04 07:37:31 +000031static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
32 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
33}
34
35static bool HasAddOverflow(ConstantInt *Result,
36 ConstantInt *In1, ConstantInt *In2,
37 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000038 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000039 return Result->getValue().ult(In1->getValue());
Chris Lattnerb1a15122011-07-15 06:08:15 +000040
41 if (In2->isNegative())
42 return Result->getValue().sgt(In1->getValue());
43 return Result->getValue().slt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000044}
45
46/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
47/// overflowed for this type.
48static bool AddWithOverflow(Constant *&Result, Constant *In1,
49 Constant *In2, bool IsSigned = false) {
50 Result = ConstantExpr::getAdd(In1, In2);
51
Chris Lattner229907c2011-07-18 04:54:35 +000052 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000053 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
54 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
55 if (HasAddOverflow(ExtractElement(Result, Idx),
56 ExtractElement(In1, Idx),
57 ExtractElement(In2, Idx),
58 IsSigned))
59 return true;
60 }
61 return false;
62 }
63
64 return HasAddOverflow(cast<ConstantInt>(Result),
65 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
66 IsSigned);
67}
68
69static bool HasSubOverflow(ConstantInt *Result,
70 ConstantInt *In1, ConstantInt *In2,
71 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000072 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000073 return Result->getValue().ugt(In1->getValue());
Jim Grosbach129c52a2011-09-30 18:09:53 +000074
Chris Lattnerb1a15122011-07-15 06:08:15 +000075 if (In2->isNegative())
76 return Result->getValue().slt(In1->getValue());
77
78 return Result->getValue().sgt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000079}
80
81/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
82/// overflowed for this type.
83static bool SubWithOverflow(Constant *&Result, Constant *In1,
84 Constant *In2, bool IsSigned = false) {
85 Result = ConstantExpr::getSub(In1, In2);
86
Chris Lattner229907c2011-07-18 04:54:35 +000087 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000088 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
89 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
90 if (HasSubOverflow(ExtractElement(Result, Idx),
91 ExtractElement(In1, Idx),
92 ExtractElement(In2, Idx),
93 IsSigned))
94 return true;
95 }
96 return false;
97 }
98
99 return HasSubOverflow(cast<ConstantInt>(Result),
100 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
101 IsSigned);
102}
103
104/// isSignBitCheck - Given an exploded icmp instruction, return true if the
105/// comparison only checks the sign bit. If it only checks the sign bit, set
106/// TrueIfSigned if the result of the comparison is true when the input value is
107/// signed.
108static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
109 bool &TrueIfSigned) {
110 switch (pred) {
111 case ICmpInst::ICMP_SLT: // True if LHS s< 0
112 TrueIfSigned = true;
113 return RHS->isZero();
114 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
115 TrueIfSigned = true;
116 return RHS->isAllOnesValue();
117 case ICmpInst::ICMP_SGT: // True if LHS s> -1
118 TrueIfSigned = false;
119 return RHS->isAllOnesValue();
120 case ICmpInst::ICMP_UGT:
121 // True if LHS u> RHS and RHS == high-bit-mask - 1
122 TrueIfSigned = true;
Chris Lattnerb1a15122011-07-15 06:08:15 +0000123 return RHS->isMaxValue(true);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000124 case ICmpInst::ICMP_UGE:
Chris Lattner2188e402010-01-04 07:37:31 +0000125 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
126 TrueIfSigned = true;
127 return RHS->getValue().isSignBit();
128 default:
129 return false;
130 }
131}
132
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000133/// Returns true if the exploded icmp can be expressed as a signed comparison
134/// to zero and updates the predicate accordingly.
135/// The signedness of the comparison is preserved.
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000136static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
137 if (!ICmpInst::isSigned(pred))
138 return false;
139
140 if (RHS->isZero())
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000141 return ICmpInst::isRelational(pred);
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000142
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000143 if (RHS->isOne()) {
144 if (pred == ICmpInst::ICMP_SLT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000145 pred = ICmpInst::ICMP_SLE;
146 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000147 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000148 } else if (RHS->isAllOnesValue()) {
149 if (pred == ICmpInst::ICMP_SGT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000150 pred = ICmpInst::ICMP_SGE;
151 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000152 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000153 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000154
155 return false;
156}
157
Chris Lattner2188e402010-01-04 07:37:31 +0000158// isHighOnes - Return true if the constant is of the form 1+0+.
159// This is the same as lowones(~X).
160static bool isHighOnes(const ConstantInt *CI) {
161 return (~CI->getValue() + 1).isPowerOf2();
162}
163
Jim Grosbach129c52a2011-09-30 18:09:53 +0000164/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
Chris Lattner2188e402010-01-04 07:37:31 +0000165/// set of known zero and one bits, compute the maximum and minimum values that
166/// could have the specified known zero and known one bits, returning them in
167/// min/max.
168static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
169 const APInt& KnownOne,
170 APInt& Min, APInt& Max) {
171 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
172 KnownZero.getBitWidth() == Min.getBitWidth() &&
173 KnownZero.getBitWidth() == Max.getBitWidth() &&
174 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
175 APInt UnknownBits = ~(KnownZero|KnownOne);
176
177 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
178 // bit if it is unknown.
179 Min = KnownOne;
180 Max = KnownOne|UnknownBits;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000181
Chris Lattner2188e402010-01-04 07:37:31 +0000182 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000183 Min.setBit(Min.getBitWidth()-1);
184 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000185 }
186}
187
188// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
189// a set of known zero and one bits, compute the maximum and minimum values that
190// could have the specified known zero and known one bits, returning them in
191// min/max.
192static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
193 const APInt &KnownOne,
194 APInt &Min, APInt &Max) {
195 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
196 KnownZero.getBitWidth() == Min.getBitWidth() &&
197 KnownZero.getBitWidth() == Max.getBitWidth() &&
198 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
199 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000200
Chris Lattner2188e402010-01-04 07:37:31 +0000201 // The minimum value is when the unknown bits are all zeros.
202 Min = KnownOne;
203 // The maximum value is when the unknown bits are all ones.
204 Max = KnownOne|UnknownBits;
205}
206
207
208
209/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
210/// cmp pred (load (gep GV, ...)), cmpcst
211/// where GV is a global variable with a constant initializer. Try to simplify
212/// this into some simple computation that does not need the load. For example
213/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
214///
215/// If AndCst is non-null, then the loaded value is masked with that constant
216/// before doing the comparison. This handles cases like "A[i]&4 == 0".
217Instruction *InstCombiner::
218FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
219 CmpInst &ICI, ConstantInt *AndCst) {
Matt Arsenault5aeae182013-08-19 21:40:31 +0000220 // We need TD information to know the pointer size unless this is inbounds.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000221 if (!GEP->isInBounds() && DL == 0)
Matt Arsenault1de76772013-08-15 23:11:07 +0000222 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000223
Chris Lattnerfe741762012-01-31 02:55:06 +0000224 Constant *Init = GV->getInitializer();
225 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
226 return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000227
Chris Lattnerfe741762012-01-31 02:55:06 +0000228 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
229 if (ArrayElementCount > 1024) return 0; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000230
Chris Lattner2188e402010-01-04 07:37:31 +0000231 // There are many forms of this optimization we can handle, for now, just do
232 // the simple index into a single-dimensional array.
233 //
234 // Require: GEP GV, 0, i {{, constant indices}}
235 if (GEP->getNumOperands() < 3 ||
236 !isa<ConstantInt>(GEP->getOperand(1)) ||
237 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
238 isa<Constant>(GEP->getOperand(2)))
239 return 0;
240
241 // Check that indices after the variable are constants and in-range for the
242 // type they index. Collect the indices. This is typically for arrays of
243 // structs.
244 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000245
Chris Lattnerfe741762012-01-31 02:55:06 +0000246 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000247 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
248 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
249 if (Idx == 0) return 0; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000250
Chris Lattner2188e402010-01-04 07:37:31 +0000251 uint64_t IdxVal = Idx->getZExtValue();
252 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000253
Chris Lattner229907c2011-07-18 04:54:35 +0000254 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000255 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000256 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Chris Lattner2188e402010-01-04 07:37:31 +0000257 if (IdxVal >= ATy->getNumElements()) return 0;
258 EltTy = ATy->getElementType();
259 } else {
260 return 0; // Unknown type.
261 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000262
Chris Lattner2188e402010-01-04 07:37:31 +0000263 LaterIndices.push_back(IdxVal);
264 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000265
Chris Lattner2188e402010-01-04 07:37:31 +0000266 enum { Overdefined = -3, Undefined = -2 };
267
268 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000269
Chris Lattner2188e402010-01-04 07:37:31 +0000270 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
271 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
272 // and 87 is the second (and last) index. FirstTrueElement is -2 when
273 // undefined, otherwise set to the first true element. SecondTrueElement is
274 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
275 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
276
277 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
278 // form "i != 47 & i != 87". Same state transitions as for true elements.
279 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000280
Chris Lattner2188e402010-01-04 07:37:31 +0000281 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
282 /// define a state machine that triggers for ranges of values that the index
283 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
284 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
285 /// index in the range (inclusive). We use -2 for undefined here because we
286 /// use relative comparisons and don't want 0-1 to match -1.
287 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000288
Chris Lattner2188e402010-01-04 07:37:31 +0000289 // MagicBitvector - This is a magic bitvector where we set a bit if the
290 // comparison is true for element 'i'. If there are 64 elements or less in
291 // the array, this will fully represent all the comparison results.
292 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000293
294
Chris Lattner2188e402010-01-04 07:37:31 +0000295 // Scan the array and see if one of our patterns matches.
296 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000297 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
298 Constant *Elt = Init->getAggregateElement(i);
299 if (Elt == 0) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000300
Chris Lattner2188e402010-01-04 07:37:31 +0000301 // If this is indexing an array of structures, get the structure element.
302 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000303 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000304
Chris Lattner2188e402010-01-04 07:37:31 +0000305 // If the element is masked, handle it.
306 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000307
Chris Lattner2188e402010-01-04 07:37:31 +0000308 // Find out if the comparison would be true or false for the i'th element.
309 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000310 CompareRHS, DL, TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000311 // If the result is undef for this element, ignore it.
312 if (isa<UndefValue>(C)) {
313 // Extend range state machines to cover this element in case there is an
314 // undef in the middle of the range.
315 if (TrueRangeEnd == (int)i-1)
316 TrueRangeEnd = i;
317 if (FalseRangeEnd == (int)i-1)
318 FalseRangeEnd = i;
319 continue;
320 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000321
Chris Lattner2188e402010-01-04 07:37:31 +0000322 // If we can't compute the result for any of the elements, we have to give
323 // up evaluating the entire conditional.
324 if (!isa<ConstantInt>(C)) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000325
Chris Lattner2188e402010-01-04 07:37:31 +0000326 // Otherwise, we know if the comparison is true or false for this element,
327 // update our state machines.
328 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000329
Chris Lattner2188e402010-01-04 07:37:31 +0000330 // State machine for single/double/range index comparison.
331 if (IsTrueForElt) {
332 // Update the TrueElement state machine.
333 if (FirstTrueElement == Undefined)
334 FirstTrueElement = TrueRangeEnd = i; // First true element.
335 else {
336 // Update double-compare state machine.
337 if (SecondTrueElement == Undefined)
338 SecondTrueElement = i;
339 else
340 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000341
Chris Lattner2188e402010-01-04 07:37:31 +0000342 // Update range state machine.
343 if (TrueRangeEnd == (int)i-1)
344 TrueRangeEnd = i;
345 else
346 TrueRangeEnd = Overdefined;
347 }
348 } else {
349 // Update the FalseElement state machine.
350 if (FirstFalseElement == Undefined)
351 FirstFalseElement = FalseRangeEnd = i; // First false element.
352 else {
353 // Update double-compare state machine.
354 if (SecondFalseElement == Undefined)
355 SecondFalseElement = i;
356 else
357 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000358
Chris Lattner2188e402010-01-04 07:37:31 +0000359 // Update range state machine.
360 if (FalseRangeEnd == (int)i-1)
361 FalseRangeEnd = i;
362 else
363 FalseRangeEnd = Overdefined;
364 }
365 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000366
367
Chris Lattner2188e402010-01-04 07:37:31 +0000368 // If this element is in range, update our magic bitvector.
369 if (i < 64 && IsTrueForElt)
370 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000371
Chris Lattner2188e402010-01-04 07:37:31 +0000372 // If all of our states become overdefined, bail out early. Since the
373 // predicate is expensive, only check it every 8 elements. This is only
374 // really useful for really huge arrays.
375 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
376 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
377 FalseRangeEnd == Overdefined)
378 return 0;
379 }
380
381 // Now that we've scanned the entire array, emit our new comparison(s). We
382 // order the state machines in complexity of the generated code.
383 Value *Idx = GEP->getOperand(2);
384
Matt Arsenault5aeae182013-08-19 21:40:31 +0000385 // If the index is larger than the pointer size of the target, truncate the
386 // index down like the GEP would do implicitly. We don't have to do this for
387 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000388 if (!GEP->isInBounds()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000389 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000390 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
391 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
392 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
393 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000394
Chris Lattner2188e402010-01-04 07:37:31 +0000395 // If the comparison is only true for one or two elements, emit direct
396 // comparisons.
397 if (SecondTrueElement != Overdefined) {
398 // None true -> false.
399 if (FirstTrueElement == Undefined)
Jakub Staszakbddea112013-06-06 20:18:46 +0000400 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000401
Chris Lattner2188e402010-01-04 07:37:31 +0000402 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000403
Chris Lattner2188e402010-01-04 07:37:31 +0000404 // True for one element -> 'i == 47'.
405 if (SecondTrueElement == Undefined)
406 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000407
Chris Lattner2188e402010-01-04 07:37:31 +0000408 // True for two elements -> 'i == 47 | i == 72'.
409 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
410 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
411 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
412 return BinaryOperator::CreateOr(C1, C2);
413 }
414
415 // If the comparison is only false for one or two elements, emit direct
416 // comparisons.
417 if (SecondFalseElement != Overdefined) {
418 // None false -> true.
419 if (FirstFalseElement == Undefined)
Jakub Staszakbddea112013-06-06 20:18:46 +0000420 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000421
Chris Lattner2188e402010-01-04 07:37:31 +0000422 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
423
424 // False for one element -> 'i != 47'.
425 if (SecondFalseElement == Undefined)
426 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000427
Chris Lattner2188e402010-01-04 07:37:31 +0000428 // False for two elements -> 'i != 47 & i != 72'.
429 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
430 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
431 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
432 return BinaryOperator::CreateAnd(C1, C2);
433 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000434
Chris Lattner2188e402010-01-04 07:37:31 +0000435 // If the comparison can be replaced with a range comparison for the elements
436 // where it is true, emit the range check.
437 if (TrueRangeEnd != Overdefined) {
438 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000439
Chris Lattner2188e402010-01-04 07:37:31 +0000440 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
441 if (FirstTrueElement) {
442 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
443 Idx = Builder->CreateAdd(Idx, Offs);
444 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000445
Chris Lattner2188e402010-01-04 07:37:31 +0000446 Value *End = ConstantInt::get(Idx->getType(),
447 TrueRangeEnd-FirstTrueElement+1);
448 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
449 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000450
Chris Lattner2188e402010-01-04 07:37:31 +0000451 // False range check.
452 if (FalseRangeEnd != Overdefined) {
453 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
454 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
455 if (FirstFalseElement) {
456 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
457 Idx = Builder->CreateAdd(Idx, Offs);
458 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000459
Chris Lattner2188e402010-01-04 07:37:31 +0000460 Value *End = ConstantInt::get(Idx->getType(),
461 FalseRangeEnd-FirstFalseElement);
462 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
463 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000464
465
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000466 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000467 // of this load, replace it with computation that does:
468 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000469 {
470 Type *Ty = 0;
471
472 // Look for an appropriate type:
473 // - The type of Idx if the magic fits
474 // - The smallest fitting legal type if we have a DataLayout
475 // - Default to i32
476 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
477 Ty = Idx->getType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000478 else if (DL)
479 Ty = DL->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000480 else if (ArrayElementCount <= 32)
Chris Lattner2188e402010-01-04 07:37:31 +0000481 Ty = Type::getInt32Ty(Init->getContext());
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000482
483 if (Ty != 0) {
484 Value *V = Builder->CreateIntCast(Idx, Ty, false);
485 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
486 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
487 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
488 }
Chris Lattner2188e402010-01-04 07:37:31 +0000489 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000490
Chris Lattner2188e402010-01-04 07:37:31 +0000491 return 0;
492}
493
494
495/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
496/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
497/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
498/// be complex, and scales are involved. The above expression would also be
499/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
500/// This later form is less amenable to optimization though, and we are allowed
501/// to generate the first by knowing that pointer arithmetic doesn't overflow.
502///
503/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000504///
Eli Friedman1754a252011-05-18 23:11:30 +0000505static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000506 const DataLayout &DL = *IC.getDataLayout();
Chris Lattner2188e402010-01-04 07:37:31 +0000507 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000508
Chris Lattner2188e402010-01-04 07:37:31 +0000509 // Check to see if this gep only has a single variable index. If so, and if
510 // any constant indices are a multiple of its scale, then we can compute this
511 // in terms of the scale of the variable index. For example, if the GEP
512 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
513 // because the expression will cross zero at the same point.
514 unsigned i, e = GEP->getNumOperands();
515 int64_t Offset = 0;
516 for (i = 1; i != e; ++i, ++GTI) {
517 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
518 // Compute the aggregate offset of constant indices.
519 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000520
Chris Lattner2188e402010-01-04 07:37:31 +0000521 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000522 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000523 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000524 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000525 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000526 Offset += Size*CI->getSExtValue();
527 }
528 } else {
529 // Found our variable index.
530 break;
531 }
532 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000533
Chris Lattner2188e402010-01-04 07:37:31 +0000534 // If there are no variable indices, we must have a constant offset, just
535 // evaluate it the general way.
536 if (i == e) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000537
Chris Lattner2188e402010-01-04 07:37:31 +0000538 Value *VariableIdx = GEP->getOperand(i);
539 // Determine the scale factor of the variable element. For example, this is
540 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000541 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000542
Chris Lattner2188e402010-01-04 07:37:31 +0000543 // Verify that there are no other variable indices. If so, emit the hard way.
544 for (++i, ++GTI; i != e; ++i, ++GTI) {
545 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
546 if (!CI) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000547
Chris Lattner2188e402010-01-04 07:37:31 +0000548 // Compute the aggregate offset of constant indices.
549 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000550
Chris Lattner2188e402010-01-04 07:37:31 +0000551 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000552 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000553 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000554 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000555 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000556 Offset += Size*CI->getSExtValue();
557 }
558 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000559
Matt Arsenault745101d2013-08-21 19:53:10 +0000560
561
Chris Lattner2188e402010-01-04 07:37:31 +0000562 // Okay, we know we have a single variable index, which must be a
563 // pointer/array/vector index. If there is no offset, life is simple, return
564 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000565 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000566 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000567 if (Offset == 0) {
568 // Cast to intptrty in case a truncation occurs. If an extension is needed,
569 // we don't need to bother extending: the extension won't affect where the
570 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000571 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000572 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
573 }
Chris Lattner2188e402010-01-04 07:37:31 +0000574 return VariableIdx;
575 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000576
Chris Lattner2188e402010-01-04 07:37:31 +0000577 // Otherwise, there is an index. The computation we will do will be modulo
578 // the pointer size, so get it.
579 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000580
Chris Lattner2188e402010-01-04 07:37:31 +0000581 Offset &= PtrSizeMask;
582 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000583
Chris Lattner2188e402010-01-04 07:37:31 +0000584 // To do this transformation, any constant index must be a multiple of the
585 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
586 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
587 // multiple of the variable scale.
588 int64_t NewOffs = Offset / (int64_t)VariableScale;
589 if (Offset != NewOffs*(int64_t)VariableScale)
590 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000591
Chris Lattner2188e402010-01-04 07:37:31 +0000592 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000593 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000594 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
595 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000596 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000597 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000598}
599
600/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
601/// else. At this point we know that the GEP is on the LHS of the comparison.
602Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
603 ICmpInst::Predicate Cond,
604 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000605 // Don't transform signed compares of GEPs into index compares. Even if the
606 // GEP is inbounds, the final add of the base pointer can have signed overflow
607 // and would change the result of the icmp.
608 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000609 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000610 if (ICmpInst::isSigned(Cond))
611 return 0;
612
Chris Lattner2188e402010-01-04 07:37:31 +0000613 // Look through bitcasts.
614 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
615 RHS = BCI->getOperand(0);
616
617 Value *PtrBase = GEPLHS->getOperand(0);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000618 if (DL && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000619 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
620 // This transformation (ignoring the base and scales) is valid because we
621 // know pointers can't overflow since the gep is inbounds. See if we can
622 // output an optimized form.
Eli Friedman1754a252011-05-18 23:11:30 +0000623 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000624
Chris Lattner2188e402010-01-04 07:37:31 +0000625 // If not, synthesize the offset the hard way.
626 if (Offset == 0)
627 Offset = EmitGEPOffset(GEPLHS);
628 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
629 Constant::getNullValue(Offset->getType()));
630 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
631 // If the base pointers are different, but the indices are the same, just
632 // compare the base pointer.
633 if (PtrBase != GEPRHS->getOperand(0)) {
634 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
635 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
636 GEPRHS->getOperand(0)->getType();
637 if (IndicesTheSame)
638 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
639 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
640 IndicesTheSame = false;
641 break;
642 }
643
644 // If all indices are the same, just compare the base pointers.
645 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000646 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000647
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000648 // If we're comparing GEPs with two base pointers that only differ in type
649 // and both GEPs have only constant indices or just one use, then fold
650 // the compare with the adjusted indices.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000651 if (DL && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000652 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
653 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
654 PtrBase->stripPointerCasts() ==
655 GEPRHS->getOperand(0)->stripPointerCasts()) {
656 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
657 EmitGEPOffset(GEPLHS),
658 EmitGEPOffset(GEPRHS));
659 return ReplaceInstUsesWith(I, Cmp);
660 }
661
Chris Lattner2188e402010-01-04 07:37:31 +0000662 // Otherwise, the base pointers are different and the indices are
663 // different, bail out.
664 return 0;
665 }
666
667 // If one of the GEPs has all zero indices, recurse.
668 bool AllZeros = true;
669 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
670 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
671 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
672 AllZeros = false;
673 break;
674 }
675 if (AllZeros)
676 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +0000677 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +0000678
679 // If the other GEP has all zero indices, recurse.
680 AllZeros = true;
681 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
682 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
683 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
684 AllZeros = false;
685 break;
686 }
687 if (AllZeros)
688 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
689
Stuart Hastings66a82b92011-05-14 05:55:10 +0000690 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +0000691 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
692 // If the GEPs only differ by one index, compare it.
693 unsigned NumDifferences = 0; // Keep track of # differences.
694 unsigned DiffOperand = 0; // The operand that differs.
695 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
696 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
697 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
698 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
699 // Irreconcilable differences.
700 NumDifferences = 2;
701 break;
702 } else {
703 if (NumDifferences++) break;
704 DiffOperand = i;
705 }
706 }
707
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +0000708 if (NumDifferences == 0) // SAME GEP?
709 return ReplaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +0000710 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +0000711
Stuart Hastings66a82b92011-05-14 05:55:10 +0000712 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +0000713 Value *LHSV = GEPLHS->getOperand(DiffOperand);
714 Value *RHSV = GEPRHS->getOperand(DiffOperand);
715 // Make sure we do a signed comparison here.
716 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
717 }
718 }
719
720 // Only lower this if the icmp is the only user of the GEP or if we expect
721 // the result to fold to a constant!
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000722 if (DL &&
Stuart Hastings66a82b92011-05-14 05:55:10 +0000723 GEPsInBounds &&
Chris Lattner2188e402010-01-04 07:37:31 +0000724 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
725 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
726 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
727 Value *L = EmitGEPOffset(GEPLHS);
728 Value *R = EmitGEPOffset(GEPRHS);
729 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
730 }
731 }
732 return 0;
733}
734
735/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
Benjamin Kramer0e2d1622013-09-20 22:12:42 +0000736Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
Chris Lattner2188e402010-01-04 07:37:31 +0000737 Value *X, ConstantInt *CI,
Benjamin Kramer0e2d1622013-09-20 22:12:42 +0000738 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +0000739 // If we have X+0, exit early (simplifying logic below) and let it get folded
740 // elsewhere. icmp X+0, X -> icmp X, X
741 if (CI->isZero()) {
742 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
743 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
744 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000745
Chris Lattner2188e402010-01-04 07:37:31 +0000746 // (X+4) == X -> false.
747 if (Pred == ICmpInst::ICMP_EQ)
Jakub Staszakbddea112013-06-06 20:18:46 +0000748 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +0000749
750 // (X+4) != X -> true.
751 if (Pred == ICmpInst::ICMP_NE)
Jakub Staszakbddea112013-06-06 20:18:46 +0000752 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +0000753
Chris Lattner2188e402010-01-04 07:37:31 +0000754 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000755 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +0000756 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000757
Chris Lattner8c92b572010-01-08 17:48:19 +0000758 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +0000759 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
760 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
761 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +0000762 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +0000763 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +0000764 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
765 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000766
Chris Lattner2188e402010-01-04 07:37:31 +0000767 // (X+1) >u X --> X <u (0-1) --> X != 255
768 // (X+2) >u X --> X <u (0-2) --> X <u 254
769 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +0000770 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +0000771 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000772
Chris Lattner2188e402010-01-04 07:37:31 +0000773 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
774 ConstantInt *SMax = ConstantInt::get(X->getContext(),
775 APInt::getSignedMaxValue(BitWidth));
776
777 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
778 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
779 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
780 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
781 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
782 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +0000783 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +0000784 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000785
Chris Lattner2188e402010-01-04 07:37:31 +0000786 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
787 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
788 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
789 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
790 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
791 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +0000792
Chris Lattner2188e402010-01-04 07:37:31 +0000793 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +0000794 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000795 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
796}
797
798/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
799/// and CmpRHS are both known to be integer constants.
800Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
801 ConstantInt *DivRHS) {
802 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
803 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000804
805 // FIXME: If the operand types don't match the type of the divide
Chris Lattner2188e402010-01-04 07:37:31 +0000806 // then don't attempt this transform. The code below doesn't have the
807 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach129c52a2011-09-30 18:09:53 +0000808 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner2188e402010-01-04 07:37:31 +0000809 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach129c52a2011-09-30 18:09:53 +0000810 // (x /u C1) <u C2. Simply casting the operands and result won't
811 // work. :( The if statement below tests that condition and bails
Chris Lattner98457102011-02-10 05:23:05 +0000812 // if it finds it.
Chris Lattner2188e402010-01-04 07:37:31 +0000813 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
814 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
815 return 0;
816 if (DivRHS->isZero())
817 return 0; // The ProdOV computation fails on divide by zero.
818 if (DivIsSigned && DivRHS->isAllOnesValue())
819 return 0; // The overflow computation also screws up here
Chris Lattner43273af2011-02-13 08:07:21 +0000820 if (DivRHS->isOne()) {
821 // This eliminates some funny cases with INT_MIN.
822 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
823 return &ICI;
824 }
Chris Lattner2188e402010-01-04 07:37:31 +0000825
826 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach129c52a2011-09-30 18:09:53 +0000827 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
828 // C2 (CI). By solving for X we can turn this into a range check
829 // instead of computing a divide.
Chris Lattner2188e402010-01-04 07:37:31 +0000830 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
831
832 // Determine if the product overflows by seeing if the product is
833 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach129c52a2011-09-30 18:09:53 +0000834 // as in the LHS instruction that we're folding.
Chris Lattner2188e402010-01-04 07:37:31 +0000835 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
836 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
837
838 // Get the ICmp opcode
839 ICmpInst::Predicate Pred = ICI.getPredicate();
840
Chris Lattner98457102011-02-10 05:23:05 +0000841 /// If the division is known to be exact, then there is no remainder from the
842 /// divide, so the covered range size is unit, otherwise it is the divisor.
843 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000844
Chris Lattner2188e402010-01-04 07:37:31 +0000845 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach129c52a2011-09-30 18:09:53 +0000846 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner2188e402010-01-04 07:37:31 +0000847 // Compute this interval based on the constants involved and the signedness of
848 // the compare/divide. This computes a half-open interval, keeping track of
849 // whether either value in the interval overflows. After analysis each
850 // overflow variable is set to 0 if it's corresponding bound variable is valid
851 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
852 int LoOverflow = 0, HiOverflow = 0;
853 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner98457102011-02-10 05:23:05 +0000854
Chris Lattner2188e402010-01-04 07:37:31 +0000855 if (!DivIsSigned) { // udiv
856 // e.g. X/5 op 3 --> [15, 20)
857 LoBound = Prod;
858 HiOverflow = LoOverflow = ProdOV;
Chris Lattner98457102011-02-10 05:23:05 +0000859 if (!HiOverflow) {
860 // If this is not an exact divide, then many values in the range collapse
861 // to the same result value.
862 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
863 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000864
Chris Lattner2188e402010-01-04 07:37:31 +0000865 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
866 if (CmpRHSV == 0) { // (X / pos) op 0
867 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner98457102011-02-10 05:23:05 +0000868 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
869 HiBound = RangeSize;
Chris Lattner2188e402010-01-04 07:37:31 +0000870 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
871 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
872 HiOverflow = LoOverflow = ProdOV;
873 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000874 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +0000875 } else { // (X / pos) op neg
876 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
877 HiBound = AddOne(Prod);
878 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
879 if (!LoOverflow) {
Chris Lattner98457102011-02-10 05:23:05 +0000880 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000881 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattner98457102011-02-10 05:23:05 +0000882 }
Chris Lattner2188e402010-01-04 07:37:31 +0000883 }
Chris Lattnerb1a15122011-07-15 06:08:15 +0000884 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattner98457102011-02-10 05:23:05 +0000885 if (DivI->isExact())
886 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000887 if (CmpRHSV == 0) { // (X / neg) op 0
888 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner98457102011-02-10 05:23:05 +0000889 LoBound = AddOne(RangeSize);
890 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000891 if (HiBound == DivRHS) { // -INTMIN = INTMIN
892 HiOverflow = 1; // [INTMIN+1, overflow)
893 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
894 }
895 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
896 // e.g. X/-5 op 3 --> [-19, -14)
897 HiBound = AddOne(Prod);
898 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
899 if (!LoOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000900 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner2188e402010-01-04 07:37:31 +0000901 } else { // (X / neg) op neg
902 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
903 LoOverflow = HiOverflow = ProdOV;
904 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000905 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +0000906 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000907
Chris Lattner2188e402010-01-04 07:37:31 +0000908 // Dividing by a negative swaps the condition. LT <-> GT
909 Pred = ICmpInst::getSwappedPredicate(Pred);
910 }
911
912 Value *X = DivI->getOperand(0);
913 switch (Pred) {
914 default: llvm_unreachable("Unhandled icmp opcode!");
915 case ICmpInst::ICMP_EQ:
916 if (LoOverflow && HiOverflow)
Jakub Staszakbddea112013-06-06 20:18:46 +0000917 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner067459c2010-03-05 08:46:26 +0000918 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000919 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
920 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000921 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000922 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
923 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +0000924 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
925 DivIsSigned, true));
Chris Lattner2188e402010-01-04 07:37:31 +0000926 case ICmpInst::ICMP_NE:
927 if (LoOverflow && HiOverflow)
Jakub Staszakbddea112013-06-06 20:18:46 +0000928 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner067459c2010-03-05 08:46:26 +0000929 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000930 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
931 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000932 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000933 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
934 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000935 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
936 DivIsSigned, false));
Chris Lattner2188e402010-01-04 07:37:31 +0000937 case ICmpInst::ICMP_ULT:
938 case ICmpInst::ICMP_SLT:
939 if (LoOverflow == +1) // Low bound is greater than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000940 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +0000941 if (LoOverflow == -1) // Low bound is less than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000942 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +0000943 return new ICmpInst(Pred, X, LoBound);
944 case ICmpInst::ICMP_UGT:
945 case ICmpInst::ICMP_SGT:
946 if (HiOverflow == +1) // High bound greater than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000947 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner98457102011-02-10 05:23:05 +0000948 if (HiOverflow == -1) // High bound less than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000949 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +0000950 if (Pred == ICmpInst::ICMP_UGT)
951 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +0000952 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner2188e402010-01-04 07:37:31 +0000953 }
954}
955
Chris Lattnerd369f572011-02-13 07:43:07 +0000956/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
957Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
958 ConstantInt *ShAmt) {
Chris Lattnerd369f572011-02-13 07:43:07 +0000959 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000960
Chris Lattnerd369f572011-02-13 07:43:07 +0000961 // Check that the shift amount is in range. If not, don't perform
962 // undefined shifts. When the shift is visited it will be
963 // simplified.
964 uint32_t TypeBits = CmpRHSV.getBitWidth();
965 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner43273af2011-02-13 08:07:21 +0000966 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Chris Lattnerd369f572011-02-13 07:43:07 +0000967 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000968
Chris Lattner43273af2011-02-13 08:07:21 +0000969 if (!ICI.isEquality()) {
970 // If we have an unsigned comparison and an ashr, we can't simplify this.
971 // Similarly for signed comparisons with lshr.
972 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
973 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000974
Eli Friedman865866e2011-05-25 23:26:20 +0000975 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
976 // by a power of 2. Since we already have logic to simplify these,
977 // transform to div and then simplify the resultant comparison.
Chris Lattner43273af2011-02-13 08:07:21 +0000978 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedman865866e2011-05-25 23:26:20 +0000979 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Chris Lattner43273af2011-02-13 08:07:21 +0000980 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000981
Chris Lattner43273af2011-02-13 08:07:21 +0000982 // Revisit the shift (to delete it).
983 Worklist.Add(Shr);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000984
Chris Lattner43273af2011-02-13 08:07:21 +0000985 Constant *DivCst =
986 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000987
Chris Lattner43273af2011-02-13 08:07:21 +0000988 Value *Tmp =
989 Shr->getOpcode() == Instruction::AShr ?
990 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
991 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000992
Chris Lattner43273af2011-02-13 08:07:21 +0000993 ICI.setOperand(0, Tmp);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000994
Chris Lattner43273af2011-02-13 08:07:21 +0000995 // If the builder folded the binop, just return it.
996 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
997 if (TheDiv == 0)
998 return &ICI;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000999
Chris Lattner43273af2011-02-13 08:07:21 +00001000 // Otherwise, fold this div/compare.
1001 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1002 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001003
Chris Lattner43273af2011-02-13 08:07:21 +00001004 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1005 assert(Res && "This div/cst should have folded!");
1006 return Res;
1007 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001008
1009
Chris Lattnerd369f572011-02-13 07:43:07 +00001010 // If we are comparing against bits always shifted out, the
1011 // comparison cannot succeed.
1012 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszakbddea112013-06-06 20:18:46 +00001013 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattnerd369f572011-02-13 07:43:07 +00001014 if (Shr->getOpcode() == Instruction::LShr)
1015 Comp = Comp.lshr(ShAmtVal);
1016 else
1017 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001018
Chris Lattnerd369f572011-02-13 07:43:07 +00001019 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1020 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001021 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattnerd369f572011-02-13 07:43:07 +00001022 return ReplaceInstUsesWith(ICI, Cst);
1023 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001024
Chris Lattnerd369f572011-02-13 07:43:07 +00001025 // Otherwise, check to see if the bits shifted out are known to be zero.
1026 // If so, we can compare against the unshifted value:
1027 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattner9bd7fdf2011-02-13 18:30:09 +00001028 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattnerd369f572011-02-13 07:43:07 +00001029 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001030
Chris Lattnerd369f572011-02-13 07:43:07 +00001031 if (Shr->hasOneUse()) {
1032 // Otherwise strength reduce the shift into an and.
1033 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszakbddea112013-06-06 20:18:46 +00001034 Constant *Mask = Builder->getInt(Val);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001035
Chris Lattnerd369f572011-02-13 07:43:07 +00001036 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1037 Mask, Shr->getName()+".mask");
1038 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1039 }
1040 return 0;
1041}
1042
Chris Lattner2188e402010-01-04 07:37:31 +00001043
1044/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1045///
1046Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1047 Instruction *LHSI,
1048 ConstantInt *RHS) {
1049 const APInt &RHSV = RHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001050
Chris Lattner2188e402010-01-04 07:37:31 +00001051 switch (LHSI->getOpcode()) {
1052 case Instruction::Trunc:
1053 if (ICI.isEquality() && LHSI->hasOneUse()) {
1054 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1055 // of the high bits truncated out of x are known.
1056 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1057 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner2188e402010-01-04 07:37:31 +00001058 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001059 ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001060
Chris Lattner2188e402010-01-04 07:37:31 +00001061 // If all the high bits are known, we can do this xform.
1062 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1063 // Pull in the high bits from known-ones set.
Jay Foad583abbc2010-12-07 08:25:19 +00001064 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedmane0a64d82012-05-11 01:32:59 +00001065 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner2188e402010-01-04 07:37:31 +00001066 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001067 Builder->getInt(NewRHS));
Chris Lattner2188e402010-01-04 07:37:31 +00001068 }
1069 }
1070 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001071
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001072 case Instruction::Xor: // (icmp pred (xor X, XorCst), CI)
1073 if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001074 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1075 // fold the xor.
1076 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1077 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1078 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001079
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001080 // If the sign bit of the XorCst is not set, there is no change to
Chris Lattner2188e402010-01-04 07:37:31 +00001081 // the operation, just stop using the Xor.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001082 if (!XorCst->isNegative()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001083 ICI.setOperand(0, CompareVal);
1084 Worklist.Add(LHSI);
1085 return &ICI;
1086 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001087
Chris Lattner2188e402010-01-04 07:37:31 +00001088 // Was the old condition true if the operand is positive?
1089 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001090
Chris Lattner2188e402010-01-04 07:37:31 +00001091 // If so, the new one isn't.
1092 isTrueIfPositive ^= true;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001093
Chris Lattner2188e402010-01-04 07:37:31 +00001094 if (isTrueIfPositive)
1095 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1096 SubOne(RHS));
1097 else
1098 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1099 AddOne(RHS));
1100 }
1101
1102 if (LHSI->hasOneUse()) {
1103 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001104 if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1105 const APInt &SignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001106 ICmpInst::Predicate Pred = ICI.isSigned()
1107 ? ICI.getUnsignedPredicate()
1108 : ICI.getSignedPredicate();
1109 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001110 Builder->getInt(RHSV ^ SignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001111 }
1112
1113 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001114 if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1115 const APInt &NotSignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001116 ICmpInst::Predicate Pred = ICI.isSigned()
1117 ? ICI.getUnsignedPredicate()
1118 : ICI.getSignedPredicate();
1119 Pred = ICI.getSwappedPredicate(Pred);
1120 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001121 Builder->getInt(RHSV ^ NotSignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001122 }
1123 }
David Majnemer72d76272013-07-09 09:20:58 +00001124
1125 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1126 // iff -C is a power of 2
1127 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001128 XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1129 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
David Majnemer72d76272013-07-09 09:20:58 +00001130
1131 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1132 // iff -C is a power of 2
1133 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001134 XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1135 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001136 }
1137 break;
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001138 case Instruction::And: // (icmp pred (and X, AndCst), RHS)
Chris Lattner2188e402010-01-04 07:37:31 +00001139 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1140 LHSI->getOperand(0)->hasOneUse()) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001141 ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001142
Chris Lattner2188e402010-01-04 07:37:31 +00001143 // If the LHS is an AND of a truncating cast, we can widen the
1144 // and/compare to be the input width without changing the value
1145 // produced, eliminating a cast.
1146 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1147 // We can do this transformation if either the AND constant does not
Jim Grosbach129c52a2011-09-30 18:09:53 +00001148 // have its sign bit set or if it is an equality comparison.
Chris Lattner2188e402010-01-04 07:37:31 +00001149 // Extending a relational comparison when we're checking the sign
1150 // bit would not work.
Benjamin Kramer35159c12011-06-12 22:47:53 +00001151 if (ICI.isEquality() ||
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001152 (!AndCst->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer35159c12011-06-12 22:47:53 +00001153 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001154 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001155 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
Benjamin Kramer35159c12011-06-12 22:47:53 +00001156 NewAnd->takeName(LHSI);
Chris Lattner2188e402010-01-04 07:37:31 +00001157 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer35159c12011-06-12 22:47:53 +00001158 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner2188e402010-01-04 07:37:31 +00001159 }
1160 }
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001161
1162 // If the LHS is an AND of a zext, and we have an equality compare, we can
1163 // shrink the and/compare to the smaller type, eliminating the cast.
1164 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattner229907c2011-07-18 04:54:35 +00001165 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001166 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1167 // should fold the icmp to true/false in that case.
1168 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1169 Value *NewAnd =
1170 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001171 ConstantExpr::getTrunc(AndCst, Ty));
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001172 NewAnd->takeName(LHSI);
1173 return new ICmpInst(ICI.getPredicate(), NewAnd,
1174 ConstantExpr::getTrunc(RHS, Ty));
1175 }
1176 }
1177
Chris Lattner2188e402010-01-04 07:37:31 +00001178 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1179 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1180 // happens a LOT in code produced by the C front-end, for bitfield
1181 // access.
1182 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1183 if (Shift && !Shift->isShift())
1184 Shift = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001185
Chris Lattner2188e402010-01-04 07:37:31 +00001186 ConstantInt *ShAmt;
1187 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001188
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001189 // This seemingly simple opportunity to fold away a shift turns out to
1190 // be rather complicated. See PR17827
1191 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
Chris Lattner2188e402010-01-04 07:37:31 +00001192 if (ShAmt) {
Kay Tiong Khoo5389f742013-12-02 18:43:59 +00001193 bool CanFold = false;
1194 unsigned ShiftOpcode = Shift->getOpcode();
1195 if (ShiftOpcode == Instruction::AShr) {
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001196 // There may be some constraints that make this possible,
1197 // but nothing simple has been discovered yet.
1198 CanFold = false;
1199 } else if (ShiftOpcode == Instruction::Shl) {
1200 // For a left shift, we can fold if the comparison is not signed.
1201 // We can also fold a signed comparison if the mask value and
1202 // comparison value are not negative. These constraints may not be
1203 // obvious, but we can prove that they are correct using an SMT
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001204 // solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001205 if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
Chris Lattner2188e402010-01-04 07:37:31 +00001206 CanFold = true;
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001207 } else if (ShiftOpcode == Instruction::LShr) {
1208 // For a logical right shift, we can fold if the comparison is not
1209 // signed. We can also fold a signed comparison if the shifted mask
1210 // value and the shifted comparison value are not negative.
1211 // These constraints may not be obvious, but we can prove that they
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001212 // are correct using an SMT solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001213 if (!ICI.isSigned())
1214 CanFold = true;
1215 else {
1216 ConstantInt *ShiftedAndCst =
1217 cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1218 ConstantInt *ShiftedRHSCst =
1219 cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1220
1221 if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1222 CanFold = true;
1223 }
Chris Lattner2188e402010-01-04 07:37:31 +00001224 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001225
Chris Lattner2188e402010-01-04 07:37:31 +00001226 if (CanFold) {
1227 Constant *NewCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001228 if (ShiftOpcode == Instruction::Shl)
Chris Lattner2188e402010-01-04 07:37:31 +00001229 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1230 else
1231 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001232
Chris Lattner2188e402010-01-04 07:37:31 +00001233 // Check to see if we are shifting out any of the bits being
1234 // compared.
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001235 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001236 // If we shifted bits out, the fold is not going to work out.
1237 // As a special case, check to see if this means that the
1238 // result is always true or false now.
1239 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Jakub Staszakbddea112013-06-06 20:18:46 +00001240 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001241 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Jakub Staszakbddea112013-06-06 20:18:46 +00001242 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001243 } else {
1244 ICI.setOperand(1, NewCst);
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001245 Constant *NewAndCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001246 if (ShiftOpcode == Instruction::Shl)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001247 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
Chris Lattner2188e402010-01-04 07:37:31 +00001248 else
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001249 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1250 LHSI->setOperand(1, NewAndCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001251 LHSI->setOperand(0, Shift->getOperand(0));
1252 Worklist.Add(Shift); // Shift is dead.
1253 return &ICI;
1254 }
1255 }
1256 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001257
Chris Lattner2188e402010-01-04 07:37:31 +00001258 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1259 // preferable because it allows the C<<Y expression to be hoisted out
1260 // of a loop if Y is invariant and X is not.
1261 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1262 ICI.isEquality() && !Shift->isArithmeticShift() &&
1263 !isa<Constant>(Shift->getOperand(0))) {
1264 // Compute C << Y.
1265 Value *NS;
1266 if (Shift->getOpcode() == Instruction::LShr) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001267 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001268 } else {
1269 // Insert a logical shift.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001270 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001271 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001272
Chris Lattner2188e402010-01-04 07:37:31 +00001273 // Compute X & (C << Y).
Jim Grosbach129c52a2011-09-30 18:09:53 +00001274 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001275 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001276
Chris Lattner2188e402010-01-04 07:37:31 +00001277 ICI.setOperand(0, NewAnd);
1278 return &ICI;
1279 }
Paul Redmond5917f4c2012-12-19 19:47:13 +00001280
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001281 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1282 // bit set in (X & AndCst) will produce a result greater than RHSV.
Paul Redmond5917f4c2012-12-19 19:47:13 +00001283 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001284 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1285 if ((NTZ < AndCst->getBitWidth()) &&
1286 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
Paul Redmond5917f4c2012-12-19 19:47:13 +00001287 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1288 Constant::getNullValue(RHS->getType()));
1289 }
Chris Lattner2188e402010-01-04 07:37:31 +00001290 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001291
Chris Lattner2188e402010-01-04 07:37:31 +00001292 // Try to optimize things like "A[i]&42 == 0" to index computations.
1293 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1294 if (GetElementPtrInst *GEP =
1295 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1296 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1297 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1298 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1299 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1300 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1301 return Res;
1302 }
1303 }
David Majnemer414d4e52013-07-09 08:09:32 +00001304
1305 // X & -C == -C -> X > u ~C
1306 // X & -C != -C -> X <= u ~C
1307 // iff C is a power of 2
1308 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1309 return new ICmpInst(
1310 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1311 : ICmpInst::ICMP_ULE,
1312 LHSI->getOperand(0), SubOne(RHS));
Chris Lattner2188e402010-01-04 07:37:31 +00001313 break;
1314
1315 case Instruction::Or: {
1316 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1317 break;
1318 Value *P, *Q;
1319 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1320 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1321 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner2188e402010-01-04 07:37:31 +00001322 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1323 Constant::getNullValue(P->getType()));
1324 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1325 Constant::getNullValue(Q->getType()));
1326 Instruction *Op;
1327 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1328 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1329 else
1330 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1331 return Op;
1332 }
1333 break;
1334 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001335
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001336 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1337 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1338 if (!Val) break;
1339
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001340 // If this is a signed comparison to 0 and the mul is sign preserving,
1341 // use the mul LHS operand instead.
1342 ICmpInst::Predicate pred = ICI.getPredicate();
1343 if (isSignTest(pred, RHS) && !Val->isZero() &&
1344 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1345 return new ICmpInst(Val->isNegative() ?
1346 ICmpInst::getSwappedPredicate(pred) : pred,
1347 LHSI->getOperand(0),
1348 Constant::getNullValue(RHS->getType()));
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001349
1350 break;
1351 }
1352
Chris Lattner2188e402010-01-04 07:37:31 +00001353 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
Chris Lattner2188e402010-01-04 07:37:31 +00001354 uint32_t TypeBits = RHSV.getBitWidth();
David Majnemerb889e402013-06-28 23:42:03 +00001355 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1356 if (!ShAmt) {
1357 Value *X;
1358 // (1 << X) pred P2 -> X pred Log2(P2)
1359 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1360 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1361 ICmpInst::Predicate Pred = ICI.getPredicate();
1362 if (ICI.isUnsigned()) {
1363 if (!RHSVIsPowerOf2) {
1364 // (1 << X) < 30 -> X <= 4
1365 // (1 << X) <= 30 -> X <= 4
1366 // (1 << X) >= 30 -> X > 4
1367 // (1 << X) > 30 -> X > 4
1368 if (Pred == ICmpInst::ICMP_ULT)
1369 Pred = ICmpInst::ICMP_ULE;
1370 else if (Pred == ICmpInst::ICMP_UGE)
1371 Pred = ICmpInst::ICMP_UGT;
1372 }
1373 unsigned RHSLog2 = RHSV.logBase2();
1374
1375 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
1376 // (1 << X) > 2147483648 -> X > 31 -> false
1377 // (1 << X) <= 2147483648 -> X <= 31 -> true
1378 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1379 if (RHSLog2 == TypeBits-1) {
1380 if (Pred == ICmpInst::ICMP_UGE)
1381 Pred = ICmpInst::ICMP_EQ;
1382 else if (Pred == ICmpInst::ICMP_UGT)
1383 return ReplaceInstUsesWith(ICI, Builder->getFalse());
1384 else if (Pred == ICmpInst::ICMP_ULE)
1385 return ReplaceInstUsesWith(ICI, Builder->getTrue());
1386 else if (Pred == ICmpInst::ICMP_ULT)
1387 Pred = ICmpInst::ICMP_NE;
1388 }
1389
1390 return new ICmpInst(Pred, X,
1391 ConstantInt::get(RHS->getType(), RHSLog2));
1392 } else if (ICI.isSigned()) {
1393 if (RHSV.isAllOnesValue()) {
1394 // (1 << X) <= -1 -> X == 31
1395 if (Pred == ICmpInst::ICMP_SLE)
1396 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1397 ConstantInt::get(RHS->getType(), TypeBits-1));
1398
1399 // (1 << X) > -1 -> X != 31
1400 if (Pred == ICmpInst::ICMP_SGT)
1401 return new ICmpInst(ICmpInst::ICMP_NE, X,
1402 ConstantInt::get(RHS->getType(), TypeBits-1));
1403 } else if (!RHSV) {
1404 // (1 << X) < 0 -> X == 31
1405 // (1 << X) <= 0 -> X == 31
1406 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1407 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1408 ConstantInt::get(RHS->getType(), TypeBits-1));
1409
1410 // (1 << X) >= 0 -> X != 31
1411 // (1 << X) > 0 -> X != 31
1412 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1413 return new ICmpInst(ICmpInst::ICMP_NE, X,
1414 ConstantInt::get(RHS->getType(), TypeBits-1));
1415 }
1416 } else if (ICI.isEquality()) {
1417 if (RHSVIsPowerOf2)
1418 return new ICmpInst(
1419 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
1420
1421 return ReplaceInstUsesWith(
1422 ICI, Pred == ICmpInst::ICMP_EQ ? Builder->getFalse()
1423 : Builder->getTrue());
1424 }
1425 }
1426 break;
1427 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001428
Chris Lattner2188e402010-01-04 07:37:31 +00001429 // Check that the shift amount is in range. If not, don't perform
1430 // undefined shifts. When the shift is visited it will be
1431 // simplified.
1432 if (ShAmt->uge(TypeBits))
1433 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001434
Chris Lattner2188e402010-01-04 07:37:31 +00001435 if (ICI.isEquality()) {
1436 // If we are comparing against bits always shifted out, the
1437 // comparison cannot succeed.
1438 Constant *Comp =
1439 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1440 ShAmt);
1441 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1442 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001443 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattner2188e402010-01-04 07:37:31 +00001444 return ReplaceInstUsesWith(ICI, Cst);
1445 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001446
Chris Lattner98457102011-02-10 05:23:05 +00001447 // If the shift is NUW, then it is just shifting out zeros, no need for an
1448 // AND.
1449 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1450 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1451 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001452
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001453 // If the shift is NSW and we compare to 0, then it is just shifting out
1454 // sign bits, no need for an AND either.
1455 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1456 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1457 ConstantExpr::getLShr(RHS, ShAmt));
1458
Chris Lattner2188e402010-01-04 07:37:31 +00001459 if (LHSI->hasOneUse()) {
1460 // Otherwise strength reduce the shift into an and.
1461 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Jakub Staszakbddea112013-06-06 20:18:46 +00001462 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
1463 TypeBits - ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001464
Chris Lattner2188e402010-01-04 07:37:31 +00001465 Value *And =
1466 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1467 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner98457102011-02-10 05:23:05 +00001468 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner2188e402010-01-04 07:37:31 +00001469 }
1470 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001471
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001472 // If this is a signed comparison to 0 and the shift is sign preserving,
1473 // use the shift LHS operand instead.
1474 ICmpInst::Predicate pred = ICI.getPredicate();
1475 if (isSignTest(pred, RHS) &&
1476 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1477 return new ICmpInst(pred,
1478 LHSI->getOperand(0),
1479 Constant::getNullValue(RHS->getType()));
1480
Chris Lattner2188e402010-01-04 07:37:31 +00001481 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1482 bool TrueIfSigned = false;
1483 if (LHSI->hasOneUse() &&
1484 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1485 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattner43273af2011-02-13 08:07:21 +00001486 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach129c52a2011-09-30 18:09:53 +00001487 APInt::getOneBitSet(TypeBits,
Chris Lattner43273af2011-02-13 08:07:21 +00001488 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00001489 Value *And =
1490 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1491 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1492 And, Constant::getNullValue(And->getType()));
1493 }
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001494
1495 // Transform (icmp pred iM (shl iM %v, N), CI)
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00001496 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1497 // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001498 // This enables to get rid of the shift in favor of a trunc which can be
1499 // free on the target. It has the additional benefit of comparing to a
1500 // smaller constant, which will be target friendly.
1501 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00001502 if (LHSI->hasOneUse() &&
1503 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001504 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1505 Constant *NCI = ConstantExpr::getTrunc(
1506 ConstantExpr::getAShr(RHS,
1507 ConstantInt::get(RHS->getType(), Amt)),
1508 NTy);
1509 return new ICmpInst(ICI.getPredicate(),
1510 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaison1fd843e2013-02-15 15:18:17 +00001511 NCI);
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001512 }
1513
Chris Lattner2188e402010-01-04 07:37:31 +00001514 break;
1515 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001516
Chris Lattner2188e402010-01-04 07:37:31 +00001517 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewycky174a7052011-02-28 08:31:40 +00001518 case Instruction::AShr: {
1519 // Handle equality comparisons of shift-by-constant.
1520 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1521 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1522 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattnerd369f572011-02-13 07:43:07 +00001523 return Res;
Nick Lewycky174a7052011-02-28 08:31:40 +00001524 }
1525
1526 // Handle exact shr's.
1527 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1528 if (RHSV.isMinValue())
1529 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1530 }
Chris Lattner2188e402010-01-04 07:37:31 +00001531 break;
Nick Lewycky174a7052011-02-28 08:31:40 +00001532 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001533
Chris Lattner2188e402010-01-04 07:37:31 +00001534 case Instruction::SDiv:
1535 case Instruction::UDiv:
1536 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach129c52a2011-09-30 18:09:53 +00001537 // Fold this div into the comparison, producing a range check.
1538 // Determine, based on the divide type, what the range is being
1539 // checked. If there is an overflow on the low or high side, remember
Chris Lattner2188e402010-01-04 07:37:31 +00001540 // it, otherwise compute the range [low, hi) bounding the new value.
1541 // See: InsertRangeTest above for the kinds of replacements possible.
1542 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1543 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1544 DivRHS))
1545 return R;
1546 break;
1547
David Majnemerf2a9a512013-07-09 07:50:59 +00001548 case Instruction::Sub: {
1549 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
1550 if (!LHSC) break;
1551 const APInt &LHSV = LHSC->getValue();
1552
1553 // C1-X <u C2 -> (X|(C2-1)) == C1
1554 // iff C1 & (C2-1) == C2-1
1555 // C2 is a power of 2
1556 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1557 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
1558 return new ICmpInst(ICmpInst::ICMP_EQ,
1559 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
1560 LHSC);
1561
David Majnemereeed73b2013-07-09 09:24:35 +00001562 // C1-X >u C2 -> (X|C2) != C1
David Majnemerf2a9a512013-07-09 07:50:59 +00001563 // iff C1 & C2 == C2
1564 // C2+1 is a power of 2
1565 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1566 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
1567 return new ICmpInst(ICmpInst::ICMP_NE,
1568 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
1569 break;
1570 }
1571
Chris Lattner2188e402010-01-04 07:37:31 +00001572 case Instruction::Add:
1573 // Fold: icmp pred (add X, C1), C2
1574 if (!ICI.isEquality()) {
1575 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1576 if (!LHSC) break;
1577 const APInt &LHSV = LHSC->getValue();
1578
1579 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1580 .subtract(LHSV);
1581
1582 if (ICI.isSigned()) {
1583 if (CR.getLower().isSignBit()) {
1584 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001585 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00001586 } else if (CR.getUpper().isSignBit()) {
1587 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001588 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00001589 }
1590 } else {
1591 if (CR.getLower().isMinValue()) {
1592 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001593 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00001594 } else if (CR.getUpper().isMinValue()) {
1595 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001596 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00001597 }
1598 }
David Majnemerfa90a0b2013-07-08 11:53:08 +00001599
David Majnemerbafa5372013-07-09 07:58:32 +00001600 // X-C1 <u C2 -> (X & -C2) == C1
1601 // iff C1 & (C2-1) == 0
1602 // C2 is a power of 2
David Majnemerfa90a0b2013-07-08 11:53:08 +00001603 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
David Majnemerbafa5372013-07-09 07:58:32 +00001604 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
David Majnemerfa90a0b2013-07-08 11:53:08 +00001605 return new ICmpInst(ICmpInst::ICMP_EQ,
1606 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
1607 ConstantExpr::getNeg(LHSC));
David Majnemerbafa5372013-07-09 07:58:32 +00001608
David Majnemereeed73b2013-07-09 09:24:35 +00001609 // X-C1 >u C2 -> (X & ~C2) != C1
David Majnemerbafa5372013-07-09 07:58:32 +00001610 // iff C1 & C2 == 0
1611 // C2+1 is a power of 2
1612 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1613 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
1614 return new ICmpInst(ICmpInst::ICMP_NE,
1615 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
1616 ConstantExpr::getNeg(LHSC));
Chris Lattner2188e402010-01-04 07:37:31 +00001617 }
1618 break;
1619 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001620
Chris Lattner2188e402010-01-04 07:37:31 +00001621 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1622 if (ICI.isEquality()) {
1623 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001624
1625 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner2188e402010-01-04 07:37:31 +00001626 // the second operand is a constant, simplify a bit.
1627 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1628 switch (BO->getOpcode()) {
1629 case Instruction::SRem:
1630 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1631 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1632 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohman4ce1fb12010-04-08 23:03:40 +00001633 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001634 Value *NewRem =
1635 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1636 BO->getName());
1637 return new ICmpInst(ICI.getPredicate(), NewRem,
1638 Constant::getNullValue(BO->getType()));
1639 }
1640 }
1641 break;
1642 case Instruction::Add:
1643 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1644 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1645 if (BO->hasOneUse())
1646 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1647 ConstantExpr::getSub(RHS, BOp1C));
1648 } else if (RHSV == 0) {
1649 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1650 // efficiently invertible, or if the add has just this one use.
1651 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001652
Chris Lattner2188e402010-01-04 07:37:31 +00001653 if (Value *NegVal = dyn_castNegVal(BOp1))
1654 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner31b106d2011-04-26 20:02:45 +00001655 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner2188e402010-01-04 07:37:31 +00001656 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner31b106d2011-04-26 20:02:45 +00001657 if (BO->hasOneUse()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001658 Value *Neg = Builder->CreateNeg(BOp1);
1659 Neg->takeName(BO);
1660 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1661 }
1662 }
1663 break;
1664 case Instruction::Xor:
1665 // For the xor case, we can xor two constants together, eliminating
1666 // the explicit xor.
Benjamin Kramerc9708492011-06-13 15:24:24 +00001667 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1668 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner2188e402010-01-04 07:37:31 +00001669 ConstantExpr::getXor(RHS, BOC));
Benjamin Kramerc9708492011-06-13 15:24:24 +00001670 } else if (RHSV == 0) {
1671 // Replace ((xor A, B) != 0) with (A != B)
Chris Lattner2188e402010-01-04 07:37:31 +00001672 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1673 BO->getOperand(1));
Benjamin Kramerc9708492011-06-13 15:24:24 +00001674 }
Chris Lattner2188e402010-01-04 07:37:31 +00001675 break;
Benjamin Kramerc9708492011-06-13 15:24:24 +00001676 case Instruction::Sub:
1677 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1678 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1679 if (BO->hasOneUse())
1680 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1681 ConstantExpr::getSub(BOp0C, RHS));
1682 } else if (RHSV == 0) {
1683 // Replace ((sub A, B) != 0) with (A != B)
1684 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1685 BO->getOperand(1));
1686 }
1687 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001688 case Instruction::Or:
1689 // If bits are being or'd in that are not present in the constant we
1690 // are comparing against, then the comparison could never succeed!
Eli Friedman0428a612010-07-29 18:03:33 +00001691 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001692 Constant *NotCI = ConstantExpr::getNot(RHS);
1693 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Jakub Staszakbddea112013-06-06 20:18:46 +00001694 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Chris Lattner2188e402010-01-04 07:37:31 +00001695 }
1696 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001697
Chris Lattner2188e402010-01-04 07:37:31 +00001698 case Instruction::And:
1699 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1700 // If bits are being compared against that are and'd out, then the
1701 // comparison can never succeed!
1702 if ((RHSV & ~BOC->getValue()) != 0)
Jakub Staszakbddea112013-06-06 20:18:46 +00001703 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001704
Chris Lattner2188e402010-01-04 07:37:31 +00001705 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1706 if (RHS == BOC && RHSV.isPowerOf2())
1707 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1708 ICmpInst::ICMP_NE, LHSI,
1709 Constant::getNullValue(RHS->getType()));
Benjamin Kramer9eca5fe2011-07-04 20:16:36 +00001710
1711 // Don't perform the following transforms if the AND has multiple uses
1712 if (!BO->hasOneUse())
1713 break;
1714
Chris Lattner2188e402010-01-04 07:37:31 +00001715 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1716 if (BOC->getValue().isSignBit()) {
1717 Value *X = BO->getOperand(0);
1718 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001719 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00001720 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1721 return new ICmpInst(pred, X, Zero);
1722 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001723
Chris Lattner2188e402010-01-04 07:37:31 +00001724 // ((X & ~7) == 0) --> X < 8
1725 if (RHSV == 0 && isHighOnes(BOC)) {
1726 Value *X = BO->getOperand(0);
1727 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001728 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00001729 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1730 return new ICmpInst(pred, X, NegX);
1731 }
1732 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001733 break;
1734 case Instruction::Mul:
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001735 if (RHSV == 0 && BO->hasNoSignedWrap()) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001736 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1737 // The trivial case (mul X, 0) is handled by InstSimplify
1738 // General case : (mul X, C) != 0 iff X != 0
1739 // (mul X, C) == 0 iff X == 0
1740 if (!BOC->isZero())
1741 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1742 Constant::getNullValue(RHS->getType()));
1743 }
1744 }
1745 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001746 default: break;
1747 }
1748 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1749 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner54f4e392010-01-05 18:09:56 +00001750 switch (II->getIntrinsicID()) {
1751 case Intrinsic::bswap:
Chris Lattner2188e402010-01-04 07:37:31 +00001752 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001753 ICI.setOperand(0, II->getArgOperand(0));
Jakub Staszakbddea112013-06-06 20:18:46 +00001754 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
Chris Lattner2188e402010-01-04 07:37:31 +00001755 return &ICI;
Chris Lattner54f4e392010-01-05 18:09:56 +00001756 case Intrinsic::ctlz:
1757 case Intrinsic::cttz:
1758 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1759 if (RHSV == RHS->getType()->getBitWidth()) {
1760 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001761 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00001762 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1763 return &ICI;
1764 }
1765 break;
1766 case Intrinsic::ctpop:
1767 // popcount(A) == 0 -> A == 0 and likewise for !=
1768 if (RHS->isZero()) {
1769 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001770 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00001771 ICI.setOperand(1, RHS);
1772 return &ICI;
1773 }
1774 break;
1775 default:
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001776 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001777 }
1778 }
1779 }
1780 return 0;
1781}
1782
1783/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1784/// We only handle extending casts so far.
1785///
1786Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1787 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1788 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001789 Type *SrcTy = LHSCIOp->getType();
1790 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00001791 Value *RHSCIOp;
1792
Jim Grosbach129c52a2011-09-30 18:09:53 +00001793 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00001794 // integer type is the same size as the pointer type.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001795 if (DL && LHSCI->getOpcode() == Instruction::PtrToInt &&
1796 DL->getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001797 Value *RHSOp = 0;
1798 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1799 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1800 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1801 RHSOp = RHSC->getOperand(0);
1802 // If the pointer types don't match, insert a bitcast.
1803 if (LHSCIOp->getType() != RHSOp->getType())
1804 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1805 }
1806
1807 if (RHSOp)
1808 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1809 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001810
Chris Lattner2188e402010-01-04 07:37:31 +00001811 // The code below only handles extension cast instructions, so far.
1812 // Enforce this.
1813 if (LHSCI->getOpcode() != Instruction::ZExt &&
1814 LHSCI->getOpcode() != Instruction::SExt)
1815 return 0;
1816
1817 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1818 bool isSignedCmp = ICI.isSigned();
1819
1820 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1821 // Not an extension from the same type?
1822 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001823 if (RHSCIOp->getType() != LHSCIOp->getType())
Chris Lattner2188e402010-01-04 07:37:31 +00001824 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001825
Chris Lattner2188e402010-01-04 07:37:31 +00001826 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1827 // and the other is a zext), then we can't handle this.
1828 if (CI->getOpcode() != LHSCI->getOpcode())
1829 return 0;
1830
1831 // Deal with equality cases early.
1832 if (ICI.isEquality())
1833 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1834
1835 // A signed comparison of sign extended values simplifies into a
1836 // signed comparison.
1837 if (isSignedCmp && isSignedExt)
1838 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1839
1840 // The other three cases all fold into an unsigned comparison.
1841 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1842 }
1843
1844 // If we aren't dealing with a constant on the RHS, exit early
1845 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1846 if (!CI)
1847 return 0;
1848
1849 // Compute the constant that would happen if we truncated to SrcTy then
1850 // reextended to DestTy.
1851 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1852 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1853 Res1, DestTy);
1854
1855 // If the re-extended constant didn't change...
1856 if (Res2 == CI) {
1857 // Deal with equality cases early.
1858 if (ICI.isEquality())
1859 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1860
1861 // A signed comparison of sign extended values simplifies into a
1862 // signed comparison.
1863 if (isSignedExt && isSignedCmp)
1864 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1865
1866 // The other three cases all fold into an unsigned comparison.
1867 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1868 }
1869
Jim Grosbach129c52a2011-09-30 18:09:53 +00001870 // The re-extended constant changed so the constant cannot be represented
Chris Lattner2188e402010-01-04 07:37:31 +00001871 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00001872 // All the cases that fold to true or false will have already been handled
1873 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00001874
Duncan Sands8fb2c382011-01-20 13:21:55 +00001875 if (isSignedCmp || !isSignedExt)
1876 return 0;
Chris Lattner2188e402010-01-04 07:37:31 +00001877
1878 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1879 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00001880
1881 // We're performing an unsigned comp with a sign extended value.
1882 // This is true if the input is >= 0. [aka >s -1]
1883 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1884 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00001885
1886 // Finally, return the value computed.
Duncan Sands8fb2c382011-01-20 13:21:55 +00001887 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner2188e402010-01-04 07:37:31 +00001888 return ReplaceInstUsesWith(ICI, Result);
1889
Duncan Sands8fb2c382011-01-20 13:21:55 +00001890 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00001891 return BinaryOperator::CreateNot(Result);
1892}
1893
Chris Lattneree61c1d2010-12-19 17:52:50 +00001894/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1895/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00001896/// If this is of the form:
1897/// sum = a + b
1898/// if (sum+128 >u 255)
1899/// Then replace it with llvm.sadd.with.overflow.i8.
1900///
Chris Lattneree61c1d2010-12-19 17:52:50 +00001901static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1902 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00001903 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00001904 // The transformation we're trying to do here is to transform this into an
1905 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1906 // with a narrower add, and discard the add-with-constant that is part of the
1907 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00001908
Chris Lattnerf29562d2010-12-19 17:59:02 +00001909 // In order to eliminate the add-with-constant, the compare can be its only
1910 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00001911 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Chris Lattnerf29562d2010-12-19 17:59:02 +00001912 if (!AddWithCst->hasOneUse()) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001913
Chris Lattnerc56c8452010-12-19 18:22:06 +00001914 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1915 if (!CI2->getValue().isPowerOf2()) return 0;
1916 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1917 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001918
Chris Lattnerc56c8452010-12-19 18:22:06 +00001919 // The width of the new add formed is 1 more than the bias.
1920 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001921
Chris Lattnerc56c8452010-12-19 18:22:06 +00001922 // Check to see that CI1 is an all-ones value with NewWidth bits.
1923 if (CI1->getBitWidth() == NewWidth ||
1924 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1925 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001926
Eli Friedmanb3f9b062011-11-28 23:32:19 +00001927 // This is only really a signed overflow check if the inputs have been
1928 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1929 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1930 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1931 if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1932 IC.ComputeNumSignBits(B) < NeededSignBits)
1933 return 0;
1934
Jim Grosbach129c52a2011-09-30 18:09:53 +00001935 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00001936 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1937 // and truncates that discard the high bits of the add. Verify that this is
1938 // the case.
1939 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00001940 for (User *U : OrigAdd->users()) {
1941 if (U == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001942
Chris Lattnerc56c8452010-12-19 18:22:06 +00001943 // Only accept truncates for now. We would really like a nice recursive
1944 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1945 // chain to see which bits of a value are actually demanded. If the
1946 // original add had another add which was then immediately truncated, we
1947 // could still do the transformation.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001948 TruncInst *TI = dyn_cast<TruncInst>(U);
Chris Lattnerc56c8452010-12-19 18:22:06 +00001949 if (TI == 0 ||
1950 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1951 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001952
Chris Lattneree61c1d2010-12-19 17:52:50 +00001953 // If the pattern matches, truncate the inputs to the narrower type and
1954 // use the sadd_with_overflow intrinsic to efficiently compute both the
1955 // result and the overflow bit.
Chris Lattner79874562010-12-19 18:35:09 +00001956 Module *M = I.getParent()->getParent()->getParent();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001957
Jay Foadb804a2b2011-07-12 14:06:48 +00001958 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Chris Lattner79874562010-12-19 18:35:09 +00001959 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
Benjamin Kramere6e19332011-07-14 17:45:39 +00001960 NewType);
Chris Lattner79874562010-12-19 18:35:09 +00001961
Chris Lattnerce2995a2010-12-19 18:38:44 +00001962 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001963
Chris Lattner79874562010-12-19 18:35:09 +00001964 // Put the new code above the original add, in case there are any uses of the
1965 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00001966 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001967
Chris Lattner79874562010-12-19 18:35:09 +00001968 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1969 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1970 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1971 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1972 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001973
Chris Lattneree61c1d2010-12-19 17:52:50 +00001974 // The inner add was the result of the narrow add, zero extended to the
1975 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattnerce2995a2010-12-19 18:38:44 +00001976 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001977
Chris Lattner79874562010-12-19 18:35:09 +00001978 // The original icmp gets replaced with the overflow value.
1979 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00001980}
Chris Lattner2188e402010-01-04 07:37:31 +00001981
Chris Lattner5e0c0c72010-12-19 19:37:52 +00001982static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1983 InstCombiner &IC) {
1984 // Don't bother doing this transformation for pointers, don't do it for
1985 // vectors.
1986 if (!isa<IntegerType>(OrigAddV->getType())) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001987
Chris Lattner5e0c0c72010-12-19 19:37:52 +00001988 // If the add is a constant expr, then we don't bother transforming it.
1989 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1990 if (OrigAdd == 0) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001991
Chris Lattner5e0c0c72010-12-19 19:37:52 +00001992 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001993
Chris Lattner5e0c0c72010-12-19 19:37:52 +00001994 // Put the new code above the original add, in case there are any uses of the
1995 // add between the add and the compare.
1996 InstCombiner::BuilderTy *Builder = IC.Builder;
1997 Builder->SetInsertPoint(OrigAdd);
1998
1999 Module *M = I.getParent()->getParent()->getParent();
Jay Foadb804a2b2011-07-12 14:06:48 +00002000 Type *Ty = LHS->getType();
Benjamin Kramere6e19332011-07-14 17:45:39 +00002001 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002002 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
2003 Value *Add = Builder->CreateExtractValue(Call, 0);
2004
2005 IC.ReplaceInstUsesWith(*OrigAdd, Add);
2006
2007 // The original icmp gets replaced with the overflow value.
2008 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
2009}
2010
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002011/// \brief Recognize and process idiom involving test for multiplication
2012/// overflow.
2013///
2014/// The caller has matched a pattern of the form:
2015/// I = cmp u (mul(zext A, zext B), V
2016/// The function checks if this is a test for overflow and if so replaces
2017/// multiplication with call to 'mul.with.overflow' intrinsic.
2018///
2019/// \param I Compare instruction.
2020/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2021/// the compare instruction. Must be of integer type.
2022/// \param OtherVal The other argument of compare instruction.
2023/// \returns Instruction which must replace the compare instruction, NULL if no
2024/// replacement required.
2025static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2026 Value *OtherVal, InstCombiner &IC) {
2027 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2028 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
2029 assert(isa<IntegerType>(MulVal->getType()));
2030 Instruction *MulInstr = cast<Instruction>(MulVal);
2031 assert(MulInstr->getOpcode() == Instruction::Mul);
2032
2033 Instruction *LHS = cast<Instruction>(MulInstr->getOperand(0)),
2034 *RHS = cast<Instruction>(MulInstr->getOperand(1));
2035 assert(LHS->getOpcode() == Instruction::ZExt);
2036 assert(RHS->getOpcode() == Instruction::ZExt);
2037 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2038
2039 // Calculate type and width of the result produced by mul.with.overflow.
2040 Type *TyA = A->getType(), *TyB = B->getType();
2041 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2042 WidthB = TyB->getPrimitiveSizeInBits();
2043 unsigned MulWidth;
2044 Type *MulType;
2045 if (WidthB > WidthA) {
2046 MulWidth = WidthB;
2047 MulType = TyB;
2048 } else {
2049 MulWidth = WidthA;
2050 MulType = TyA;
2051 }
2052
2053 // In order to replace the original mul with a narrower mul.with.overflow,
2054 // all uses must ignore upper bits of the product. The number of used low
2055 // bits must be not greater than the width of mul.with.overflow.
2056 if (MulVal->hasNUsesOrMore(2))
2057 for (User *U : MulVal->users()) {
2058 if (U == &I)
2059 continue;
2060 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2061 // Check if truncation ignores bits above MulWidth.
2062 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2063 if (TruncWidth > MulWidth)
2064 return 0;
2065 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2066 // Check if AND ignores bits above MulWidth.
2067 if (BO->getOpcode() != Instruction::And)
2068 return 0;
2069 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2070 const APInt &CVal = CI->getValue();
2071 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
2072 return 0;
2073 }
2074 } else {
2075 // Other uses prohibit this transformation.
2076 return 0;
2077 }
2078 }
2079
2080 // Recognize patterns
2081 switch (I.getPredicate()) {
2082 case ICmpInst::ICMP_EQ:
2083 case ICmpInst::ICMP_NE:
2084 // Recognize pattern:
2085 // mulval = mul(zext A, zext B)
2086 // cmp eq/neq mulval, zext trunc mulval
2087 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2088 if (Zext->hasOneUse()) {
2089 Value *ZextArg = Zext->getOperand(0);
2090 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2091 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2092 break; //Recognized
2093 }
2094
2095 // Recognize pattern:
2096 // mulval = mul(zext A, zext B)
2097 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2098 ConstantInt *CI;
2099 Value *ValToMask;
2100 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2101 if (ValToMask != MulVal)
2102 return 0;
2103 const APInt &CVal = CI->getValue() + 1;
2104 if (CVal.isPowerOf2()) {
2105 unsigned MaskWidth = CVal.logBase2();
2106 if (MaskWidth == MulWidth)
2107 break; // Recognized
2108 }
2109 }
2110 return 0;
2111
2112 case ICmpInst::ICMP_UGT:
2113 // Recognize pattern:
2114 // mulval = mul(zext A, zext B)
2115 // cmp ugt mulval, max
2116 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2117 APInt MaxVal = APInt::getMaxValue(MulWidth);
2118 MaxVal = MaxVal.zext(CI->getBitWidth());
2119 if (MaxVal.eq(CI->getValue()))
2120 break; // Recognized
2121 }
2122 return 0;
2123
2124 case ICmpInst::ICMP_UGE:
2125 // Recognize pattern:
2126 // mulval = mul(zext A, zext B)
2127 // cmp uge mulval, max+1
2128 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2129 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2130 if (MaxVal.eq(CI->getValue()))
2131 break; // Recognized
2132 }
2133 return 0;
2134
2135 case ICmpInst::ICMP_ULE:
2136 // Recognize pattern:
2137 // mulval = mul(zext A, zext B)
2138 // cmp ule mulval, max
2139 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2140 APInt MaxVal = APInt::getMaxValue(MulWidth);
2141 MaxVal = MaxVal.zext(CI->getBitWidth());
2142 if (MaxVal.eq(CI->getValue()))
2143 break; // Recognized
2144 }
2145 return 0;
2146
2147 case ICmpInst::ICMP_ULT:
2148 // Recognize pattern:
2149 // mulval = mul(zext A, zext B)
2150 // cmp ule mulval, max + 1
2151 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002152 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002153 if (MaxVal.eq(CI->getValue()))
2154 break; // Recognized
2155 }
2156 return 0;
2157
2158 default:
2159 return 0;
2160 }
2161
2162 InstCombiner::BuilderTy *Builder = IC.Builder;
2163 Builder->SetInsertPoint(MulInstr);
2164 Module *M = I.getParent()->getParent()->getParent();
2165
2166 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2167 Value *MulA = A, *MulB = B;
2168 if (WidthA < MulWidth)
2169 MulA = Builder->CreateZExt(A, MulType);
2170 if (WidthB < MulWidth)
2171 MulB = Builder->CreateZExt(B, MulType);
2172 Value *F =
2173 Intrinsic::getDeclaration(M, Intrinsic::umul_with_overflow, MulType);
2174 CallInst *Call = Builder->CreateCall2(F, MulA, MulB, "umul");
2175 IC.Worklist.Add(MulInstr);
2176
2177 // If there are uses of mul result other than the comparison, we know that
2178 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002179 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002180 if (MulVal->hasNUsesOrMore(2)) {
2181 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2182 for (User *U : MulVal->users()) {
2183 if (U == &I || U == OtherVal)
2184 continue;
2185 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2186 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
2187 IC.ReplaceInstUsesWith(*TI, Mul);
2188 else
2189 TI->setOperand(0, Mul);
2190 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2191 assert(BO->getOpcode() == Instruction::And);
2192 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2193 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2194 APInt ShortMask = CI->getValue().trunc(MulWidth);
2195 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2196 Instruction *Zext =
2197 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2198 IC.Worklist.Add(Zext);
2199 IC.ReplaceInstUsesWith(*BO, Zext);
2200 } else {
2201 llvm_unreachable("Unexpected Binary operation");
2202 }
2203 IC.Worklist.Add(cast<Instruction>(U));
2204 }
2205 }
2206 if (isa<Instruction>(OtherVal))
2207 IC.Worklist.Add(cast<Instruction>(OtherVal));
2208
2209 // The original icmp gets replaced with the overflow value, maybe inverted
2210 // depending on predicate.
2211 bool Inverse = false;
2212 switch (I.getPredicate()) {
2213 case ICmpInst::ICMP_NE:
2214 break;
2215 case ICmpInst::ICMP_EQ:
2216 Inverse = true;
2217 break;
2218 case ICmpInst::ICMP_UGT:
2219 case ICmpInst::ICMP_UGE:
2220 if (I.getOperand(0) == MulVal)
2221 break;
2222 Inverse = true;
2223 break;
2224 case ICmpInst::ICMP_ULT:
2225 case ICmpInst::ICMP_ULE:
2226 if (I.getOperand(1) == MulVal)
2227 break;
2228 Inverse = true;
2229 break;
2230 default:
2231 llvm_unreachable("Unexpected predicate");
2232 }
2233 if (Inverse) {
2234 Value *Res = Builder->CreateExtractValue(Call, 1);
2235 return BinaryOperator::CreateNot(Res);
2236 }
2237
2238 return ExtractValueInst::Create(Call, 1);
2239}
2240
Owen Andersond490c2d2011-01-11 00:36:45 +00002241// DemandedBitsLHSMask - When performing a comparison against a constant,
2242// it is possible that not all the bits in the LHS are demanded. This helper
2243// method computes the mask that IS demanded.
2244static APInt DemandedBitsLHSMask(ICmpInst &I,
2245 unsigned BitWidth, bool isSignCheck) {
2246 if (isSignCheck)
2247 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002248
Owen Andersond490c2d2011-01-11 00:36:45 +00002249 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2250 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00002251 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002252
Owen Andersond490c2d2011-01-11 00:36:45 +00002253 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002254 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00002255 // correspond to the trailing ones of the comparand. The value of these
2256 // bits doesn't impact the outcome of the comparison, because any value
2257 // greater than the RHS must differ in a bit higher than these due to carry.
2258 case ICmpInst::ICMP_UGT: {
2259 unsigned trailingOnes = RHS.countTrailingOnes();
2260 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2261 return ~lowBitsSet;
2262 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002263
Owen Andersond490c2d2011-01-11 00:36:45 +00002264 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2265 // Any value less than the RHS must differ in a higher bit because of carries.
2266 case ICmpInst::ICMP_ULT: {
2267 unsigned trailingZeros = RHS.countTrailingZeros();
2268 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2269 return ~lowBitsSet;
2270 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002271
Owen Andersond490c2d2011-01-11 00:36:45 +00002272 default:
2273 return APInt::getAllOnesValue(BitWidth);
2274 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002275
Owen Andersond490c2d2011-01-11 00:36:45 +00002276}
Chris Lattner2188e402010-01-04 07:37:31 +00002277
Quentin Colombet5ab55552013-09-09 20:56:48 +00002278/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2279/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00002280/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00002281/// as subtract operands and their positions in those instructions.
2282/// The rational is that several architectures use the same instruction for
2283/// both subtract and cmp, thus it is better if the order of those operands
2284/// match.
2285/// \return true if Op0 and Op1 should be swapped.
2286static bool swapMayExposeCSEOpportunities(const Value * Op0,
2287 const Value * Op1) {
2288 // Filter out pointer value as those cannot appears directly in subtract.
2289 // FIXME: we may want to go through inttoptrs or bitcasts.
2290 if (Op0->getType()->isPointerTy())
2291 return false;
2292 // Count every uses of both Op0 and Op1 in a subtract.
2293 // Each time Op0 is the first operand, count -1: swapping is bad, the
2294 // subtract has already the same layout as the compare.
2295 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00002296 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002297 // At the end, if the benefit is greater than 0, Op0 should come second to
2298 // expose more CSE opportunities.
2299 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002300 for (const User *U : Op0->users()) {
2301 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002302 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2303 continue;
2304 // If Op0 is the first argument, this is not beneficial to swap the
2305 // arguments.
2306 int LocalSwapBenefits = -1;
2307 unsigned Op1Idx = 1;
2308 if (BinOp->getOperand(Op1Idx) == Op0) {
2309 Op1Idx = 0;
2310 LocalSwapBenefits = 1;
2311 }
2312 if (BinOp->getOperand(Op1Idx) != Op1)
2313 continue;
2314 GlobalSwapBenefits += LocalSwapBenefits;
2315 }
2316 return GlobalSwapBenefits > 0;
2317}
2318
Chris Lattner2188e402010-01-04 07:37:31 +00002319Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
2320 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00002321 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002322 unsigned Op0Cplxity = getComplexity(Op0);
2323 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002324
Chris Lattner2188e402010-01-04 07:37:31 +00002325 /// Orders the operands of the compare so that they are listed from most
2326 /// complex to least complex. This puts constants before unary operators,
2327 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002328 if (Op0Cplxity < Op1Cplxity ||
2329 (Op0Cplxity == Op1Cplxity &&
2330 swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002331 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00002332 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00002333 Changed = true;
2334 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002335
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002336 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL))
Chris Lattner2188e402010-01-04 07:37:31 +00002337 return ReplaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002338
Pete Cooperbc5c5242011-12-01 03:58:40 +00002339 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00002340 // ie, abs(val) != 0 -> val != 0
Pete Cooperbc5c5242011-12-01 03:58:40 +00002341 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
2342 {
Pete Cooperfdddc272011-12-01 19:13:26 +00002343 Value *Cond, *SelectTrue, *SelectFalse;
2344 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00002345 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00002346 if (Value *V = dyn_castNegVal(SelectTrue)) {
2347 if (V == SelectFalse)
2348 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2349 }
2350 else if (Value *V = dyn_castNegVal(SelectFalse)) {
2351 if (V == SelectTrue)
2352 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00002353 }
2354 }
2355 }
2356
Chris Lattner229907c2011-07-18 04:54:35 +00002357 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002358
2359 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sands9dff9be2010-02-15 16:12:20 +00002360 if (Ty->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00002361 switch (I.getPredicate()) {
2362 default: llvm_unreachable("Invalid icmp instruction!");
2363 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
2364 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
2365 return BinaryOperator::CreateNot(Xor);
2366 }
2367 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
2368 return BinaryOperator::CreateXor(Op0, Op1);
2369
2370 case ICmpInst::ICMP_UGT:
2371 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
2372 // FALL THROUGH
2373 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
2374 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2375 return BinaryOperator::CreateAnd(Not, Op1);
2376 }
2377 case ICmpInst::ICMP_SGT:
2378 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
2379 // FALL THROUGH
2380 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
2381 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2382 return BinaryOperator::CreateAnd(Not, Op0);
2383 }
2384 case ICmpInst::ICMP_UGE:
2385 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
2386 // FALL THROUGH
2387 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
2388 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2389 return BinaryOperator::CreateOr(Not, Op1);
2390 }
2391 case ICmpInst::ICMP_SGE:
2392 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
2393 // FALL THROUGH
2394 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
2395 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2396 return BinaryOperator::CreateOr(Not, Op0);
2397 }
2398 }
2399 }
2400
2401 unsigned BitWidth = 0;
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002402 if (Ty->isIntOrIntVectorTy())
Chris Lattner2188e402010-01-04 07:37:31 +00002403 BitWidth = Ty->getScalarSizeInBits();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002404 else if (DL) // Pointers require DL info to get their size.
2405 BitWidth = DL->getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002406
Chris Lattner2188e402010-01-04 07:37:31 +00002407 bool isSignBit = false;
2408
2409 // See if we are doing a comparison with a constant.
2410 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2411 Value *A = 0, *B = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002412
Owen Anderson1294ea72010-12-17 18:08:00 +00002413 // Match the following pattern, which is a common idiom when writing
2414 // overflow-safe integer arithmetic function. The source performs an
2415 // addition in wider type, and explicitly checks for overflow using
2416 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
2417 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00002418 //
2419 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00002420 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00002421 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00002422 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00002423 // sum = a + b
2424 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00002425 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00002426 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00002427 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00002428 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00002429 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00002430 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00002431 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002432
Chris Lattner2188e402010-01-04 07:37:31 +00002433 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2434 if (I.isEquality() && CI->isZero() &&
2435 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
2436 // (icmp cond A B) if cond is equality
2437 return new ICmpInst(I.getPredicate(), A, B);
2438 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002439
Chris Lattner2188e402010-01-04 07:37:31 +00002440 // If we have an icmp le or icmp ge instruction, turn it into the
2441 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
2442 // them being folded in the code below. The SimplifyICmpInst code has
2443 // already handled the edge cases for us, so we just assert on them.
2444 switch (I.getPredicate()) {
2445 default: break;
2446 case ICmpInst::ICMP_ULE:
2447 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
2448 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002449 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002450 case ICmpInst::ICMP_SLE:
2451 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
2452 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002453 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002454 case ICmpInst::ICMP_UGE:
Nick Lewycky6b4454192011-02-28 06:20:05 +00002455 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner2188e402010-01-04 07:37:31 +00002456 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002457 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002458 case ICmpInst::ICMP_SGE:
Nick Lewycky6b4454192011-02-28 06:20:05 +00002459 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner2188e402010-01-04 07:37:31 +00002460 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002461 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002462 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002463
Chris Lattner2188e402010-01-04 07:37:31 +00002464 // If this comparison is a normal comparison, it demands all
2465 // bits, if it is a sign bit comparison, it only demands the sign bit.
2466 bool UnusedBit;
2467 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2468 }
2469
2470 // See if we can fold the comparison based on range information we can get
2471 // by checking whether bits are known to be zero or one in the input.
2472 if (BitWidth != 0) {
2473 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2474 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2475
2476 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersond490c2d2011-01-11 00:36:45 +00002477 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner2188e402010-01-04 07:37:31 +00002478 Op0KnownZero, Op0KnownOne, 0))
2479 return &I;
2480 if (SimplifyDemandedBits(I.getOperandUse(1),
2481 APInt::getAllOnesValue(BitWidth),
2482 Op1KnownZero, Op1KnownOne, 0))
2483 return &I;
2484
2485 // Given the known and unknown bits, compute a range that the LHS could be
2486 // in. Compute the Min, Max and RHS values based on the known bits. For the
2487 // EQ and NE we use unsigned values.
2488 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2489 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2490 if (I.isSigned()) {
2491 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2492 Op0Min, Op0Max);
2493 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2494 Op1Min, Op1Max);
2495 } else {
2496 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2497 Op0Min, Op0Max);
2498 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2499 Op1Min, Op1Max);
2500 }
2501
2502 // If Min and Max are known to be the same, then SimplifyDemandedBits
2503 // figured out that the LHS is a constant. Just constant fold this now so
2504 // that code below can assume that Min != Max.
2505 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2506 return new ICmpInst(I.getPredicate(),
Nick Lewycky92db8e82011-03-06 03:36:19 +00002507 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00002508 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2509 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewycky92db8e82011-03-06 03:36:19 +00002510 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner2188e402010-01-04 07:37:31 +00002511
2512 // Based on the range information we know about the LHS, see if we can
Nick Lewycky6b4454192011-02-28 06:20:05 +00002513 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner2188e402010-01-04 07:37:31 +00002514 switch (I.getPredicate()) {
2515 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattnerf7e89612010-11-21 06:44:42 +00002516 case ICmpInst::ICMP_EQ: {
Chris Lattner2188e402010-01-04 07:37:31 +00002517 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewycky92db8e82011-03-06 03:36:19 +00002518 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002519
Chris Lattnerf7e89612010-11-21 06:44:42 +00002520 // If all bits are known zero except for one, then we know at most one
2521 // bit is set. If the comparison is against zero, then this is a check
2522 // to see if *that* bit is set.
2523 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2524 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2525 // If the LHS is an AND with the same constant, look through it.
2526 Value *LHS = 0;
2527 ConstantInt *LHSC = 0;
2528 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2529 LHSC->getValue() != Op0KnownZeroInverted)
2530 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002531
Chris Lattnerf7e89612010-11-21 06:44:42 +00002532 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattnere5afa152010-11-23 02:42:04 +00002533 // then turn "((1 << x)&8) == 0" into "x != 3".
Chris Lattnerf7e89612010-11-21 06:44:42 +00002534 Value *X = 0;
2535 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2536 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattnere5afa152010-11-23 02:42:04 +00002537 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattnerf7e89612010-11-21 06:44:42 +00002538 ConstantInt::get(X->getType(), CmpVal));
2539 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002540
Chris Lattnerf7e89612010-11-21 06:44:42 +00002541 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattnere5afa152010-11-23 02:42:04 +00002542 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattner98457102011-02-10 05:23:05 +00002543 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002544 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00002545 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00002546 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner98457102011-02-10 05:23:05 +00002547 ConstantInt::get(X->getType(),
2548 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00002549 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002550
Chris Lattner2188e402010-01-04 07:37:31 +00002551 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002552 }
2553 case ICmpInst::ICMP_NE: {
Chris Lattner2188e402010-01-04 07:37:31 +00002554 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewycky92db8e82011-03-06 03:36:19 +00002555 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002556
Chris Lattnerf7e89612010-11-21 06:44:42 +00002557 // If all bits are known zero except for one, then we know at most one
2558 // bit is set. If the comparison is against zero, then this is a check
2559 // to see if *that* bit is set.
2560 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2561 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2562 // If the LHS is an AND with the same constant, look through it.
2563 Value *LHS = 0;
2564 ConstantInt *LHSC = 0;
2565 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2566 LHSC->getValue() != Op0KnownZeroInverted)
2567 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002568
Chris Lattnerf7e89612010-11-21 06:44:42 +00002569 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattnere5afa152010-11-23 02:42:04 +00002570 // then turn "((1 << x)&8) != 0" into "x == 3".
Chris Lattnerf7e89612010-11-21 06:44:42 +00002571 Value *X = 0;
2572 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2573 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattnere5afa152010-11-23 02:42:04 +00002574 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattnerf7e89612010-11-21 06:44:42 +00002575 ConstantInt::get(X->getType(), CmpVal));
2576 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002577
Chris Lattnerf7e89612010-11-21 06:44:42 +00002578 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattnere5afa152010-11-23 02:42:04 +00002579 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattner98457102011-02-10 05:23:05 +00002580 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002581 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00002582 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00002583 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner98457102011-02-10 05:23:05 +00002584 ConstantInt::get(X->getType(),
2585 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00002586 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002587
Chris Lattner2188e402010-01-04 07:37:31 +00002588 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002589 }
Chris Lattner2188e402010-01-04 07:37:31 +00002590 case ICmpInst::ICMP_ULT:
2591 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002592 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002593 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002594 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002595 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2596 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2597 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2598 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2599 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002600 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002601
2602 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2603 if (CI->isMinValue(true))
2604 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2605 Constant::getAllOnesValue(Op0->getType()));
2606 }
2607 break;
2608 case ICmpInst::ICMP_UGT:
2609 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002610 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002611 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002612 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002613
2614 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2615 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2616 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2617 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2618 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002619 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002620
2621 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2622 if (CI->isMaxValue(true))
2623 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2624 Constant::getNullValue(Op0->getType()));
2625 }
2626 break;
2627 case ICmpInst::ICMP_SLT:
2628 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002629 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002630 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002631 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002632 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2633 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2634 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2635 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2636 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002637 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002638 }
2639 break;
2640 case ICmpInst::ICMP_SGT:
2641 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002642 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002643 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002644 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002645
2646 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2647 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2648 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2649 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2650 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002651 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002652 }
2653 break;
2654 case ICmpInst::ICMP_SGE:
2655 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2656 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002657 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002658 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002659 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002660 break;
2661 case ICmpInst::ICMP_SLE:
2662 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2663 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002664 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002665 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002666 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002667 break;
2668 case ICmpInst::ICMP_UGE:
2669 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2670 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002671 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002672 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002673 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002674 break;
2675 case ICmpInst::ICMP_ULE:
2676 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2677 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002678 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002679 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002680 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002681 break;
2682 }
2683
2684 // Turn a signed comparison into an unsigned one if both operands
2685 // are known to have the same sign.
2686 if (I.isSigned() &&
2687 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2688 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2689 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2690 }
2691
2692 // Test if the ICmpInst instruction is used exclusively by a select as
2693 // part of a minimum or maximum operation. If so, refrain from doing
2694 // any other folding. This helps out other analyses which understand
2695 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2696 // and CodeGen. And in this case, at least one of the comparison
2697 // operands has at least one user besides the compare (the select),
2698 // which would often largely negate the benefit of folding anyway.
2699 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00002700 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00002701 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2702 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2703 return 0;
2704
2705 // See if we are doing a comparison between a constant and an instruction that
2706 // can be folded into the comparison.
2707 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002708 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2709 // instruction, see if that instruction also has constants so that the
2710 // instruction can be folded into the icmp
Chris Lattner2188e402010-01-04 07:37:31 +00002711 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2712 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2713 return Res;
2714 }
2715
2716 // Handle icmp with constant (but not simple integer constant) RHS
2717 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2718 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2719 switch (LHSI->getOpcode()) {
2720 case Instruction::GetElementPtr:
2721 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2722 if (RHSC->isNullValue() &&
2723 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2724 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2725 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2726 break;
2727 case Instruction::PHI:
2728 // Only fold icmp into the PHI if the phi and icmp are in the same
2729 // block. If in the same block, we're encouraging jump threading. If
2730 // not, we are just pessimizing the code by making an i1 phi.
2731 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00002732 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00002733 return NV;
2734 break;
2735 case Instruction::Select: {
2736 // If either operand of the select is a constant, we can fold the
2737 // comparison into the select arms, which will cause one to be
2738 // constant folded and the select turned into a bitwise or.
2739 Value *Op1 = 0, *Op2 = 0;
2740 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2741 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2742 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2743 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2744
2745 // We only want to perform this transformation if it will not lead to
2746 // additional code. This is true if either both sides of the select
2747 // fold to a constant (in which case the icmp is replaced with a select
2748 // which will usually simplify) or this is the only user of the
2749 // select (in which case we are trading a select+icmp for a simpler
2750 // select+icmp).
2751 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2752 if (!Op1)
2753 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2754 RHSC, I.getName());
2755 if (!Op2)
2756 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2757 RHSC, I.getName());
2758 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2759 }
2760 break;
2761 }
Chris Lattner2188e402010-01-04 07:37:31 +00002762 case Instruction::IntToPtr:
2763 // icmp pred inttoptr(X), null -> icmp pred X, 0
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002764 if (RHSC->isNullValue() && DL &&
2765 DL->getIntPtrType(RHSC->getType()) ==
Chris Lattner2188e402010-01-04 07:37:31 +00002766 LHSI->getOperand(0)->getType())
2767 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2768 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2769 break;
2770
2771 case Instruction::Load:
2772 // Try to optimize things like "A[i] > 4" to index computations.
2773 if (GetElementPtrInst *GEP =
2774 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2775 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2776 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2777 !cast<LoadInst>(LHSI)->isVolatile())
2778 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2779 return Res;
2780 }
2781 break;
2782 }
2783 }
2784
2785 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2786 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2787 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2788 return NI;
2789 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2790 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2791 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2792 return NI;
2793
2794 // Test to see if the operands of the icmp are casted versions of other
2795 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
2796 // now.
2797 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002798 if (Op0->getType()->isPointerTy() &&
2799 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002800 // We keep moving the cast from the left operand over to the right
2801 // operand, where it can often be eliminated completely.
2802 Op0 = CI->getOperand(0);
2803
2804 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2805 // so eliminate it as well.
2806 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2807 Op1 = CI2->getOperand(0);
2808
2809 // If Op1 is a constant, we can fold the cast into the constant.
2810 if (Op0->getType() != Op1->getType()) {
2811 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2812 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2813 } else {
2814 // Otherwise, cast the RHS right before the icmp
2815 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2816 }
2817 }
2818 return new ICmpInst(I.getPredicate(), Op0, Op1);
2819 }
2820 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002821
Chris Lattner2188e402010-01-04 07:37:31 +00002822 if (isa<CastInst>(Op0)) {
2823 // Handle the special case of: icmp (cast bool to X), <cst>
2824 // This comes up when you have code like
2825 // int X = A < B;
2826 // if (X) ...
2827 // For generality, we handle any zero-extension of any operand comparison
2828 // with a constant or another cast from the same type.
2829 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2830 if (Instruction *R = visitICmpInstWithCastAndCast(I))
2831 return R;
2832 }
Chris Lattner2188e402010-01-04 07:37:31 +00002833
Duncan Sandse5220012011-02-17 07:46:37 +00002834 // Special logic for binary operators.
2835 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2836 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2837 if (BO0 || BO1) {
2838 CmpInst::Predicate Pred = I.getPredicate();
2839 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2840 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2841 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2842 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2843 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2844 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2845 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2846 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2847 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2848
2849 // Analyze the case when either Op0 or Op1 is an add instruction.
2850 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2851 Value *A = 0, *B = 0, *C = 0, *D = 0;
2852 if (BO0 && BO0->getOpcode() == Instruction::Add)
2853 A = BO0->getOperand(0), B = BO0->getOperand(1);
2854 if (BO1 && BO1->getOpcode() == Instruction::Add)
2855 C = BO1->getOperand(0), D = BO1->getOperand(1);
2856
2857 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2858 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2859 return new ICmpInst(Pred, A == Op1 ? B : A,
2860 Constant::getNullValue(Op1->getType()));
2861
2862 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2863 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2864 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2865 C == Op0 ? D : C);
2866
Duncan Sands84653b32011-02-18 16:25:37 +00002867 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00002868 if (A && C && (A == C || A == D || B == C || B == D) &&
2869 NoOp0WrapProblem && NoOp1WrapProblem &&
2870 // Try not to increase register pressure.
2871 BO0->hasOneUse() && BO1->hasOneUse()) {
2872 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00002873 Value *Y, *Z;
2874 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002875 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00002876 Y = B;
2877 Z = D;
2878 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002879 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00002880 Y = B;
2881 Z = C;
2882 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002883 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00002884 Y = A;
2885 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002886 } else {
2887 assert(B == D);
2888 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00002889 Y = A;
2890 Z = C;
2891 }
Duncan Sandse5220012011-02-17 07:46:37 +00002892 return new ICmpInst(Pred, Y, Z);
2893 }
2894
David Majnemerb81cd632013-04-11 20:05:46 +00002895 // icmp slt (X + -1), Y -> icmp sle X, Y
2896 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
2897 match(B, m_AllOnes()))
2898 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
2899
2900 // icmp sge (X + -1), Y -> icmp sgt X, Y
2901 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
2902 match(B, m_AllOnes()))
2903 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
2904
2905 // icmp sle (X + 1), Y -> icmp slt X, Y
2906 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
2907 match(B, m_One()))
2908 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
2909
2910 // icmp sgt (X + 1), Y -> icmp sge X, Y
2911 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
2912 match(B, m_One()))
2913 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
2914
2915 // if C1 has greater magnitude than C2:
2916 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
2917 // s.t. C3 = C1 - C2
2918 //
2919 // if C2 has greater magnitude than C1:
2920 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
2921 // s.t. C3 = C2 - C1
2922 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
2923 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
2924 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
2925 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
2926 const APInt &AP1 = C1->getValue();
2927 const APInt &AP2 = C2->getValue();
2928 if (AP1.isNegative() == AP2.isNegative()) {
2929 APInt AP1Abs = C1->getValue().abs();
2930 APInt AP2Abs = C2->getValue().abs();
2931 if (AP1Abs.uge(AP2Abs)) {
2932 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
2933 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
2934 return new ICmpInst(Pred, NewAdd, C);
2935 } else {
2936 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
2937 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
2938 return new ICmpInst(Pred, A, NewAdd);
2939 }
2940 }
2941 }
2942
2943
Duncan Sandse5220012011-02-17 07:46:37 +00002944 // Analyze the case when either Op0 or Op1 is a sub instruction.
2945 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2946 A = 0; B = 0; C = 0; D = 0;
2947 if (BO0 && BO0->getOpcode() == Instruction::Sub)
2948 A = BO0->getOperand(0), B = BO0->getOperand(1);
2949 if (BO1 && BO1->getOpcode() == Instruction::Sub)
2950 C = BO1->getOperand(0), D = BO1->getOperand(1);
2951
Duncan Sands84653b32011-02-18 16:25:37 +00002952 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2953 if (A == Op1 && NoOp0WrapProblem)
2954 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2955
2956 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2957 if (C == Op0 && NoOp1WrapProblem)
2958 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2959
2960 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00002961 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2962 // Try not to increase register pressure.
2963 BO0->hasOneUse() && BO1->hasOneUse())
2964 return new ICmpInst(Pred, A, C);
2965
Duncan Sands84653b32011-02-18 16:25:37 +00002966 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2967 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2968 // Try not to increase register pressure.
2969 BO0->hasOneUse() && BO1->hasOneUse())
2970 return new ICmpInst(Pred, D, B);
2971
Nick Lewycky25cc3382011-03-05 04:28:48 +00002972 BinaryOperator *SRem = NULL;
Nick Lewyckyafc80982011-03-08 06:29:47 +00002973 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00002974 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2975 Op1 == BO0->getOperand(1))
2976 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00002977 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00002978 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2979 Op0 == BO1->getOperand(1))
2980 SRem = BO1;
2981 if (SRem) {
2982 // We don't check hasOneUse to avoid increasing register pressure because
2983 // the value we use is the same value this instruction was already using.
2984 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2985 default: break;
2986 case ICmpInst::ICMP_EQ:
Nick Lewycky92db8e82011-03-06 03:36:19 +00002987 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00002988 case ICmpInst::ICMP_NE:
Nick Lewycky92db8e82011-03-06 03:36:19 +00002989 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00002990 case ICmpInst::ICMP_SGT:
2991 case ICmpInst::ICMP_SGE:
2992 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2993 Constant::getAllOnesValue(SRem->getType()));
2994 case ICmpInst::ICMP_SLT:
2995 case ICmpInst::ICMP_SLE:
2996 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2997 Constant::getNullValue(SRem->getType()));
2998 }
2999 }
3000
Duncan Sandse5220012011-02-17 07:46:37 +00003001 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
3002 BO0->hasOneUse() && BO1->hasOneUse() &&
3003 BO0->getOperand(1) == BO1->getOperand(1)) {
3004 switch (BO0->getOpcode()) {
3005 default: break;
3006 case Instruction::Add:
3007 case Instruction::Sub:
3008 case Instruction::Xor:
3009 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
3010 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3011 BO1->getOperand(0));
3012 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
3013 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3014 if (CI->getValue().isSignBit()) {
3015 ICmpInst::Predicate Pred = I.isSigned()
3016 ? I.getUnsignedPredicate()
3017 : I.getSignedPredicate();
3018 return new ICmpInst(Pred, BO0->getOperand(0),
3019 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00003020 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003021
Chris Lattnerb1a15122011-07-15 06:08:15 +00003022 if (CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00003023 ICmpInst::Predicate Pred = I.isSigned()
3024 ? I.getUnsignedPredicate()
3025 : I.getSignedPredicate();
3026 Pred = I.getSwappedPredicate(Pred);
3027 return new ICmpInst(Pred, BO0->getOperand(0),
3028 BO1->getOperand(0));
3029 }
Chris Lattner2188e402010-01-04 07:37:31 +00003030 }
Duncan Sandse5220012011-02-17 07:46:37 +00003031 break;
3032 case Instruction::Mul:
3033 if (!I.isEquality())
3034 break;
3035
3036 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3037 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
3038 // Mask = -1 >> count-trailing-zeros(Cst).
3039 if (!CI->isZero() && !CI->isOne()) {
3040 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003041 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00003042 APInt::getLowBitsSet(AP.getBitWidth(),
3043 AP.getBitWidth() -
3044 AP.countTrailingZeros()));
3045 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
3046 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
3047 return new ICmpInst(I.getPredicate(), And1, And2);
3048 }
3049 }
3050 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00003051 case Instruction::UDiv:
3052 case Instruction::LShr:
3053 if (I.isSigned())
3054 break;
3055 // fall-through
3056 case Instruction::SDiv:
3057 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00003058 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00003059 break;
3060 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3061 BO1->getOperand(0));
3062 case Instruction::Shl: {
3063 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
3064 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
3065 if (!NUW && !NSW)
3066 break;
3067 if (!NSW && I.isSigned())
3068 break;
3069 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3070 BO1->getOperand(0));
3071 }
Chris Lattner2188e402010-01-04 07:37:31 +00003072 }
3073 }
3074 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003075
Chris Lattner2188e402010-01-04 07:37:31 +00003076 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00003077 // Transform (A & ~B) == 0 --> (A & B) != 0
3078 // and (A & ~B) != 0 --> (A & B) == 0
3079 // if A is a power of 2.
3080 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
3081 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A) && I.isEquality())
3082 return new ICmpInst(I.getInversePredicate(),
3083 Builder->CreateAnd(A, B),
3084 Op1);
3085
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00003086 // ~x < ~y --> y < x
3087 // ~x < cst --> ~cst < x
3088 if (match(Op0, m_Not(m_Value(A)))) {
3089 if (match(Op1, m_Not(m_Value(B))))
3090 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00003091 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00003092 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
3093 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003094
3095 // (a+b) <u a --> llvm.uadd.with.overflow.
3096 // (a+b) <u b --> llvm.uadd.with.overflow.
3097 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
Jim Grosbach129c52a2011-09-30 18:09:53 +00003098 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003099 (Op1 == A || Op1 == B))
3100 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
3101 return R;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003102
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003103 // a >u (a+b) --> llvm.uadd.with.overflow.
3104 // b >u (a+b) --> llvm.uadd.with.overflow.
3105 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
3106 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
3107 (Op0 == A || Op0 == B))
3108 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
3109 return R;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003110
3111 // (zext a) * (zext b) --> llvm.umul.with.overflow.
3112 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
3113 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
3114 return R;
3115 }
3116 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
3117 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
3118 return R;
3119 }
Chris Lattner2188e402010-01-04 07:37:31 +00003120 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003121
Chris Lattner2188e402010-01-04 07:37:31 +00003122 if (I.isEquality()) {
3123 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00003124
Chris Lattner2188e402010-01-04 07:37:31 +00003125 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3126 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
3127 Value *OtherVal = A == Op1 ? B : A;
3128 return new ICmpInst(I.getPredicate(), OtherVal,
3129 Constant::getNullValue(A->getType()));
3130 }
3131
3132 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
3133 // A^c1 == C^c2 --> A == C^(c1^c2)
3134 ConstantInt *C1, *C2;
3135 if (match(B, m_ConstantInt(C1)) &&
3136 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00003137 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003138 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00003139 return new ICmpInst(I.getPredicate(), A, Xor);
3140 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003141
Chris Lattner2188e402010-01-04 07:37:31 +00003142 // A^B == A^D -> B == D
3143 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
3144 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
3145 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
3146 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
3147 }
3148 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003149
Chris Lattner2188e402010-01-04 07:37:31 +00003150 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
3151 (A == Op0 || B == Op0)) {
3152 // A == (A^B) -> B == 0
3153 Value *OtherVal = A == Op0 ? B : A;
3154 return new ICmpInst(I.getPredicate(), OtherVal,
3155 Constant::getNullValue(A->getType()));
3156 }
3157
Chris Lattner2188e402010-01-04 07:37:31 +00003158 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00003159 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00003160 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003161 Value *X = 0, *Y = 0, *Z = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003162
Chris Lattner2188e402010-01-04 07:37:31 +00003163 if (A == C) {
3164 X = B; Y = D; Z = A;
3165 } else if (A == D) {
3166 X = B; Y = C; Z = A;
3167 } else if (B == C) {
3168 X = A; Y = D; Z = B;
3169 } else if (B == D) {
3170 X = A; Y = C; Z = B;
3171 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003172
Chris Lattner2188e402010-01-04 07:37:31 +00003173 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003174 Op1 = Builder->CreateXor(X, Y);
3175 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00003176 I.setOperand(0, Op1);
3177 I.setOperand(1, Constant::getNullValue(Op1->getType()));
3178 return &I;
3179 }
3180 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003181
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00003182 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00003183 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00003184 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00003185 if ((Op0->hasOneUse() &&
3186 match(Op0, m_ZExt(m_Value(A))) &&
3187 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
3188 (Op1->hasOneUse() &&
3189 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
3190 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00003191 APInt Pow2 = Cst1->getValue() + 1;
3192 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
3193 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
3194 return new ICmpInst(I.getPredicate(), A,
3195 Builder->CreateTrunc(B, A->getType()));
3196 }
3197
Benjamin Kramer03f3e242013-11-16 16:00:48 +00003198 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
3199 // For lshr and ashr pairs.
3200 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3201 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
3202 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3203 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
3204 unsigned TypeBits = Cst1->getBitWidth();
3205 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3206 if (ShAmt < TypeBits && ShAmt != 0) {
3207 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
3208 ? ICmpInst::ICMP_UGE
3209 : ICmpInst::ICMP_ULT;
3210 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
3211 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
3212 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
3213 }
3214 }
3215
Chris Lattner1b06c712011-04-26 20:18:20 +00003216 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
3217 // "icmp (and X, mask), cst"
3218 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00003219 if (Op0->hasOneUse() &&
3220 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
3221 m_ConstantInt(ShAmt))))) &&
3222 match(Op1, m_ConstantInt(Cst1)) &&
3223 // Only do this when A has multiple uses. This is most important to do
3224 // when it exposes other optimizations.
3225 !A->hasOneUse()) {
3226 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003227
Chris Lattner1b06c712011-04-26 20:18:20 +00003228 if (ShAmt < ASize) {
3229 APInt MaskV =
3230 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
3231 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003232
Chris Lattner1b06c712011-04-26 20:18:20 +00003233 APInt CmpV = Cst1->getValue().zext(ASize);
3234 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003235
Chris Lattner1b06c712011-04-26 20:18:20 +00003236 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
3237 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
3238 }
3239 }
Chris Lattner2188e402010-01-04 07:37:31 +00003240 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003241
Chris Lattner2188e402010-01-04 07:37:31 +00003242 {
3243 Value *X; ConstantInt *Cst;
3244 // icmp X+Cst, X
3245 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00003246 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00003247
3248 // icmp X, X+Cst
3249 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00003250 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00003251 }
3252 return Changed ? &I : 0;
3253}
3254
Chris Lattner2188e402010-01-04 07:37:31 +00003255/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
3256///
3257Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
3258 Instruction *LHSI,
3259 Constant *RHSC) {
3260 if (!isa<ConstantFP>(RHSC)) return 0;
3261 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003262
Chris Lattner2188e402010-01-04 07:37:31 +00003263 // Get the width of the mantissa. We don't want to hack on conversions that
3264 // might lose information from the integer, e.g. "i64 -> float"
3265 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
3266 if (MantissaWidth == -1) return 0; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003267
Chris Lattner2188e402010-01-04 07:37:31 +00003268 // Check to see that the input is converted from an integer type that is small
3269 // enough that preserves all bits. TODO: check here for "known" sign bits.
3270 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
3271 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003272
Chris Lattner2188e402010-01-04 07:37:31 +00003273 // If this is a uitofp instruction, we need an extra bit to hold the sign.
3274 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
3275 if (LHSUnsigned)
3276 ++InputSize;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003277
Chris Lattner2188e402010-01-04 07:37:31 +00003278 // If the conversion would lose info, don't hack on this.
3279 if ((int)InputSize > MantissaWidth)
3280 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003281
Chris Lattner2188e402010-01-04 07:37:31 +00003282 // Otherwise, we can potentially simplify the comparison. We know that it
3283 // will always come through as an integer value and we know the constant is
3284 // not a NAN (it would have been previously simplified).
3285 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00003286
Chris Lattner2188e402010-01-04 07:37:31 +00003287 ICmpInst::Predicate Pred;
3288 switch (I.getPredicate()) {
3289 default: llvm_unreachable("Unexpected predicate!");
3290 case FCmpInst::FCMP_UEQ:
3291 case FCmpInst::FCMP_OEQ:
3292 Pred = ICmpInst::ICMP_EQ;
3293 break;
3294 case FCmpInst::FCMP_UGT:
3295 case FCmpInst::FCMP_OGT:
3296 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
3297 break;
3298 case FCmpInst::FCMP_UGE:
3299 case FCmpInst::FCMP_OGE:
3300 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
3301 break;
3302 case FCmpInst::FCMP_ULT:
3303 case FCmpInst::FCMP_OLT:
3304 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
3305 break;
3306 case FCmpInst::FCMP_ULE:
3307 case FCmpInst::FCMP_OLE:
3308 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
3309 break;
3310 case FCmpInst::FCMP_UNE:
3311 case FCmpInst::FCMP_ONE:
3312 Pred = ICmpInst::ICMP_NE;
3313 break;
3314 case FCmpInst::FCMP_ORD:
Jakub Staszakbddea112013-06-06 20:18:46 +00003315 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003316 case FCmpInst::FCMP_UNO:
Jakub Staszakbddea112013-06-06 20:18:46 +00003317 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003318 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003319
Chris Lattner229907c2011-07-18 04:54:35 +00003320 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00003321
Chris Lattner2188e402010-01-04 07:37:31 +00003322 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003323
Chris Lattner2188e402010-01-04 07:37:31 +00003324 // See if the FP constant is too large for the integer. For example,
3325 // comparing an i8 to 300.0.
3326 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003327
Chris Lattner2188e402010-01-04 07:37:31 +00003328 if (!LHSUnsigned) {
3329 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
3330 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00003331 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003332 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
3333 APFloat::rmNearestTiesToEven);
3334 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
3335 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
3336 Pred == ICmpInst::ICMP_SLE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003337 return ReplaceInstUsesWith(I, Builder->getTrue());
3338 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003339 }
3340 } else {
3341 // If the RHS value is > UnsignedMax, fold the comparison. This handles
3342 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00003343 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003344 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
3345 APFloat::rmNearestTiesToEven);
3346 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
3347 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
3348 Pred == ICmpInst::ICMP_ULE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003349 return ReplaceInstUsesWith(I, Builder->getTrue());
3350 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003351 }
3352 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003353
Chris Lattner2188e402010-01-04 07:37:31 +00003354 if (!LHSUnsigned) {
3355 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00003356 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003357 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
3358 APFloat::rmNearestTiesToEven);
3359 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
3360 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
3361 Pred == ICmpInst::ICMP_SGE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003362 return ReplaceInstUsesWith(I, Builder->getTrue());
3363 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003364 }
Devang Patel698452b2012-02-13 23:05:18 +00003365 } else {
3366 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00003367 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00003368 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
3369 APFloat::rmNearestTiesToEven);
3370 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
3371 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
3372 Pred == ICmpInst::ICMP_UGE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003373 return ReplaceInstUsesWith(I, Builder->getTrue());
3374 return ReplaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00003375 }
Chris Lattner2188e402010-01-04 07:37:31 +00003376 }
3377
3378 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
3379 // [0, UMAX], but it may still be fractional. See if it is fractional by
3380 // casting the FP value to the integer value and back, checking for equality.
3381 // Don't do this for zero, because -0.0 is not fractional.
3382 Constant *RHSInt = LHSUnsigned
3383 ? ConstantExpr::getFPToUI(RHSC, IntTy)
3384 : ConstantExpr::getFPToSI(RHSC, IntTy);
3385 if (!RHS.isZero()) {
3386 bool Equal = LHSUnsigned
3387 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
3388 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
3389 if (!Equal) {
3390 // If we had a comparison against a fractional value, we have to adjust
3391 // the compare predicate and sometimes the value. RHSC is rounded towards
3392 // zero at this point.
3393 switch (Pred) {
3394 default: llvm_unreachable("Unexpected integer comparison!");
3395 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Jakub Staszakbddea112013-06-06 20:18:46 +00003396 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003397 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Jakub Staszakbddea112013-06-06 20:18:46 +00003398 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003399 case ICmpInst::ICMP_ULE:
3400 // (float)int <= 4.4 --> int <= 4
3401 // (float)int <= -4.4 --> false
3402 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003403 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003404 break;
3405 case ICmpInst::ICMP_SLE:
3406 // (float)int <= 4.4 --> int <= 4
3407 // (float)int <= -4.4 --> int < -4
3408 if (RHS.isNegative())
3409 Pred = ICmpInst::ICMP_SLT;
3410 break;
3411 case ICmpInst::ICMP_ULT:
3412 // (float)int < -4.4 --> false
3413 // (float)int < 4.4 --> int <= 4
3414 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003415 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003416 Pred = ICmpInst::ICMP_ULE;
3417 break;
3418 case ICmpInst::ICMP_SLT:
3419 // (float)int < -4.4 --> int < -4
3420 // (float)int < 4.4 --> int <= 4
3421 if (!RHS.isNegative())
3422 Pred = ICmpInst::ICMP_SLE;
3423 break;
3424 case ICmpInst::ICMP_UGT:
3425 // (float)int > 4.4 --> int > 4
3426 // (float)int > -4.4 --> true
3427 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003428 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003429 break;
3430 case ICmpInst::ICMP_SGT:
3431 // (float)int > 4.4 --> int > 4
3432 // (float)int > -4.4 --> int >= -4
3433 if (RHS.isNegative())
3434 Pred = ICmpInst::ICMP_SGE;
3435 break;
3436 case ICmpInst::ICMP_UGE:
3437 // (float)int >= -4.4 --> true
3438 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00003439 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003440 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003441 Pred = ICmpInst::ICMP_UGT;
3442 break;
3443 case ICmpInst::ICMP_SGE:
3444 // (float)int >= -4.4 --> int >= -4
3445 // (float)int >= 4.4 --> int > 4
3446 if (!RHS.isNegative())
3447 Pred = ICmpInst::ICMP_SGT;
3448 break;
3449 }
3450 }
3451 }
3452
3453 // Lower this FP comparison into an appropriate integer version of the
3454 // comparison.
3455 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
3456}
3457
3458Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
3459 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003460
Chris Lattner2188e402010-01-04 07:37:31 +00003461 /// Orders the operands of the compare so that they are listed from most
3462 /// complex to least complex. This puts constants before unary operators,
3463 /// before binary operators.
3464 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
3465 I.swapOperands();
3466 Changed = true;
3467 }
3468
3469 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003470
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003471 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, DL))
Chris Lattner2188e402010-01-04 07:37:31 +00003472 return ReplaceInstUsesWith(I, V);
3473
3474 // Simplify 'fcmp pred X, X'
3475 if (Op0 == Op1) {
3476 switch (I.getPredicate()) {
3477 default: llvm_unreachable("Unknown predicate!");
3478 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
3479 case FCmpInst::FCMP_ULT: // True if unordered or less than
3480 case FCmpInst::FCMP_UGT: // True if unordered or greater than
3481 case FCmpInst::FCMP_UNE: // True if unordered or not equal
3482 // Canonicalize these to be 'fcmp uno %X, 0.0'.
3483 I.setPredicate(FCmpInst::FCMP_UNO);
3484 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3485 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003486
Chris Lattner2188e402010-01-04 07:37:31 +00003487 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
3488 case FCmpInst::FCMP_OEQ: // True if ordered and equal
3489 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
3490 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
3491 // Canonicalize these to be 'fcmp ord %X, 0.0'.
3492 I.setPredicate(FCmpInst::FCMP_ORD);
3493 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3494 return &I;
3495 }
3496 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003497
Chris Lattner2188e402010-01-04 07:37:31 +00003498 // Handle fcmp with constant RHS
3499 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3500 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3501 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003502 case Instruction::FPExt: {
3503 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
3504 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
3505 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
3506 if (!RHSF)
3507 break;
3508
3509 const fltSemantics *Sem;
3510 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00003511 if (LHSExt->getSrcTy()->isHalfTy())
3512 Sem = &APFloat::IEEEhalf;
3513 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003514 Sem = &APFloat::IEEEsingle;
3515 else if (LHSExt->getSrcTy()->isDoubleTy())
3516 Sem = &APFloat::IEEEdouble;
3517 else if (LHSExt->getSrcTy()->isFP128Ty())
3518 Sem = &APFloat::IEEEquad;
3519 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
3520 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00003521 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
3522 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003523 else
3524 break;
3525
3526 bool Lossy;
3527 APFloat F = RHSF->getValueAPF();
3528 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
3529
Jim Grosbach24ff8342011-09-30 18:45:50 +00003530 // Avoid lossy conversions and denormals. Zero is a special case
3531 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00003532 APFloat Fabs = F;
3533 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003534 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00003535 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
3536 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00003537
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003538 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3539 ConstantFP::get(RHSC->getContext(), F));
3540 break;
3541 }
Chris Lattner2188e402010-01-04 07:37:31 +00003542 case Instruction::PHI:
3543 // Only fold fcmp into the PHI if the phi and fcmp are in the same
3544 // block. If in the same block, we're encouraging jump threading. If
3545 // not, we are just pessimizing the code by making an i1 phi.
3546 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003547 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003548 return NV;
3549 break;
3550 case Instruction::SIToFP:
3551 case Instruction::UIToFP:
3552 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
3553 return NV;
3554 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00003555 case Instruction::FSub: {
3556 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3557 Value *Op;
3558 if (match(LHSI, m_FNeg(m_Value(Op))))
3559 return new FCmpInst(I.getSwappedPredicate(), Op,
3560 ConstantExpr::getFNeg(RHSC));
3561 break;
3562 }
Dan Gohman94732022010-02-24 06:46:09 +00003563 case Instruction::Load:
3564 if (GetElementPtrInst *GEP =
3565 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3566 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3567 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3568 !cast<LoadInst>(LHSI)->isVolatile())
3569 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3570 return Res;
3571 }
3572 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00003573 case Instruction::Call: {
3574 CallInst *CI = cast<CallInst>(LHSI);
3575 LibFunc::Func Func;
3576 // Various optimization for fabs compared with zero.
Benjamin Kramer9d032422012-08-18 22:04:34 +00003577 if (RHSC->isNullValue() && CI->getCalledFunction() &&
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00003578 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3579 TLI->has(Func)) {
3580 if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3581 Func == LibFunc::fabsl) {
3582 switch (I.getPredicate()) {
3583 default: break;
3584 // fabs(x) < 0 --> false
3585 case FCmpInst::FCMP_OLT:
3586 return ReplaceInstUsesWith(I, Builder->getFalse());
3587 // fabs(x) > 0 --> x != 0
3588 case FCmpInst::FCMP_OGT:
3589 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3590 RHSC);
3591 // fabs(x) <= 0 --> x == 0
3592 case FCmpInst::FCMP_OLE:
3593 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3594 RHSC);
3595 // fabs(x) >= 0 --> !isnan(x)
3596 case FCmpInst::FCMP_OGE:
3597 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3598 RHSC);
3599 // fabs(x) == 0 --> x == 0
3600 // fabs(x) != 0 --> x != 0
3601 case FCmpInst::FCMP_OEQ:
3602 case FCmpInst::FCMP_UEQ:
3603 case FCmpInst::FCMP_ONE:
3604 case FCmpInst::FCMP_UNE:
3605 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3606 RHSC);
3607 }
3608 }
3609 }
3610 }
Chris Lattner2188e402010-01-04 07:37:31 +00003611 }
Chris Lattner2188e402010-01-04 07:37:31 +00003612 }
3613
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00003614 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00003615 Value *X, *Y;
3616 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00003617 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00003618
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00003619 // fcmp (fpext x), (fpext y) -> fcmp x, y
3620 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3621 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3622 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3623 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3624 RHSExt->getOperand(0));
3625
Chris Lattner2188e402010-01-04 07:37:31 +00003626 return Changed ? &I : 0;
3627}