blob: 3afb5ed6d8ac5de3758ffbcd63884547220c36c9 [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
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Matt Arsenault55e73122015-01-06 15:50:59 +000015#include "llvm/ADT/APSInt.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000016#include "llvm/ADT/Statistic.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000017#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2188e402010-01-04 07:37:31 +000018#include "llvm/Analysis/InstructionSimplify.h"
19#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000020#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000022#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000024#include "llvm/IR/PatternMatch.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Debug.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000027#include "llvm/Analysis/TargetLibraryInfo.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000028
Chris Lattner2188e402010-01-04 07:37:31 +000029using namespace llvm;
30using namespace PatternMatch;
31
Chandler Carruth964daaa2014-04-22 02:55:47 +000032#define DEBUG_TYPE "instcombine"
33
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000034// How many times is a select replaced by one of its operands?
35STATISTIC(NumSel, "Number of select opts");
36
37// Initialization Routines
38
Chris Lattner98457102011-02-10 05:23:05 +000039static ConstantInt *getOne(Constant *C) {
40 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
41}
42
Chris Lattner2188e402010-01-04 07:37:31 +000043static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
44 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
45}
46
47static bool HasAddOverflow(ConstantInt *Result,
48 ConstantInt *In1, ConstantInt *In2,
49 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000050 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000051 return Result->getValue().ult(In1->getValue());
Chris Lattnerb1a15122011-07-15 06:08:15 +000052
53 if (In2->isNegative())
54 return Result->getValue().sgt(In1->getValue());
55 return Result->getValue().slt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000056}
57
58/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
59/// overflowed for this type.
60static bool AddWithOverflow(Constant *&Result, Constant *In1,
61 Constant *In2, bool IsSigned = false) {
62 Result = ConstantExpr::getAdd(In1, In2);
63
Chris Lattner229907c2011-07-18 04:54:35 +000064 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000065 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
66 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
67 if (HasAddOverflow(ExtractElement(Result, Idx),
68 ExtractElement(In1, Idx),
69 ExtractElement(In2, Idx),
70 IsSigned))
71 return true;
72 }
73 return false;
74 }
75
76 return HasAddOverflow(cast<ConstantInt>(Result),
77 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
78 IsSigned);
79}
80
81static bool HasSubOverflow(ConstantInt *Result,
82 ConstantInt *In1, ConstantInt *In2,
83 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000084 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000085 return Result->getValue().ugt(In1->getValue());
Jim Grosbach129c52a2011-09-30 18:09:53 +000086
Chris Lattnerb1a15122011-07-15 06:08:15 +000087 if (In2->isNegative())
88 return Result->getValue().slt(In1->getValue());
89
90 return Result->getValue().sgt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000091}
92
93/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
94/// overflowed for this type.
95static bool SubWithOverflow(Constant *&Result, Constant *In1,
96 Constant *In2, bool IsSigned = false) {
97 Result = ConstantExpr::getSub(In1, In2);
98
Chris Lattner229907c2011-07-18 04:54:35 +000099 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +0000100 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
101 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
102 if (HasSubOverflow(ExtractElement(Result, Idx),
103 ExtractElement(In1, Idx),
104 ExtractElement(In2, Idx),
105 IsSigned))
106 return true;
107 }
108 return false;
109 }
110
111 return HasSubOverflow(cast<ConstantInt>(Result),
112 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
113 IsSigned);
114}
115
116/// isSignBitCheck - Given an exploded icmp instruction, return true if the
117/// comparison only checks the sign bit. If it only checks the sign bit, set
118/// TrueIfSigned if the result of the comparison is true when the input value is
119/// signed.
120static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
121 bool &TrueIfSigned) {
122 switch (pred) {
123 case ICmpInst::ICMP_SLT: // True if LHS s< 0
124 TrueIfSigned = true;
125 return RHS->isZero();
126 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
127 TrueIfSigned = true;
128 return RHS->isAllOnesValue();
129 case ICmpInst::ICMP_SGT: // True if LHS s> -1
130 TrueIfSigned = false;
131 return RHS->isAllOnesValue();
132 case ICmpInst::ICMP_UGT:
133 // True if LHS u> RHS and RHS == high-bit-mask - 1
134 TrueIfSigned = true;
Chris Lattnerb1a15122011-07-15 06:08:15 +0000135 return RHS->isMaxValue(true);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000136 case ICmpInst::ICMP_UGE:
Chris Lattner2188e402010-01-04 07:37:31 +0000137 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
138 TrueIfSigned = true;
139 return RHS->getValue().isSignBit();
140 default:
141 return false;
142 }
143}
144
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000145/// Returns true if the exploded icmp can be expressed as a signed comparison
146/// to zero and updates the predicate accordingly.
147/// The signedness of the comparison is preserved.
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000148static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
149 if (!ICmpInst::isSigned(pred))
150 return false;
151
152 if (RHS->isZero())
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000153 return ICmpInst::isRelational(pred);
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000154
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000155 if (RHS->isOne()) {
156 if (pred == ICmpInst::ICMP_SLT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000157 pred = ICmpInst::ICMP_SLE;
158 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000159 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000160 } else if (RHS->isAllOnesValue()) {
161 if (pred == ICmpInst::ICMP_SGT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000162 pred = ICmpInst::ICMP_SGE;
163 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000164 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000165 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000166
167 return false;
168}
169
Chris Lattner2188e402010-01-04 07:37:31 +0000170// isHighOnes - Return true if the constant is of the form 1+0+.
171// This is the same as lowones(~X).
172static bool isHighOnes(const ConstantInt *CI) {
173 return (~CI->getValue() + 1).isPowerOf2();
174}
175
Jim Grosbach129c52a2011-09-30 18:09:53 +0000176/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
Chris Lattner2188e402010-01-04 07:37:31 +0000177/// set of known zero and one bits, compute the maximum and minimum values that
178/// could have the specified known zero and known one bits, returning them in
179/// min/max.
180static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
181 const APInt& KnownOne,
182 APInt& Min, APInt& Max) {
183 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
184 KnownZero.getBitWidth() == Min.getBitWidth() &&
185 KnownZero.getBitWidth() == Max.getBitWidth() &&
186 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
187 APInt UnknownBits = ~(KnownZero|KnownOne);
188
189 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
190 // bit if it is unknown.
191 Min = KnownOne;
192 Max = KnownOne|UnknownBits;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000193
Chris Lattner2188e402010-01-04 07:37:31 +0000194 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000195 Min.setBit(Min.getBitWidth()-1);
196 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000197 }
198}
199
200// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
201// a set of known zero and one bits, compute the maximum and minimum values that
202// could have the specified known zero and known one bits, returning them in
203// min/max.
204static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
205 const APInt &KnownOne,
206 APInt &Min, APInt &Max) {
207 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
208 KnownZero.getBitWidth() == Min.getBitWidth() &&
209 KnownZero.getBitWidth() == Max.getBitWidth() &&
210 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
211 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000212
Chris Lattner2188e402010-01-04 07:37:31 +0000213 // The minimum value is when the unknown bits are all zeros.
214 Min = KnownOne;
215 // The maximum value is when the unknown bits are all ones.
216 Max = KnownOne|UnknownBits;
217}
218
Chris Lattner2188e402010-01-04 07:37:31 +0000219/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
220/// cmp pred (load (gep GV, ...)), cmpcst
221/// where GV is a global variable with a constant initializer. Try to simplify
222/// this into some simple computation that does not need the load. For example
223/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
224///
225/// If AndCst is non-null, then the loaded value is masked with that constant
226/// before doing the comparison. This handles cases like "A[i]&4 == 0".
227Instruction *InstCombiner::
228FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
229 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattnerfe741762012-01-31 02:55:06 +0000230 Constant *Init = GV->getInitializer();
231 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
Craig Topperf40110f2014-04-25 05:29:35 +0000232 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000233
Chris Lattnerfe741762012-01-31 02:55:06 +0000234 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +0000235 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000236
Chris Lattner2188e402010-01-04 07:37:31 +0000237 // There are many forms of this optimization we can handle, for now, just do
238 // the simple index into a single-dimensional array.
239 //
240 // Require: GEP GV, 0, i {{, constant indices}}
241 if (GEP->getNumOperands() < 3 ||
242 !isa<ConstantInt>(GEP->getOperand(1)) ||
243 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
244 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000245 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000246
247 // Check that indices after the variable are constants and in-range for the
248 // type they index. Collect the indices. This is typically for arrays of
249 // structs.
250 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000251
Chris Lattnerfe741762012-01-31 02:55:06 +0000252 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000253 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
254 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000255 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000256
Chris Lattner2188e402010-01-04 07:37:31 +0000257 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000258 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000259
Chris Lattner229907c2011-07-18 04:54:35 +0000260 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000261 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000262 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000263 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000264 EltTy = ATy->getElementType();
265 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000266 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000267 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000268
Chris Lattner2188e402010-01-04 07:37:31 +0000269 LaterIndices.push_back(IdxVal);
270 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000271
Chris Lattner2188e402010-01-04 07:37:31 +0000272 enum { Overdefined = -3, Undefined = -2 };
273
274 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000275
Chris Lattner2188e402010-01-04 07:37:31 +0000276 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
277 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
278 // and 87 is the second (and last) index. FirstTrueElement is -2 when
279 // undefined, otherwise set to the first true element. SecondTrueElement is
280 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
281 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
282
283 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
284 // form "i != 47 & i != 87". Same state transitions as for true elements.
285 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000286
Chris Lattner2188e402010-01-04 07:37:31 +0000287 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
288 /// define a state machine that triggers for ranges of values that the index
289 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
290 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
291 /// index in the range (inclusive). We use -2 for undefined here because we
292 /// use relative comparisons and don't want 0-1 to match -1.
293 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000294
Chris Lattner2188e402010-01-04 07:37:31 +0000295 // MagicBitvector - This is a magic bitvector where we set a bit if the
296 // comparison is true for element 'i'. If there are 64 elements or less in
297 // the array, this will fully represent all the comparison results.
298 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000299
Chris Lattner2188e402010-01-04 07:37:31 +0000300 // Scan the array and see if one of our patterns matches.
301 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000302 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
303 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000304 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000305
Chris Lattner2188e402010-01-04 07:37:31 +0000306 // If this is indexing an array of structures, get the structure element.
307 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000308 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000309
Chris Lattner2188e402010-01-04 07:37:31 +0000310 // If the element is masked, handle it.
311 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000312
Chris Lattner2188e402010-01-04 07:37:31 +0000313 // Find out if the comparison would be true or false for the i'th element.
314 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000315 CompareRHS, DL, TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000316 // If the result is undef for this element, ignore it.
317 if (isa<UndefValue>(C)) {
318 // Extend range state machines to cover this element in case there is an
319 // undef in the middle of the range.
320 if (TrueRangeEnd == (int)i-1)
321 TrueRangeEnd = i;
322 if (FalseRangeEnd == (int)i-1)
323 FalseRangeEnd = i;
324 continue;
325 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000326
Chris Lattner2188e402010-01-04 07:37:31 +0000327 // If we can't compute the result for any of the elements, we have to give
328 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000329 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000330
Chris Lattner2188e402010-01-04 07:37:31 +0000331 // Otherwise, we know if the comparison is true or false for this element,
332 // update our state machines.
333 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000334
Chris Lattner2188e402010-01-04 07:37:31 +0000335 // State machine for single/double/range index comparison.
336 if (IsTrueForElt) {
337 // Update the TrueElement state machine.
338 if (FirstTrueElement == Undefined)
339 FirstTrueElement = TrueRangeEnd = i; // First true element.
340 else {
341 // Update double-compare state machine.
342 if (SecondTrueElement == Undefined)
343 SecondTrueElement = i;
344 else
345 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000346
Chris Lattner2188e402010-01-04 07:37:31 +0000347 // Update range state machine.
348 if (TrueRangeEnd == (int)i-1)
349 TrueRangeEnd = i;
350 else
351 TrueRangeEnd = Overdefined;
352 }
353 } else {
354 // Update the FalseElement state machine.
355 if (FirstFalseElement == Undefined)
356 FirstFalseElement = FalseRangeEnd = i; // First false element.
357 else {
358 // Update double-compare state machine.
359 if (SecondFalseElement == Undefined)
360 SecondFalseElement = i;
361 else
362 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000363
Chris Lattner2188e402010-01-04 07:37:31 +0000364 // Update range state machine.
365 if (FalseRangeEnd == (int)i-1)
366 FalseRangeEnd = i;
367 else
368 FalseRangeEnd = Overdefined;
369 }
370 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000371
Chris Lattner2188e402010-01-04 07:37:31 +0000372 // If this element is in range, update our magic bitvector.
373 if (i < 64 && IsTrueForElt)
374 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000375
Chris Lattner2188e402010-01-04 07:37:31 +0000376 // If all of our states become overdefined, bail out early. Since the
377 // predicate is expensive, only check it every 8 elements. This is only
378 // really useful for really huge arrays.
379 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
380 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
381 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000382 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000383 }
384
385 // Now that we've scanned the entire array, emit our new comparison(s). We
386 // order the state machines in complexity of the generated code.
387 Value *Idx = GEP->getOperand(2);
388
Matt Arsenault5aeae182013-08-19 21:40:31 +0000389 // If the index is larger than the pointer size of the target, truncate the
390 // index down like the GEP would do implicitly. We don't have to do this for
391 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000392 if (!GEP->isInBounds()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000393 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000394 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
395 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
396 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
397 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000398
Chris Lattner2188e402010-01-04 07:37:31 +0000399 // If the comparison is only true for one or two elements, emit direct
400 // comparisons.
401 if (SecondTrueElement != Overdefined) {
402 // None true -> false.
403 if (FirstTrueElement == Undefined)
Jakub Staszakbddea112013-06-06 20:18:46 +0000404 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000405
Chris Lattner2188e402010-01-04 07:37:31 +0000406 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000407
Chris Lattner2188e402010-01-04 07:37:31 +0000408 // True for one element -> 'i == 47'.
409 if (SecondTrueElement == Undefined)
410 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000411
Chris Lattner2188e402010-01-04 07:37:31 +0000412 // True for two elements -> 'i == 47 | i == 72'.
413 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
414 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
415 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
416 return BinaryOperator::CreateOr(C1, C2);
417 }
418
419 // If the comparison is only false for one or two elements, emit direct
420 // comparisons.
421 if (SecondFalseElement != Overdefined) {
422 // None false -> true.
423 if (FirstFalseElement == Undefined)
Jakub Staszakbddea112013-06-06 20:18:46 +0000424 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000425
Chris Lattner2188e402010-01-04 07:37:31 +0000426 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
427
428 // False for one element -> 'i != 47'.
429 if (SecondFalseElement == Undefined)
430 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000431
Chris Lattner2188e402010-01-04 07:37:31 +0000432 // False for two elements -> 'i != 47 & i != 72'.
433 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
434 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
435 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
436 return BinaryOperator::CreateAnd(C1, C2);
437 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000438
Chris Lattner2188e402010-01-04 07:37:31 +0000439 // If the comparison can be replaced with a range comparison for the elements
440 // where it is true, emit the range check.
441 if (TrueRangeEnd != Overdefined) {
442 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000443
Chris Lattner2188e402010-01-04 07:37:31 +0000444 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
445 if (FirstTrueElement) {
446 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
447 Idx = Builder->CreateAdd(Idx, Offs);
448 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000449
Chris Lattner2188e402010-01-04 07:37:31 +0000450 Value *End = ConstantInt::get(Idx->getType(),
451 TrueRangeEnd-FirstTrueElement+1);
452 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
453 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000454
Chris Lattner2188e402010-01-04 07:37:31 +0000455 // False range check.
456 if (FalseRangeEnd != Overdefined) {
457 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
458 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
459 if (FirstFalseElement) {
460 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
461 Idx = Builder->CreateAdd(Idx, Offs);
462 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000463
Chris Lattner2188e402010-01-04 07:37:31 +0000464 Value *End = ConstantInt::get(Idx->getType(),
465 FalseRangeEnd-FirstFalseElement);
466 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
467 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000468
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000469 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000470 // of this load, replace it with computation that does:
471 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000472 {
Craig Topperf40110f2014-04-25 05:29:35 +0000473 Type *Ty = nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000474
475 // Look for an appropriate type:
476 // - The type of Idx if the magic fits
477 // - The smallest fitting legal type if we have a DataLayout
478 // - Default to i32
479 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
480 Ty = Idx->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000481 else
482 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000483
Craig Topperf40110f2014-04-25 05:29:35 +0000484 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000485 Value *V = Builder->CreateIntCast(Idx, Ty, false);
486 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
487 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
488 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
489 }
Chris Lattner2188e402010-01-04 07:37:31 +0000490 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000491
Craig Topperf40110f2014-04-25 05:29:35 +0000492 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000493}
494
Chris Lattner2188e402010-01-04 07:37:31 +0000495/// 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///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000505static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
506 const DataLayout &DL) {
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.
Craig Topperf40110f2014-04-25 05:29:35 +0000536 if (i == e) return nullptr;
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));
Craig Topperf40110f2014-04-25 05:29:35 +0000546 if (!CI) return nullptr;
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
Chris Lattner2188e402010-01-04 07:37:31 +0000560 // Okay, we know we have a single variable index, which must be a
561 // pointer/array/vector index. If there is no offset, life is simple, return
562 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000563 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000564 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000565 if (Offset == 0) {
566 // Cast to intptrty in case a truncation occurs. If an extension is needed,
567 // we don't need to bother extending: the extension won't affect where the
568 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000569 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000570 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
571 }
Chris Lattner2188e402010-01-04 07:37:31 +0000572 return VariableIdx;
573 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000574
Chris Lattner2188e402010-01-04 07:37:31 +0000575 // Otherwise, there is an index. The computation we will do will be modulo
576 // the pointer size, so get it.
577 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000578
Chris Lattner2188e402010-01-04 07:37:31 +0000579 Offset &= PtrSizeMask;
580 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000581
Chris Lattner2188e402010-01-04 07:37:31 +0000582 // To do this transformation, any constant index must be a multiple of the
583 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
584 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
585 // multiple of the variable scale.
586 int64_t NewOffs = Offset / (int64_t)VariableScale;
587 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000588 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000589
Chris Lattner2188e402010-01-04 07:37:31 +0000590 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000591 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000592 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
593 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000594 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000595 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000596}
597
598/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
599/// else. At this point we know that the GEP is on the LHS of the comparison.
600Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
601 ICmpInst::Predicate Cond,
602 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000603 // Don't transform signed compares of GEPs into index compares. Even if the
604 // GEP is inbounds, the final add of the base pointer can have signed overflow
605 // and would change the result of the icmp.
606 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000607 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000608 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000609 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000610
Matt Arsenault44f60d02014-06-09 19:20:29 +0000611 // Look through bitcasts and addrspacecasts. We do not however want to remove
612 // 0 GEPs.
613 if (!isa<GetElementPtrInst>(RHS))
614 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000615
616 Value *PtrBase = GEPLHS->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000617 if (PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000618 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
619 // This transformation (ignoring the base and scales) is valid because we
620 // know pointers can't overflow since the gep is inbounds. See if we can
621 // output an optimized form.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000622 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this, DL);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000623
Chris Lattner2188e402010-01-04 07:37:31 +0000624 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000625 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000626 Offset = EmitGEPOffset(GEPLHS);
627 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
628 Constant::getNullValue(Offset->getType()));
629 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
630 // If the base pointers are different, but the indices are the same, just
631 // compare the base pointer.
632 if (PtrBase != GEPRHS->getOperand(0)) {
633 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
634 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
635 GEPRHS->getOperand(0)->getType();
636 if (IndicesTheSame)
637 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
638 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
639 IndicesTheSame = false;
640 break;
641 }
642
643 // If all indices are the same, just compare the base pointers.
644 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000645 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000646
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000647 // If we're comparing GEPs with two base pointers that only differ in type
648 // and both GEPs have only constant indices or just one use, then fold
649 // the compare with the adjusted indices.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000650 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000651 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
652 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
653 PtrBase->stripPointerCasts() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000654 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000655 Value *LOffset = EmitGEPOffset(GEPLHS);
656 Value *ROffset = EmitGEPOffset(GEPRHS);
657
658 // If we looked through an addrspacecast between different sized address
659 // spaces, the LHS and RHS pointers are different sized
660 // integers. Truncate to the smaller one.
661 Type *LHSIndexTy = LOffset->getType();
662 Type *RHSIndexTy = ROffset->getType();
663 if (LHSIndexTy != RHSIndexTy) {
664 if (LHSIndexTy->getPrimitiveSizeInBits() <
665 RHSIndexTy->getPrimitiveSizeInBits()) {
666 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
667 } else
668 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
669 }
670
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000671 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000672 LOffset, ROffset);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000673 return ReplaceInstUsesWith(I, Cmp);
674 }
675
Chris Lattner2188e402010-01-04 07:37:31 +0000676 // Otherwise, the base pointers are different and the indices are
677 // different, bail out.
Craig Topperf40110f2014-04-25 05:29:35 +0000678 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000679 }
680
681 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +0000682 if (GEPLHS->hasAllZeroIndices())
Chris Lattner2188e402010-01-04 07:37:31 +0000683 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +0000684 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +0000685
686 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +0000687 if (GEPRHS->hasAllZeroIndices())
Chris Lattner2188e402010-01-04 07:37:31 +0000688 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!
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000722 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner2188e402010-01-04 07:37:31 +0000723 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
724 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
725 Value *L = EmitGEPOffset(GEPLHS);
726 Value *R = EmitGEPOffset(GEPRHS);
727 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
728 }
729 }
Craig Topperf40110f2014-04-25 05:29:35 +0000730 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000731}
732
733/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
Benjamin Kramer0e2d1622013-09-20 22:12:42 +0000734Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
Chris Lattner2188e402010-01-04 07:37:31 +0000735 Value *X, ConstantInt *CI,
Benjamin Kramer0e2d1622013-09-20 22:12:42 +0000736 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +0000737 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000738 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +0000739 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000740
Chris Lattner8c92b572010-01-08 17:48:19 +0000741 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +0000742 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
743 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
744 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +0000745 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +0000746 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +0000747 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
748 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000749
Chris Lattner2188e402010-01-04 07:37:31 +0000750 // (X+1) >u X --> X <u (0-1) --> X != 255
751 // (X+2) >u X --> X <u (0-2) --> X <u 254
752 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +0000753 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +0000754 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000755
Chris Lattner2188e402010-01-04 07:37:31 +0000756 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
757 ConstantInt *SMax = ConstantInt::get(X->getContext(),
758 APInt::getSignedMaxValue(BitWidth));
759
760 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
761 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
762 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
763 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
764 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
765 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +0000766 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +0000767 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000768
Chris Lattner2188e402010-01-04 07:37:31 +0000769 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
770 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
771 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
772 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
773 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
774 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +0000775
Chris Lattner2188e402010-01-04 07:37:31 +0000776 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +0000777 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000778 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
779}
780
781/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
782/// and CmpRHS are both known to be integer constants.
783Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
784 ConstantInt *DivRHS) {
785 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
786 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000787
788 // FIXME: If the operand types don't match the type of the divide
Chris Lattner2188e402010-01-04 07:37:31 +0000789 // then don't attempt this transform. The code below doesn't have the
790 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach129c52a2011-09-30 18:09:53 +0000791 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner2188e402010-01-04 07:37:31 +0000792 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach129c52a2011-09-30 18:09:53 +0000793 // (x /u C1) <u C2. Simply casting the operands and result won't
794 // work. :( The if statement below tests that condition and bails
Chris Lattner98457102011-02-10 05:23:05 +0000795 // if it finds it.
Chris Lattner2188e402010-01-04 07:37:31 +0000796 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
797 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Craig Topperf40110f2014-04-25 05:29:35 +0000798 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000799 if (DivRHS->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000800 return nullptr; // The ProdOV computation fails on divide by zero.
Chris Lattner2188e402010-01-04 07:37:31 +0000801 if (DivIsSigned && DivRHS->isAllOnesValue())
Craig Topperf40110f2014-04-25 05:29:35 +0000802 return nullptr; // The overflow computation also screws up here
Chris Lattner43273af2011-02-13 08:07:21 +0000803 if (DivRHS->isOne()) {
804 // This eliminates some funny cases with INT_MIN.
805 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
806 return &ICI;
807 }
Chris Lattner2188e402010-01-04 07:37:31 +0000808
809 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach129c52a2011-09-30 18:09:53 +0000810 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
811 // C2 (CI). By solving for X we can turn this into a range check
812 // instead of computing a divide.
Chris Lattner2188e402010-01-04 07:37:31 +0000813 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
814
815 // Determine if the product overflows by seeing if the product is
816 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach129c52a2011-09-30 18:09:53 +0000817 // as in the LHS instruction that we're folding.
Chris Lattner2188e402010-01-04 07:37:31 +0000818 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
819 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
820
821 // Get the ICmp opcode
822 ICmpInst::Predicate Pred = ICI.getPredicate();
823
Chris Lattner98457102011-02-10 05:23:05 +0000824 /// If the division is known to be exact, then there is no remainder from the
825 /// divide, so the covered range size is unit, otherwise it is the divisor.
826 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000827
Chris Lattner2188e402010-01-04 07:37:31 +0000828 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach129c52a2011-09-30 18:09:53 +0000829 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner2188e402010-01-04 07:37:31 +0000830 // Compute this interval based on the constants involved and the signedness of
831 // the compare/divide. This computes a half-open interval, keeping track of
832 // whether either value in the interval overflows. After analysis each
833 // overflow variable is set to 0 if it's corresponding bound variable is valid
834 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
835 int LoOverflow = 0, HiOverflow = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000836 Constant *LoBound = nullptr, *HiBound = nullptr;
Chris Lattner98457102011-02-10 05:23:05 +0000837
Chris Lattner2188e402010-01-04 07:37:31 +0000838 if (!DivIsSigned) { // udiv
839 // e.g. X/5 op 3 --> [15, 20)
840 LoBound = Prod;
841 HiOverflow = LoOverflow = ProdOV;
Chris Lattner98457102011-02-10 05:23:05 +0000842 if (!HiOverflow) {
843 // If this is not an exact divide, then many values in the range collapse
844 // to the same result value.
845 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
846 }
Chris Lattner2188e402010-01-04 07:37:31 +0000847 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
848 if (CmpRHSV == 0) { // (X / pos) op 0
849 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner98457102011-02-10 05:23:05 +0000850 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
851 HiBound = RangeSize;
Chris Lattner2188e402010-01-04 07:37:31 +0000852 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
853 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
854 HiOverflow = LoOverflow = ProdOV;
855 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000856 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +0000857 } else { // (X / pos) op neg
858 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
859 HiBound = AddOne(Prod);
860 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
861 if (!LoOverflow) {
Chris Lattner98457102011-02-10 05:23:05 +0000862 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000863 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattner98457102011-02-10 05:23:05 +0000864 }
Chris Lattner2188e402010-01-04 07:37:31 +0000865 }
Chris Lattnerb1a15122011-07-15 06:08:15 +0000866 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattner98457102011-02-10 05:23:05 +0000867 if (DivI->isExact())
868 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000869 if (CmpRHSV == 0) { // (X / neg) op 0
870 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner98457102011-02-10 05:23:05 +0000871 LoBound = AddOne(RangeSize);
872 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000873 if (HiBound == DivRHS) { // -INTMIN = INTMIN
874 HiOverflow = 1; // [INTMIN+1, overflow)
Craig Topperf40110f2014-04-25 05:29:35 +0000875 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
Chris Lattner2188e402010-01-04 07:37:31 +0000876 }
877 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
878 // e.g. X/-5 op 3 --> [-19, -14)
879 HiBound = AddOne(Prod);
880 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
881 if (!LoOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000882 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner2188e402010-01-04 07:37:31 +0000883 } else { // (X / neg) op neg
884 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
885 LoOverflow = HiOverflow = ProdOV;
886 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000887 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +0000888 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000889
Chris Lattner2188e402010-01-04 07:37:31 +0000890 // Dividing by a negative swaps the condition. LT <-> GT
891 Pred = ICmpInst::getSwappedPredicate(Pred);
892 }
893
894 Value *X = DivI->getOperand(0);
895 switch (Pred) {
896 default: llvm_unreachable("Unhandled icmp opcode!");
897 case ICmpInst::ICMP_EQ:
898 if (LoOverflow && HiOverflow)
Jakub Staszakbddea112013-06-06 20:18:46 +0000899 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner067459c2010-03-05 08:46:26 +0000900 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000901 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
902 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000903 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000904 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
905 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +0000906 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
907 DivIsSigned, true));
Chris Lattner2188e402010-01-04 07:37:31 +0000908 case ICmpInst::ICMP_NE:
909 if (LoOverflow && HiOverflow)
Jakub Staszakbddea112013-06-06 20:18:46 +0000910 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner067459c2010-03-05 08:46:26 +0000911 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000912 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
913 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000914 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000915 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
916 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000917 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
918 DivIsSigned, false));
Chris Lattner2188e402010-01-04 07:37:31 +0000919 case ICmpInst::ICMP_ULT:
920 case ICmpInst::ICMP_SLT:
921 if (LoOverflow == +1) // Low bound is greater than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000922 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +0000923 if (LoOverflow == -1) // Low bound is less than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000924 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +0000925 return new ICmpInst(Pred, X, LoBound);
926 case ICmpInst::ICMP_UGT:
927 case ICmpInst::ICMP_SGT:
928 if (HiOverflow == +1) // High bound greater than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000929 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner98457102011-02-10 05:23:05 +0000930 if (HiOverflow == -1) // High bound less than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000931 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +0000932 if (Pred == ICmpInst::ICMP_UGT)
933 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +0000934 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner2188e402010-01-04 07:37:31 +0000935 }
936}
937
Chris Lattnerd369f572011-02-13 07:43:07 +0000938/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
939Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
940 ConstantInt *ShAmt) {
Chris Lattnerd369f572011-02-13 07:43:07 +0000941 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000942
Chris Lattnerd369f572011-02-13 07:43:07 +0000943 // Check that the shift amount is in range. If not, don't perform
944 // undefined shifts. When the shift is visited it will be
945 // simplified.
946 uint32_t TypeBits = CmpRHSV.getBitWidth();
947 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner43273af2011-02-13 08:07:21 +0000948 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000949 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000950
Chris Lattner43273af2011-02-13 08:07:21 +0000951 if (!ICI.isEquality()) {
952 // If we have an unsigned comparison and an ashr, we can't simplify this.
953 // Similarly for signed comparisons with lshr.
954 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
Craig Topperf40110f2014-04-25 05:29:35 +0000955 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000956
Eli Friedman865866e2011-05-25 23:26:20 +0000957 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
958 // by a power of 2. Since we already have logic to simplify these,
959 // transform to div and then simplify the resultant comparison.
Chris Lattner43273af2011-02-13 08:07:21 +0000960 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedman865866e2011-05-25 23:26:20 +0000961 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Craig Topperf40110f2014-04-25 05:29:35 +0000962 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000963
Chris Lattner43273af2011-02-13 08:07:21 +0000964 // Revisit the shift (to delete it).
965 Worklist.Add(Shr);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000966
Chris Lattner43273af2011-02-13 08:07:21 +0000967 Constant *DivCst =
968 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000969
Chris Lattner43273af2011-02-13 08:07:21 +0000970 Value *Tmp =
971 Shr->getOpcode() == Instruction::AShr ?
972 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
973 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000974
Chris Lattner43273af2011-02-13 08:07:21 +0000975 ICI.setOperand(0, Tmp);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000976
Chris Lattner43273af2011-02-13 08:07:21 +0000977 // If the builder folded the binop, just return it.
978 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
Craig Topperf40110f2014-04-25 05:29:35 +0000979 if (!TheDiv)
Chris Lattner43273af2011-02-13 08:07:21 +0000980 return &ICI;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000981
Chris Lattner43273af2011-02-13 08:07:21 +0000982 // Otherwise, fold this div/compare.
983 assert(TheDiv->getOpcode() == Instruction::SDiv ||
984 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000985
Chris Lattner43273af2011-02-13 08:07:21 +0000986 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
987 assert(Res && "This div/cst should have folded!");
988 return Res;
989 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000990
Chris Lattnerd369f572011-02-13 07:43:07 +0000991 // If we are comparing against bits always shifted out, the
992 // comparison cannot succeed.
993 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszakbddea112013-06-06 20:18:46 +0000994 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattnerd369f572011-02-13 07:43:07 +0000995 if (Shr->getOpcode() == Instruction::LShr)
996 Comp = Comp.lshr(ShAmtVal);
997 else
998 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000999
Chris Lattnerd369f572011-02-13 07:43:07 +00001000 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1001 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001002 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattnerd369f572011-02-13 07:43:07 +00001003 return ReplaceInstUsesWith(ICI, Cst);
1004 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001005
Chris Lattnerd369f572011-02-13 07:43:07 +00001006 // Otherwise, check to see if the bits shifted out are known to be zero.
1007 // If so, we can compare against the unshifted value:
1008 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattner9bd7fdf2011-02-13 18:30:09 +00001009 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattnerd369f572011-02-13 07:43:07 +00001010 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001011
Chris Lattnerd369f572011-02-13 07:43:07 +00001012 if (Shr->hasOneUse()) {
1013 // Otherwise strength reduce the shift into an and.
1014 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszakbddea112013-06-06 20:18:46 +00001015 Constant *Mask = Builder->getInt(Val);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001016
Chris Lattnerd369f572011-02-13 07:43:07 +00001017 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1018 Mask, Shr->getName()+".mask");
1019 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1020 }
Craig Topperf40110f2014-04-25 05:29:35 +00001021 return nullptr;
Chris Lattnerd369f572011-02-13 07:43:07 +00001022}
1023
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001024/// FoldICmpCstShrCst - Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
1025/// (icmp eq/ne A, Log2(const2/const1)) ->
1026/// (icmp eq/ne A, Log2(const2) - Log2(const1)).
1027Instruction *InstCombiner::FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
1028 ConstantInt *CI1,
1029 ConstantInt *CI2) {
1030 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1031
1032 auto getConstant = [&I, this](bool IsTrue) {
1033 if (I.getPredicate() == I.ICMP_NE)
1034 IsTrue = !IsTrue;
1035 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
1036 };
1037
1038 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1039 if (I.getPredicate() == I.ICMP_NE)
1040 Pred = CmpInst::getInversePredicate(Pred);
1041 return new ICmpInst(Pred, LHS, RHS);
1042 };
1043
1044 APInt AP1 = CI1->getValue();
1045 APInt AP2 = CI2->getValue();
1046
David Majnemer2abb8182014-10-25 07:13:13 +00001047 // Don't bother doing any work for cases which InstSimplify handles.
1048 if (AP2 == 0)
1049 return nullptr;
1050 bool IsAShr = isa<AShrOperator>(Op);
1051 if (IsAShr) {
1052 if (AP2.isAllOnesValue())
1053 return nullptr;
1054 if (AP2.isNegative() != AP1.isNegative())
1055 return nullptr;
1056 if (AP2.sgt(AP1))
1057 return nullptr;
1058 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001059
David Majnemerd2056022014-10-21 19:51:55 +00001060 if (!AP1)
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001061 // 'A' must be large enough to shift out the highest set bit.
1062 return getICmp(I.ICMP_UGT, A,
1063 ConstantInt::get(A->getType(), AP2.logBase2()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001064
David Majnemerd2056022014-10-21 19:51:55 +00001065 if (AP1 == AP2)
1066 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001067
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001068 int Shift;
David Majnemerd2056022014-10-21 19:51:55 +00001069 if (IsAShr && AP1.isNegative())
David Majnemere5977eb2015-09-19 00:48:26 +00001070 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001071 else
David Majnemere5977eb2015-09-19 00:48:26 +00001072 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001073
David Majnemerd2056022014-10-21 19:51:55 +00001074 if (Shift > 0) {
David Majnemere5977eb2015-09-19 00:48:26 +00001075 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1076 // There are multiple solutions if we are comparing against -1 and the LHS
David Majnemer47ce0b82015-09-19 00:48:31 +00001077 // of the ashr is not a power of two.
David Majnemere5977eb2015-09-19 00:48:26 +00001078 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1079 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
David Majnemerd2056022014-10-21 19:51:55 +00001080 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
David Majnemere5977eb2015-09-19 00:48:26 +00001081 } else if (AP1 == AP2.lshr(Shift)) {
1082 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1083 }
David Majnemerd2056022014-10-21 19:51:55 +00001084 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001085 // Shifting const2 will never be equal to const1.
1086 return getConstant(false);
1087}
Chris Lattner2188e402010-01-04 07:37:31 +00001088
David Majnemer59939ac2014-10-19 08:23:08 +00001089/// FoldICmpCstShlCst - Handle "(icmp eq/ne (shl const2, A), const1)" ->
1090/// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)).
1091Instruction *InstCombiner::FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
1092 ConstantInt *CI1,
1093 ConstantInt *CI2) {
1094 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1095
1096 auto getConstant = [&I, this](bool IsTrue) {
1097 if (I.getPredicate() == I.ICMP_NE)
1098 IsTrue = !IsTrue;
1099 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
1100 };
1101
1102 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1103 if (I.getPredicate() == I.ICMP_NE)
1104 Pred = CmpInst::getInversePredicate(Pred);
1105 return new ICmpInst(Pred, LHS, RHS);
1106 };
1107
1108 APInt AP1 = CI1->getValue();
1109 APInt AP2 = CI2->getValue();
1110
David Majnemer2abb8182014-10-25 07:13:13 +00001111 // Don't bother doing any work for cases which InstSimplify handles.
1112 if (AP2 == 0)
1113 return nullptr;
David Majnemer59939ac2014-10-19 08:23:08 +00001114
1115 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1116
1117 if (!AP1 && AP2TrailingZeros != 0)
1118 return getICmp(I.ICMP_UGE, A,
1119 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1120
1121 if (AP1 == AP2)
1122 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1123
1124 // Get the distance between the lowest bits that are set.
1125 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1126
1127 if (Shift > 0 && AP2.shl(Shift) == AP1)
1128 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1129
1130 // Shifting const2 will never be equal to const1.
1131 return getConstant(false);
1132}
1133
Chris Lattner2188e402010-01-04 07:37:31 +00001134/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1135///
1136Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1137 Instruction *LHSI,
1138 ConstantInt *RHS) {
1139 const APInt &RHSV = RHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001140
Chris Lattner2188e402010-01-04 07:37:31 +00001141 switch (LHSI->getOpcode()) {
1142 case Instruction::Trunc:
Sanjoy Dase5f48892015-09-16 20:41:29 +00001143 if (RHS->isOne() && RHSV.getBitWidth() > 1) {
1144 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1145 Value *V = nullptr;
1146 if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1147 match(LHSI->getOperand(0), m_Signum(m_Value(V))))
1148 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1149 ConstantInt::get(V->getType(), 1));
1150 }
Chris Lattner2188e402010-01-04 07:37:31 +00001151 if (ICI.isEquality() && LHSI->hasOneUse()) {
1152 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1153 // of the high bits truncated out of x are known.
1154 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1155 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner2188e402010-01-04 07:37:31 +00001156 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001157 computeKnownBits(LHSI->getOperand(0), KnownZero, KnownOne, 0, &ICI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001158
Chris Lattner2188e402010-01-04 07:37:31 +00001159 // If all the high bits are known, we can do this xform.
1160 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1161 // Pull in the high bits from known-ones set.
Jay Foad583abbc2010-12-07 08:25:19 +00001162 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedmane0a64d82012-05-11 01:32:59 +00001163 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner2188e402010-01-04 07:37:31 +00001164 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001165 Builder->getInt(NewRHS));
Chris Lattner2188e402010-01-04 07:37:31 +00001166 }
1167 }
1168 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001169
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001170 case Instruction::Xor: // (icmp pred (xor X, XorCst), CI)
1171 if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001172 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1173 // fold the xor.
1174 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1175 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1176 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001177
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001178 // If the sign bit of the XorCst is not set, there is no change to
Chris Lattner2188e402010-01-04 07:37:31 +00001179 // the operation, just stop using the Xor.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001180 if (!XorCst->isNegative()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001181 ICI.setOperand(0, CompareVal);
1182 Worklist.Add(LHSI);
1183 return &ICI;
1184 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001185
Chris Lattner2188e402010-01-04 07:37:31 +00001186 // Was the old condition true if the operand is positive?
1187 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001188
Chris Lattner2188e402010-01-04 07:37:31 +00001189 // If so, the new one isn't.
1190 isTrueIfPositive ^= true;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001191
Chris Lattner2188e402010-01-04 07:37:31 +00001192 if (isTrueIfPositive)
1193 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1194 SubOne(RHS));
1195 else
1196 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1197 AddOne(RHS));
1198 }
1199
1200 if (LHSI->hasOneUse()) {
1201 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001202 if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1203 const APInt &SignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001204 ICmpInst::Predicate Pred = ICI.isSigned()
1205 ? ICI.getUnsignedPredicate()
1206 : ICI.getSignedPredicate();
1207 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001208 Builder->getInt(RHSV ^ SignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001209 }
1210
1211 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001212 if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1213 const APInt &NotSignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001214 ICmpInst::Predicate Pred = ICI.isSigned()
1215 ? ICI.getUnsignedPredicate()
1216 : ICI.getSignedPredicate();
1217 Pred = ICI.getSwappedPredicate(Pred);
1218 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001219 Builder->getInt(RHSV ^ NotSignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001220 }
1221 }
David Majnemer72d76272013-07-09 09:20:58 +00001222
1223 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1224 // iff -C is a power of 2
1225 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001226 XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1227 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
David Majnemer72d76272013-07-09 09:20:58 +00001228
1229 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1230 // iff -C is a power of 2
1231 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001232 XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1233 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001234 }
1235 break;
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001236 case Instruction::And: // (icmp pred (and X, AndCst), RHS)
Chris Lattner2188e402010-01-04 07:37:31 +00001237 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1238 LHSI->getOperand(0)->hasOneUse()) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001239 ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001240
Chris Lattner2188e402010-01-04 07:37:31 +00001241 // If the LHS is an AND of a truncating cast, we can widen the
1242 // and/compare to be the input width without changing the value
1243 // produced, eliminating a cast.
1244 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1245 // We can do this transformation if either the AND constant does not
Jim Grosbach129c52a2011-09-30 18:09:53 +00001246 // have its sign bit set or if it is an equality comparison.
Chris Lattner2188e402010-01-04 07:37:31 +00001247 // Extending a relational comparison when we're checking the sign
1248 // bit would not work.
Benjamin Kramer35159c12011-06-12 22:47:53 +00001249 if (ICI.isEquality() ||
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001250 (!AndCst->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer35159c12011-06-12 22:47:53 +00001251 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001252 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001253 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
Benjamin Kramer35159c12011-06-12 22:47:53 +00001254 NewAnd->takeName(LHSI);
Chris Lattner2188e402010-01-04 07:37:31 +00001255 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer35159c12011-06-12 22:47:53 +00001256 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner2188e402010-01-04 07:37:31 +00001257 }
1258 }
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001259
1260 // If the LHS is an AND of a zext, and we have an equality compare, we can
1261 // shrink the and/compare to the smaller type, eliminating the cast.
1262 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattner229907c2011-07-18 04:54:35 +00001263 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001264 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1265 // should fold the icmp to true/false in that case.
1266 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1267 Value *NewAnd =
1268 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001269 ConstantExpr::getTrunc(AndCst, Ty));
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001270 NewAnd->takeName(LHSI);
1271 return new ICmpInst(ICI.getPredicate(), NewAnd,
1272 ConstantExpr::getTrunc(RHS, Ty));
1273 }
1274 }
1275
Chris Lattner2188e402010-01-04 07:37:31 +00001276 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1277 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1278 // happens a LOT in code produced by the C front-end, for bitfield
1279 // access.
1280 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1281 if (Shift && !Shift->isShift())
Craig Topperf40110f2014-04-25 05:29:35 +00001282 Shift = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001283
Chris Lattner2188e402010-01-04 07:37:31 +00001284 ConstantInt *ShAmt;
Craig Topperf40110f2014-04-25 05:29:35 +00001285 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001286
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001287 // This seemingly simple opportunity to fold away a shift turns out to
1288 // be rather complicated. See PR17827
1289 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
Chris Lattner2188e402010-01-04 07:37:31 +00001290 if (ShAmt) {
Kay Tiong Khoo5389f742013-12-02 18:43:59 +00001291 bool CanFold = false;
1292 unsigned ShiftOpcode = Shift->getOpcode();
1293 if (ShiftOpcode == Instruction::AShr) {
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001294 // There may be some constraints that make this possible,
1295 // but nothing simple has been discovered yet.
1296 CanFold = false;
1297 } else if (ShiftOpcode == Instruction::Shl) {
1298 // For a left shift, we can fold if the comparison is not signed.
1299 // We can also fold a signed comparison if the mask value and
1300 // comparison value are not negative. These constraints may not be
1301 // obvious, but we can prove that they are correct using an SMT
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001302 // solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001303 if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
Chris Lattner2188e402010-01-04 07:37:31 +00001304 CanFold = true;
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001305 } else if (ShiftOpcode == Instruction::LShr) {
1306 // For a logical right shift, we can fold if the comparison is not
1307 // signed. We can also fold a signed comparison if the shifted mask
1308 // value and the shifted comparison value are not negative.
1309 // These constraints may not be obvious, but we can prove that they
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001310 // are correct using an SMT solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001311 if (!ICI.isSigned())
1312 CanFold = true;
1313 else {
1314 ConstantInt *ShiftedAndCst =
1315 cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1316 ConstantInt *ShiftedRHSCst =
1317 cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1318
1319 if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1320 CanFold = true;
1321 }
Chris Lattner2188e402010-01-04 07:37:31 +00001322 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001323
Chris Lattner2188e402010-01-04 07:37:31 +00001324 if (CanFold) {
1325 Constant *NewCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001326 if (ShiftOpcode == Instruction::Shl)
Chris Lattner2188e402010-01-04 07:37:31 +00001327 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1328 else
1329 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001330
Chris Lattner2188e402010-01-04 07:37:31 +00001331 // Check to see if we are shifting out any of the bits being
1332 // compared.
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001333 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001334 // If we shifted bits out, the fold is not going to work out.
1335 // As a special case, check to see if this means that the
1336 // result is always true or false now.
1337 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Jakub Staszakbddea112013-06-06 20:18:46 +00001338 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001339 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Jakub Staszakbddea112013-06-06 20:18:46 +00001340 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001341 } else {
1342 ICI.setOperand(1, NewCst);
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001343 Constant *NewAndCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001344 if (ShiftOpcode == Instruction::Shl)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001345 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
Chris Lattner2188e402010-01-04 07:37:31 +00001346 else
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001347 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1348 LHSI->setOperand(1, NewAndCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001349 LHSI->setOperand(0, Shift->getOperand(0));
1350 Worklist.Add(Shift); // Shift is dead.
1351 return &ICI;
1352 }
1353 }
1354 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001355
Chris Lattner2188e402010-01-04 07:37:31 +00001356 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1357 // preferable because it allows the C<<Y expression to be hoisted out
1358 // of a loop if Y is invariant and X is not.
1359 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1360 ICI.isEquality() && !Shift->isArithmeticShift() &&
1361 !isa<Constant>(Shift->getOperand(0))) {
1362 // Compute C << Y.
1363 Value *NS;
1364 if (Shift->getOpcode() == Instruction::LShr) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001365 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001366 } else {
1367 // Insert a logical shift.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001368 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001369 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001370
Chris Lattner2188e402010-01-04 07:37:31 +00001371 // Compute X & (C << Y).
Jim Grosbach129c52a2011-09-30 18:09:53 +00001372 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001373 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001374
Chris Lattner2188e402010-01-04 07:37:31 +00001375 ICI.setOperand(0, NewAnd);
1376 return &ICI;
1377 }
Paul Redmond5917f4c2012-12-19 19:47:13 +00001378
David Majnemer0ffccf72014-08-24 09:10:57 +00001379 // (icmp pred (and (or (lshr X, Y), X), 1), 0) -->
1380 // (icmp pred (and X, (or (shl 1, Y), 1), 0))
1381 //
1382 // iff pred isn't signed
1383 {
1384 Value *X, *Y, *LShr;
1385 if (!ICI.isSigned() && RHSV == 0) {
1386 if (match(LHSI->getOperand(1), m_One())) {
1387 Constant *One = cast<Constant>(LHSI->getOperand(1));
1388 Value *Or = LHSI->getOperand(0);
1389 if (match(Or, m_Or(m_Value(LShr), m_Value(X))) &&
1390 match(LShr, m_LShr(m_Specific(X), m_Value(Y)))) {
1391 unsigned UsesRemoved = 0;
1392 if (LHSI->hasOneUse())
1393 ++UsesRemoved;
1394 if (Or->hasOneUse())
1395 ++UsesRemoved;
1396 if (LShr->hasOneUse())
1397 ++UsesRemoved;
1398 Value *NewOr = nullptr;
1399 // Compute X & ((1 << Y) | 1)
1400 if (auto *C = dyn_cast<Constant>(Y)) {
1401 if (UsesRemoved >= 1)
1402 NewOr =
1403 ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1404 } else {
1405 if (UsesRemoved >= 3)
1406 NewOr = Builder->CreateOr(Builder->CreateShl(One, Y,
1407 LShr->getName(),
1408 /*HasNUW=*/true),
1409 One, Or->getName());
1410 }
1411 if (NewOr) {
1412 Value *NewAnd = Builder->CreateAnd(X, NewOr, LHSI->getName());
1413 ICI.setOperand(0, NewAnd);
1414 return &ICI;
1415 }
1416 }
1417 }
1418 }
1419 }
1420
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001421 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1422 // bit set in (X & AndCst) will produce a result greater than RHSV.
Paul Redmond5917f4c2012-12-19 19:47:13 +00001423 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001424 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1425 if ((NTZ < AndCst->getBitWidth()) &&
1426 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
Paul Redmond5917f4c2012-12-19 19:47:13 +00001427 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1428 Constant::getNullValue(RHS->getType()));
1429 }
Chris Lattner2188e402010-01-04 07:37:31 +00001430 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001431
Chris Lattner2188e402010-01-04 07:37:31 +00001432 // Try to optimize things like "A[i]&42 == 0" to index computations.
1433 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1434 if (GetElementPtrInst *GEP =
1435 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1436 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1437 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1438 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1439 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1440 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1441 return Res;
1442 }
1443 }
David Majnemer414d4e52013-07-09 08:09:32 +00001444
1445 // X & -C == -C -> X > u ~C
1446 // X & -C != -C -> X <= u ~C
1447 // iff C is a power of 2
1448 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1449 return new ICmpInst(
1450 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1451 : ICmpInst::ICMP_ULE,
1452 LHSI->getOperand(0), SubOne(RHS));
David Majnemerdfa3b092015-08-16 07:09:17 +00001453
1454 // (icmp eq (and %A, C), 0) -> (icmp sgt (trunc %A), -1)
1455 // iff C is a power of 2
1456 if (ICI.isEquality() && LHSI->hasOneUse() && match(RHS, m_Zero())) {
1457 if (auto *CI = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1458 const APInt &AI = CI->getValue();
1459 int32_t ExactLogBase2 = AI.exactLogBase2();
1460 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1461 Type *NTy = IntegerType::get(ICI.getContext(), ExactLogBase2 + 1);
1462 Value *Trunc = Builder->CreateTrunc(LHSI->getOperand(0), NTy);
1463 return new ICmpInst(ICI.getPredicate() == ICmpInst::ICMP_EQ
1464 ? ICmpInst::ICMP_SGE
1465 : ICmpInst::ICMP_SLT,
1466 Trunc, Constant::getNullValue(NTy));
1467 }
1468 }
1469 }
Chris Lattner2188e402010-01-04 07:37:31 +00001470 break;
1471
1472 case Instruction::Or: {
Sanjoy Dase5f48892015-09-16 20:41:29 +00001473 if (RHS->isOne()) {
1474 // icmp slt signum(V) 1 --> icmp slt V, 1
1475 Value *V = nullptr;
1476 if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1477 match(LHSI, m_Signum(m_Value(V))))
1478 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1479 ConstantInt::get(V->getType(), 1));
1480 }
1481
Chris Lattner2188e402010-01-04 07:37:31 +00001482 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1483 break;
1484 Value *P, *Q;
1485 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1486 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1487 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner2188e402010-01-04 07:37:31 +00001488 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1489 Constant::getNullValue(P->getType()));
1490 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1491 Constant::getNullValue(Q->getType()));
1492 Instruction *Op;
1493 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1494 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1495 else
1496 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1497 return Op;
1498 }
1499 break;
1500 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001501
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001502 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1503 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1504 if (!Val) break;
1505
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001506 // If this is a signed comparison to 0 and the mul is sign preserving,
1507 // use the mul LHS operand instead.
1508 ICmpInst::Predicate pred = ICI.getPredicate();
1509 if (isSignTest(pred, RHS) && !Val->isZero() &&
1510 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1511 return new ICmpInst(Val->isNegative() ?
1512 ICmpInst::getSwappedPredicate(pred) : pred,
1513 LHSI->getOperand(0),
1514 Constant::getNullValue(RHS->getType()));
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001515
1516 break;
1517 }
1518
Chris Lattner2188e402010-01-04 07:37:31 +00001519 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
Chris Lattner2188e402010-01-04 07:37:31 +00001520 uint32_t TypeBits = RHSV.getBitWidth();
David Majnemerb889e402013-06-28 23:42:03 +00001521 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1522 if (!ShAmt) {
1523 Value *X;
1524 // (1 << X) pred P2 -> X pred Log2(P2)
1525 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1526 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1527 ICmpInst::Predicate Pred = ICI.getPredicate();
1528 if (ICI.isUnsigned()) {
1529 if (!RHSVIsPowerOf2) {
1530 // (1 << X) < 30 -> X <= 4
1531 // (1 << X) <= 30 -> X <= 4
1532 // (1 << X) >= 30 -> X > 4
1533 // (1 << X) > 30 -> X > 4
1534 if (Pred == ICmpInst::ICMP_ULT)
1535 Pred = ICmpInst::ICMP_ULE;
1536 else if (Pred == ICmpInst::ICMP_UGE)
1537 Pred = ICmpInst::ICMP_UGT;
1538 }
1539 unsigned RHSLog2 = RHSV.logBase2();
1540
1541 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
David Majnemerb889e402013-06-28 23:42:03 +00001542 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1543 if (RHSLog2 == TypeBits-1) {
1544 if (Pred == ICmpInst::ICMP_UGE)
1545 Pred = ICmpInst::ICMP_EQ;
David Majnemerb889e402013-06-28 23:42:03 +00001546 else if (Pred == ICmpInst::ICMP_ULT)
1547 Pred = ICmpInst::ICMP_NE;
1548 }
1549
1550 return new ICmpInst(Pred, X,
1551 ConstantInt::get(RHS->getType(), RHSLog2));
1552 } else if (ICI.isSigned()) {
1553 if (RHSV.isAllOnesValue()) {
1554 // (1 << X) <= -1 -> X == 31
1555 if (Pred == ICmpInst::ICMP_SLE)
1556 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1557 ConstantInt::get(RHS->getType(), TypeBits-1));
1558
1559 // (1 << X) > -1 -> X != 31
1560 if (Pred == ICmpInst::ICMP_SGT)
1561 return new ICmpInst(ICmpInst::ICMP_NE, X,
1562 ConstantInt::get(RHS->getType(), TypeBits-1));
1563 } else if (!RHSV) {
1564 // (1 << X) < 0 -> X == 31
1565 // (1 << X) <= 0 -> X == 31
1566 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1567 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1568 ConstantInt::get(RHS->getType(), TypeBits-1));
1569
1570 // (1 << X) >= 0 -> X != 31
1571 // (1 << X) > 0 -> X != 31
1572 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1573 return new ICmpInst(ICmpInst::ICMP_NE, X,
1574 ConstantInt::get(RHS->getType(), TypeBits-1));
1575 }
1576 } else if (ICI.isEquality()) {
1577 if (RHSVIsPowerOf2)
1578 return new ICmpInst(
1579 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
David Majnemerb889e402013-06-28 23:42:03 +00001580 }
1581 }
1582 break;
1583 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001584
Chris Lattner2188e402010-01-04 07:37:31 +00001585 // Check that the shift amount is in range. If not, don't perform
1586 // undefined shifts. When the shift is visited it will be
1587 // simplified.
1588 if (ShAmt->uge(TypeBits))
1589 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001590
Chris Lattner2188e402010-01-04 07:37:31 +00001591 if (ICI.isEquality()) {
1592 // If we are comparing against bits always shifted out, the
1593 // comparison cannot succeed.
1594 Constant *Comp =
1595 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1596 ShAmt);
1597 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1598 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001599 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattner2188e402010-01-04 07:37:31 +00001600 return ReplaceInstUsesWith(ICI, Cst);
1601 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001602
Chris Lattner98457102011-02-10 05:23:05 +00001603 // If the shift is NUW, then it is just shifting out zeros, no need for an
1604 // AND.
1605 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1606 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1607 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001608
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001609 // If the shift is NSW and we compare to 0, then it is just shifting out
1610 // sign bits, no need for an AND either.
1611 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1612 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1613 ConstantExpr::getLShr(RHS, ShAmt));
1614
Chris Lattner2188e402010-01-04 07:37:31 +00001615 if (LHSI->hasOneUse()) {
1616 // Otherwise strength reduce the shift into an and.
1617 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Jakub Staszakbddea112013-06-06 20:18:46 +00001618 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
1619 TypeBits - ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001620
Chris Lattner2188e402010-01-04 07:37:31 +00001621 Value *And =
1622 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1623 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner98457102011-02-10 05:23:05 +00001624 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner2188e402010-01-04 07:37:31 +00001625 }
1626 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001627
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001628 // If this is a signed comparison to 0 and the shift is sign preserving,
1629 // use the shift LHS operand instead.
1630 ICmpInst::Predicate pred = ICI.getPredicate();
1631 if (isSignTest(pred, RHS) &&
1632 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1633 return new ICmpInst(pred,
1634 LHSI->getOperand(0),
1635 Constant::getNullValue(RHS->getType()));
1636
Chris Lattner2188e402010-01-04 07:37:31 +00001637 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1638 bool TrueIfSigned = false;
1639 if (LHSI->hasOneUse() &&
1640 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1641 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattner43273af2011-02-13 08:07:21 +00001642 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach129c52a2011-09-30 18:09:53 +00001643 APInt::getOneBitSet(TypeBits,
Chris Lattner43273af2011-02-13 08:07:21 +00001644 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00001645 Value *And =
1646 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1647 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1648 And, Constant::getNullValue(And->getType()));
1649 }
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001650
1651 // Transform (icmp pred iM (shl iM %v, N), CI)
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00001652 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1653 // 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 +00001654 // This enables to get rid of the shift in favor of a trunc which can be
1655 // free on the target. It has the additional benefit of comparing to a
1656 // smaller constant, which will be target friendly.
1657 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00001658 if (LHSI->hasOneUse() &&
1659 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001660 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1661 Constant *NCI = ConstantExpr::getTrunc(
1662 ConstantExpr::getAShr(RHS,
1663 ConstantInt::get(RHS->getType(), Amt)),
1664 NTy);
1665 return new ICmpInst(ICI.getPredicate(),
1666 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaison1fd843e2013-02-15 15:18:17 +00001667 NCI);
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001668 }
1669
Chris Lattner2188e402010-01-04 07:37:31 +00001670 break;
1671 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001672
Chris Lattner2188e402010-01-04 07:37:31 +00001673 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewycky174a7052011-02-28 08:31:40 +00001674 case Instruction::AShr: {
1675 // Handle equality comparisons of shift-by-constant.
1676 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1677 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1678 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattnerd369f572011-02-13 07:43:07 +00001679 return Res;
Nick Lewycky174a7052011-02-28 08:31:40 +00001680 }
1681
1682 // Handle exact shr's.
1683 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1684 if (RHSV.isMinValue())
1685 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1686 }
Chris Lattner2188e402010-01-04 07:37:31 +00001687 break;
Nick Lewycky174a7052011-02-28 08:31:40 +00001688 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001689
Chris Lattner2188e402010-01-04 07:37:31 +00001690 case Instruction::SDiv:
1691 case Instruction::UDiv:
1692 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach129c52a2011-09-30 18:09:53 +00001693 // Fold this div into the comparison, producing a range check.
1694 // Determine, based on the divide type, what the range is being
1695 // checked. If there is an overflow on the low or high side, remember
Chris Lattner2188e402010-01-04 07:37:31 +00001696 // it, otherwise compute the range [low, hi) bounding the new value.
1697 // See: InsertRangeTest above for the kinds of replacements possible.
1698 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1699 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1700 DivRHS))
1701 return R;
1702 break;
1703
David Majnemerf2a9a512013-07-09 07:50:59 +00001704 case Instruction::Sub: {
1705 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
1706 if (!LHSC) break;
1707 const APInt &LHSV = LHSC->getValue();
1708
1709 // C1-X <u C2 -> (X|(C2-1)) == C1
1710 // iff C1 & (C2-1) == C2-1
1711 // C2 is a power of 2
1712 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1713 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
1714 return new ICmpInst(ICmpInst::ICMP_EQ,
1715 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
1716 LHSC);
1717
David Majnemereeed73b2013-07-09 09:24:35 +00001718 // C1-X >u C2 -> (X|C2) != C1
David Majnemerf2a9a512013-07-09 07:50:59 +00001719 // iff C1 & C2 == C2
1720 // C2+1 is a power of 2
1721 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1722 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
1723 return new ICmpInst(ICmpInst::ICMP_NE,
1724 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
1725 break;
1726 }
1727
Chris Lattner2188e402010-01-04 07:37:31 +00001728 case Instruction::Add:
1729 // Fold: icmp pred (add X, C1), C2
1730 if (!ICI.isEquality()) {
1731 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1732 if (!LHSC) break;
1733 const APInt &LHSV = LHSC->getValue();
1734
1735 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1736 .subtract(LHSV);
1737
1738 if (ICI.isSigned()) {
1739 if (CR.getLower().isSignBit()) {
1740 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001741 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00001742 } else if (CR.getUpper().isSignBit()) {
1743 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001744 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00001745 }
1746 } else {
1747 if (CR.getLower().isMinValue()) {
1748 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001749 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00001750 } else if (CR.getUpper().isMinValue()) {
1751 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001752 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00001753 }
1754 }
David Majnemerfa90a0b2013-07-08 11:53:08 +00001755
David Majnemerbafa5372013-07-09 07:58:32 +00001756 // X-C1 <u C2 -> (X & -C2) == C1
1757 // iff C1 & (C2-1) == 0
1758 // C2 is a power of 2
David Majnemerfa90a0b2013-07-08 11:53:08 +00001759 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
David Majnemerbafa5372013-07-09 07:58:32 +00001760 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
David Majnemerfa90a0b2013-07-08 11:53:08 +00001761 return new ICmpInst(ICmpInst::ICMP_EQ,
1762 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
1763 ConstantExpr::getNeg(LHSC));
David Majnemerbafa5372013-07-09 07:58:32 +00001764
David Majnemereeed73b2013-07-09 09:24:35 +00001765 // X-C1 >u C2 -> (X & ~C2) != C1
David Majnemerbafa5372013-07-09 07:58:32 +00001766 // iff C1 & C2 == 0
1767 // C2+1 is a power of 2
1768 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1769 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
1770 return new ICmpInst(ICmpInst::ICMP_NE,
1771 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
1772 ConstantExpr::getNeg(LHSC));
Chris Lattner2188e402010-01-04 07:37:31 +00001773 }
1774 break;
1775 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001776
Chris Lattner2188e402010-01-04 07:37:31 +00001777 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1778 if (ICI.isEquality()) {
1779 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001780
1781 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner2188e402010-01-04 07:37:31 +00001782 // the second operand is a constant, simplify a bit.
1783 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1784 switch (BO->getOpcode()) {
1785 case Instruction::SRem:
1786 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1787 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1788 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohman4ce1fb12010-04-08 23:03:40 +00001789 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001790 Value *NewRem =
1791 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1792 BO->getName());
1793 return new ICmpInst(ICI.getPredicate(), NewRem,
1794 Constant::getNullValue(BO->getType()));
1795 }
1796 }
1797 break;
1798 case Instruction::Add:
1799 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1800 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1801 if (BO->hasOneUse())
1802 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1803 ConstantExpr::getSub(RHS, BOp1C));
1804 } else if (RHSV == 0) {
1805 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1806 // efficiently invertible, or if the add has just this one use.
1807 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001808
Chris Lattner2188e402010-01-04 07:37:31 +00001809 if (Value *NegVal = dyn_castNegVal(BOp1))
1810 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner31b106d2011-04-26 20:02:45 +00001811 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner2188e402010-01-04 07:37:31 +00001812 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner31b106d2011-04-26 20:02:45 +00001813 if (BO->hasOneUse()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001814 Value *Neg = Builder->CreateNeg(BOp1);
1815 Neg->takeName(BO);
1816 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1817 }
1818 }
1819 break;
1820 case Instruction::Xor:
1821 // For the xor case, we can xor two constants together, eliminating
1822 // the explicit xor.
Benjamin Kramerc9708492011-06-13 15:24:24 +00001823 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1824 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner2188e402010-01-04 07:37:31 +00001825 ConstantExpr::getXor(RHS, BOC));
Benjamin Kramerc9708492011-06-13 15:24:24 +00001826 } else if (RHSV == 0) {
1827 // Replace ((xor A, B) != 0) with (A != B)
Chris Lattner2188e402010-01-04 07:37:31 +00001828 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1829 BO->getOperand(1));
Benjamin Kramerc9708492011-06-13 15:24:24 +00001830 }
Chris Lattner2188e402010-01-04 07:37:31 +00001831 break;
Benjamin Kramerc9708492011-06-13 15:24:24 +00001832 case Instruction::Sub:
1833 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1834 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1835 if (BO->hasOneUse())
1836 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1837 ConstantExpr::getSub(BOp0C, RHS));
1838 } else if (RHSV == 0) {
1839 // Replace ((sub A, B) != 0) with (A != B)
1840 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1841 BO->getOperand(1));
1842 }
1843 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001844 case Instruction::Or:
1845 // If bits are being or'd in that are not present in the constant we
1846 // are comparing against, then the comparison could never succeed!
Eli Friedman0428a612010-07-29 18:03:33 +00001847 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001848 Constant *NotCI = ConstantExpr::getNot(RHS);
1849 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Jakub Staszakbddea112013-06-06 20:18:46 +00001850 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Chris Lattner2188e402010-01-04 07:37:31 +00001851 }
1852 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001853
Chris Lattner2188e402010-01-04 07:37:31 +00001854 case Instruction::And:
1855 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1856 // If bits are being compared against that are and'd out, then the
1857 // comparison can never succeed!
1858 if ((RHSV & ~BOC->getValue()) != 0)
Jakub Staszakbddea112013-06-06 20:18:46 +00001859 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001860
Chris Lattner2188e402010-01-04 07:37:31 +00001861 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1862 if (RHS == BOC && RHSV.isPowerOf2())
1863 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1864 ICmpInst::ICMP_NE, LHSI,
1865 Constant::getNullValue(RHS->getType()));
Benjamin Kramer9eca5fe2011-07-04 20:16:36 +00001866
1867 // Don't perform the following transforms if the AND has multiple uses
1868 if (!BO->hasOneUse())
1869 break;
1870
Chris Lattner2188e402010-01-04 07:37:31 +00001871 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1872 if (BOC->getValue().isSignBit()) {
1873 Value *X = BO->getOperand(0);
1874 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001875 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00001876 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1877 return new ICmpInst(pred, X, Zero);
1878 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001879
Chris Lattner2188e402010-01-04 07:37:31 +00001880 // ((X & ~7) == 0) --> X < 8
1881 if (RHSV == 0 && isHighOnes(BOC)) {
1882 Value *X = BO->getOperand(0);
1883 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001884 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00001885 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1886 return new ICmpInst(pred, X, NegX);
1887 }
1888 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001889 break;
1890 case Instruction::Mul:
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001891 if (RHSV == 0 && BO->hasNoSignedWrap()) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001892 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1893 // The trivial case (mul X, 0) is handled by InstSimplify
1894 // General case : (mul X, C) != 0 iff X != 0
1895 // (mul X, C) == 0 iff X == 0
1896 if (!BOC->isZero())
1897 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1898 Constant::getNullValue(RHS->getType()));
1899 }
1900 }
1901 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001902 default: break;
1903 }
1904 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1905 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner54f4e392010-01-05 18:09:56 +00001906 switch (II->getIntrinsicID()) {
1907 case Intrinsic::bswap:
Chris Lattner2188e402010-01-04 07:37:31 +00001908 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001909 ICI.setOperand(0, II->getArgOperand(0));
Jakub Staszakbddea112013-06-06 20:18:46 +00001910 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
Chris Lattner2188e402010-01-04 07:37:31 +00001911 return &ICI;
Chris Lattner54f4e392010-01-05 18:09:56 +00001912 case Intrinsic::ctlz:
1913 case Intrinsic::cttz:
1914 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1915 if (RHSV == RHS->getType()->getBitWidth()) {
1916 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001917 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00001918 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1919 return &ICI;
1920 }
1921 break;
1922 case Intrinsic::ctpop:
1923 // popcount(A) == 0 -> A == 0 and likewise for !=
1924 if (RHS->isZero()) {
1925 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001926 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00001927 ICI.setOperand(1, RHS);
1928 return &ICI;
1929 }
1930 break;
1931 default:
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001932 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001933 }
1934 }
1935 }
Craig Topperf40110f2014-04-25 05:29:35 +00001936 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001937}
1938
1939/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1940/// We only handle extending casts so far.
1941///
1942Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1943 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1944 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001945 Type *SrcTy = LHSCIOp->getType();
1946 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00001947 Value *RHSCIOp;
1948
Jim Grosbach129c52a2011-09-30 18:09:53 +00001949 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00001950 // integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001951 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
1952 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001953 Value *RHSOp = nullptr;
Michael Liaod266b922015-02-13 04:51:26 +00001954 if (PtrToIntOperator *RHSC = dyn_cast<PtrToIntOperator>(ICI.getOperand(1))) {
1955 Value *RHSCIOp = RHSC->getOperand(0);
1956 if (RHSCIOp->getType()->getPointerAddressSpace() ==
1957 LHSCIOp->getType()->getPointerAddressSpace()) {
1958 RHSOp = RHSC->getOperand(0);
1959 // If the pointer types don't match, insert a bitcast.
1960 if (LHSCIOp->getType() != RHSOp->getType())
1961 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1962 }
1963 } else if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1)))
Chris Lattner2188e402010-01-04 07:37:31 +00001964 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner2188e402010-01-04 07:37:31 +00001965
1966 if (RHSOp)
1967 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1968 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001969
Chris Lattner2188e402010-01-04 07:37:31 +00001970 // The code below only handles extension cast instructions, so far.
1971 // Enforce this.
1972 if (LHSCI->getOpcode() != Instruction::ZExt &&
1973 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00001974 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001975
1976 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1977 bool isSignedCmp = ICI.isSigned();
1978
1979 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1980 // Not an extension from the same type?
1981 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001982 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001983 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001984
Chris Lattner2188e402010-01-04 07:37:31 +00001985 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1986 // and the other is a zext), then we can't handle this.
1987 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00001988 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001989
1990 // Deal with equality cases early.
1991 if (ICI.isEquality())
1992 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1993
1994 // A signed comparison of sign extended values simplifies into a
1995 // signed comparison.
1996 if (isSignedCmp && isSignedExt)
1997 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1998
1999 // The other three cases all fold into an unsigned comparison.
2000 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
2001 }
2002
2003 // If we aren't dealing with a constant on the RHS, exit early
2004 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
2005 if (!CI)
Craig Topperf40110f2014-04-25 05:29:35 +00002006 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002007
2008 // Compute the constant that would happen if we truncated to SrcTy then
2009 // reextended to DestTy.
2010 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
2011 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
2012 Res1, DestTy);
2013
2014 // If the re-extended constant didn't change...
2015 if (Res2 == CI) {
2016 // Deal with equality cases early.
2017 if (ICI.isEquality())
2018 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
2019
2020 // A signed comparison of sign extended values simplifies into a
2021 // signed comparison.
2022 if (isSignedExt && isSignedCmp)
2023 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
2024
2025 // The other three cases all fold into an unsigned comparison.
2026 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
2027 }
2028
Jim Grosbach129c52a2011-09-30 18:09:53 +00002029 // The re-extended constant changed so the constant cannot be represented
Chris Lattner2188e402010-01-04 07:37:31 +00002030 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002031 // All the cases that fold to true or false will have already been handled
2032 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00002033
Duncan Sands8fb2c382011-01-20 13:21:55 +00002034 if (isSignedCmp || !isSignedExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002035 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002036
2037 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
2038 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002039
2040 // We're performing an unsigned comp with a sign extended value.
2041 // This is true if the input is >= 0. [aka >s -1]
2042 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
2043 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00002044
2045 // Finally, return the value computed.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002046 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner2188e402010-01-04 07:37:31 +00002047 return ReplaceInstUsesWith(ICI, Result);
2048
Duncan Sands8fb2c382011-01-20 13:21:55 +00002049 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00002050 return BinaryOperator::CreateNot(Result);
2051}
2052
Chris Lattneree61c1d2010-12-19 17:52:50 +00002053/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
2054/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00002055/// If this is of the form:
2056/// sum = a + b
2057/// if (sum+128 >u 255)
2058/// Then replace it with llvm.sadd.with.overflow.i8.
2059///
Chris Lattneree61c1d2010-12-19 17:52:50 +00002060static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2061 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00002062 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00002063 // The transformation we're trying to do here is to transform this into an
2064 // llvm.sadd.with.overflow. To do this, we have to replace the original add
2065 // with a narrower add, and discard the add-with-constant that is part of the
2066 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00002067
Chris Lattnerf29562d2010-12-19 17:59:02 +00002068 // In order to eliminate the add-with-constant, the compare can be its only
2069 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00002070 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00002071 if (!AddWithCst->hasOneUse()) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002072
Chris Lattnerc56c8452010-12-19 18:22:06 +00002073 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
Craig Topperf40110f2014-04-25 05:29:35 +00002074 if (!CI2->getValue().isPowerOf2()) return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002075 unsigned NewWidth = CI2->getValue().countTrailingZeros();
Craig Topperf40110f2014-04-25 05:29:35 +00002076 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002077
Chris Lattnerc56c8452010-12-19 18:22:06 +00002078 // The width of the new add formed is 1 more than the bias.
2079 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002080
Chris Lattnerc56c8452010-12-19 18:22:06 +00002081 // Check to see that CI1 is an all-ones value with NewWidth bits.
2082 if (CI1->getBitWidth() == NewWidth ||
2083 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
Craig Topperf40110f2014-04-25 05:29:35 +00002084 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002085
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002086 // This is only really a signed overflow check if the inputs have been
2087 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2088 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2089 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
Hal Finkel60db0582014-09-07 18:57:58 +00002090 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2091 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
Craig Topperf40110f2014-04-25 05:29:35 +00002092 return nullptr;
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002093
Jim Grosbach129c52a2011-09-30 18:09:53 +00002094 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00002095 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2096 // and truncates that discard the high bits of the add. Verify that this is
2097 // the case.
2098 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00002099 for (User *U : OrigAdd->users()) {
2100 if (U == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002101
Chris Lattnerc56c8452010-12-19 18:22:06 +00002102 // Only accept truncates for now. We would really like a nice recursive
2103 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2104 // chain to see which bits of a value are actually demanded. If the
2105 // original add had another add which was then immediately truncated, we
2106 // could still do the transformation.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002107 TruncInst *TI = dyn_cast<TruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00002108 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2109 return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002110 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002111
Chris Lattneree61c1d2010-12-19 17:52:50 +00002112 // If the pattern matches, truncate the inputs to the narrower type and
2113 // use the sadd_with_overflow intrinsic to efficiently compute both the
2114 // result and the overflow bit.
Chris Lattner79874562010-12-19 18:35:09 +00002115 Module *M = I.getParent()->getParent()->getParent();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002116
Jay Foadb804a2b2011-07-12 14:06:48 +00002117 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Chris Lattner79874562010-12-19 18:35:09 +00002118 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
Benjamin Kramere6e19332011-07-14 17:45:39 +00002119 NewType);
Chris Lattner79874562010-12-19 18:35:09 +00002120
Chris Lattnerce2995a2010-12-19 18:38:44 +00002121 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002122
Chris Lattner79874562010-12-19 18:35:09 +00002123 // Put the new code above the original add, in case there are any uses of the
2124 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002125 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002126
Chris Lattner79874562010-12-19 18:35:09 +00002127 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2128 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
David Blaikieff6409d2015-05-18 22:13:54 +00002129 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
Chris Lattner79874562010-12-19 18:35:09 +00002130 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2131 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002132
Chris Lattneree61c1d2010-12-19 17:52:50 +00002133 // The inner add was the result of the narrow add, zero extended to the
2134 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattnerce2995a2010-12-19 18:38:44 +00002135 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002136
Chris Lattner79874562010-12-19 18:35:09 +00002137 // The original icmp gets replaced with the overflow value.
2138 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00002139}
Chris Lattner2188e402010-01-04 07:37:31 +00002140
Sanjoy Dasb0984472015-04-08 04:27:22 +00002141bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
2142 Value *RHS, Instruction &OrigI,
2143 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00002144 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
2145 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002146
2147 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
2148 Result = OpResult;
2149 Overflow = OverflowVal;
2150 if (ReuseName)
2151 Result->takeName(&OrigI);
2152 return true;
2153 };
2154
Sanjoy Das6f5dca72015-08-28 19:09:31 +00002155 // If the overflow check was an add followed by a compare, the insertion point
2156 // may be pointing to the compare. We want to insert the new instructions
2157 // before the add in case there are uses of the add between the add and the
2158 // compare.
2159 Builder->SetInsertPoint(&OrigI);
2160
Sanjoy Dasb0984472015-04-08 04:27:22 +00002161 switch (OCF) {
2162 case OCF_INVALID:
2163 llvm_unreachable("bad overflow check kind!");
2164
2165 case OCF_UNSIGNED_ADD: {
2166 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
2167 if (OR == OverflowResult::NeverOverflows)
2168 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
2169 true);
2170
2171 if (OR == OverflowResult::AlwaysOverflows)
2172 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
2173 }
2174 // FALL THROUGH uadd into sadd
2175 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002176 // X + 0 -> {X, false}
2177 if (match(RHS, m_Zero()))
2178 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002179
2180 // We can strength reduce this signed add into a regular add if we can prove
2181 // that it will never overflow.
2182 if (OCF == OCF_SIGNED_ADD)
2183 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
2184 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
2185 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00002186 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002187 }
2188
2189 case OCF_UNSIGNED_SUB:
2190 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002191 // X - 0 -> {X, false}
2192 if (match(RHS, m_Zero()))
2193 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002194
2195 if (OCF == OCF_SIGNED_SUB) {
2196 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
2197 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
2198 true);
2199 } else {
2200 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
2201 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
2202 true);
2203 }
2204 break;
2205 }
2206
2207 case OCF_UNSIGNED_MUL: {
2208 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
2209 if (OR == OverflowResult::NeverOverflows)
2210 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
2211 true);
2212 if (OR == OverflowResult::AlwaysOverflows)
2213 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
2214 } // FALL THROUGH
2215 case OCF_SIGNED_MUL:
2216 // X * undef -> undef
2217 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00002218 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002219
David Majnemer27e89ba2015-05-21 23:04:21 +00002220 // X * 0 -> {0, false}
2221 if (match(RHS, m_Zero()))
2222 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002223
David Majnemer27e89ba2015-05-21 23:04:21 +00002224 // X * 1 -> {X, false}
2225 if (match(RHS, m_One()))
2226 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002227
2228 if (OCF == OCF_SIGNED_MUL)
2229 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
2230 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
2231 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00002232 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002233 }
2234
2235 return false;
2236}
2237
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002238/// \brief Recognize and process idiom involving test for multiplication
2239/// overflow.
2240///
2241/// The caller has matched a pattern of the form:
2242/// I = cmp u (mul(zext A, zext B), V
2243/// The function checks if this is a test for overflow and if so replaces
2244/// multiplication with call to 'mul.with.overflow' intrinsic.
2245///
2246/// \param I Compare instruction.
2247/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2248/// the compare instruction. Must be of integer type.
2249/// \param OtherVal The other argument of compare instruction.
2250/// \returns Instruction which must replace the compare instruction, NULL if no
2251/// replacement required.
2252static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2253 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00002254 // Don't bother doing this transformation for pointers, don't do it for
2255 // vectors.
2256 if (!isa<IntegerType>(MulVal->getType()))
2257 return nullptr;
2258
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002259 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2260 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00002261 auto *MulInstr = dyn_cast<Instruction>(MulVal);
2262 if (!MulInstr)
2263 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002264 assert(MulInstr->getOpcode() == Instruction::Mul);
2265
David Majnemer634ca232014-11-01 23:46:05 +00002266 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
2267 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002268 assert(LHS->getOpcode() == Instruction::ZExt);
2269 assert(RHS->getOpcode() == Instruction::ZExt);
2270 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2271
2272 // Calculate type and width of the result produced by mul.with.overflow.
2273 Type *TyA = A->getType(), *TyB = B->getType();
2274 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2275 WidthB = TyB->getPrimitiveSizeInBits();
2276 unsigned MulWidth;
2277 Type *MulType;
2278 if (WidthB > WidthA) {
2279 MulWidth = WidthB;
2280 MulType = TyB;
2281 } else {
2282 MulWidth = WidthA;
2283 MulType = TyA;
2284 }
2285
2286 // In order to replace the original mul with a narrower mul.with.overflow,
2287 // all uses must ignore upper bits of the product. The number of used low
2288 // bits must be not greater than the width of mul.with.overflow.
2289 if (MulVal->hasNUsesOrMore(2))
2290 for (User *U : MulVal->users()) {
2291 if (U == &I)
2292 continue;
2293 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2294 // Check if truncation ignores bits above MulWidth.
2295 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2296 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002297 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002298 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2299 // Check if AND ignores bits above MulWidth.
2300 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00002301 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002302 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2303 const APInt &CVal = CI->getValue();
2304 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002305 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002306 }
2307 } else {
2308 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00002309 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002310 }
2311 }
2312
2313 // Recognize patterns
2314 switch (I.getPredicate()) {
2315 case ICmpInst::ICMP_EQ:
2316 case ICmpInst::ICMP_NE:
2317 // Recognize pattern:
2318 // mulval = mul(zext A, zext B)
2319 // cmp eq/neq mulval, zext trunc mulval
2320 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2321 if (Zext->hasOneUse()) {
2322 Value *ZextArg = Zext->getOperand(0);
2323 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2324 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2325 break; //Recognized
2326 }
2327
2328 // Recognize pattern:
2329 // mulval = mul(zext A, zext B)
2330 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2331 ConstantInt *CI;
2332 Value *ValToMask;
2333 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2334 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00002335 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002336 const APInt &CVal = CI->getValue() + 1;
2337 if (CVal.isPowerOf2()) {
2338 unsigned MaskWidth = CVal.logBase2();
2339 if (MaskWidth == MulWidth)
2340 break; // Recognized
2341 }
2342 }
Craig Topperf40110f2014-04-25 05:29:35 +00002343 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002344
2345 case ICmpInst::ICMP_UGT:
2346 // Recognize pattern:
2347 // mulval = mul(zext A, zext B)
2348 // cmp ugt mulval, max
2349 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2350 APInt MaxVal = APInt::getMaxValue(MulWidth);
2351 MaxVal = MaxVal.zext(CI->getBitWidth());
2352 if (MaxVal.eq(CI->getValue()))
2353 break; // Recognized
2354 }
Craig Topperf40110f2014-04-25 05:29:35 +00002355 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002356
2357 case ICmpInst::ICMP_UGE:
2358 // Recognize pattern:
2359 // mulval = mul(zext A, zext B)
2360 // cmp uge mulval, max+1
2361 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2362 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2363 if (MaxVal.eq(CI->getValue()))
2364 break; // Recognized
2365 }
Craig Topperf40110f2014-04-25 05:29:35 +00002366 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002367
2368 case ICmpInst::ICMP_ULE:
2369 // Recognize pattern:
2370 // mulval = mul(zext A, zext B)
2371 // cmp ule mulval, max
2372 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2373 APInt MaxVal = APInt::getMaxValue(MulWidth);
2374 MaxVal = MaxVal.zext(CI->getBitWidth());
2375 if (MaxVal.eq(CI->getValue()))
2376 break; // Recognized
2377 }
Craig Topperf40110f2014-04-25 05:29:35 +00002378 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002379
2380 case ICmpInst::ICMP_ULT:
2381 // Recognize pattern:
2382 // mulval = mul(zext A, zext B)
2383 // cmp ule mulval, max + 1
2384 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002385 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002386 if (MaxVal.eq(CI->getValue()))
2387 break; // Recognized
2388 }
Craig Topperf40110f2014-04-25 05:29:35 +00002389 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002390
2391 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002392 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002393 }
2394
2395 InstCombiner::BuilderTy *Builder = IC.Builder;
2396 Builder->SetInsertPoint(MulInstr);
2397 Module *M = I.getParent()->getParent()->getParent();
2398
2399 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2400 Value *MulA = A, *MulB = B;
2401 if (WidthA < MulWidth)
2402 MulA = Builder->CreateZExt(A, MulType);
2403 if (WidthB < MulWidth)
2404 MulB = Builder->CreateZExt(B, MulType);
2405 Value *F =
2406 Intrinsic::getDeclaration(M, Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00002407 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002408 IC.Worklist.Add(MulInstr);
2409
2410 // If there are uses of mul result other than the comparison, we know that
2411 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002412 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002413 if (MulVal->hasNUsesOrMore(2)) {
2414 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2415 for (User *U : MulVal->users()) {
2416 if (U == &I || U == OtherVal)
2417 continue;
2418 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2419 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
2420 IC.ReplaceInstUsesWith(*TI, Mul);
2421 else
2422 TI->setOperand(0, Mul);
2423 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2424 assert(BO->getOpcode() == Instruction::And);
2425 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2426 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2427 APInt ShortMask = CI->getValue().trunc(MulWidth);
2428 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2429 Instruction *Zext =
2430 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2431 IC.Worklist.Add(Zext);
2432 IC.ReplaceInstUsesWith(*BO, Zext);
2433 } else {
2434 llvm_unreachable("Unexpected Binary operation");
2435 }
2436 IC.Worklist.Add(cast<Instruction>(U));
2437 }
2438 }
2439 if (isa<Instruction>(OtherVal))
2440 IC.Worklist.Add(cast<Instruction>(OtherVal));
2441
2442 // The original icmp gets replaced with the overflow value, maybe inverted
2443 // depending on predicate.
2444 bool Inverse = false;
2445 switch (I.getPredicate()) {
2446 case ICmpInst::ICMP_NE:
2447 break;
2448 case ICmpInst::ICMP_EQ:
2449 Inverse = true;
2450 break;
2451 case ICmpInst::ICMP_UGT:
2452 case ICmpInst::ICMP_UGE:
2453 if (I.getOperand(0) == MulVal)
2454 break;
2455 Inverse = true;
2456 break;
2457 case ICmpInst::ICMP_ULT:
2458 case ICmpInst::ICMP_ULE:
2459 if (I.getOperand(1) == MulVal)
2460 break;
2461 Inverse = true;
2462 break;
2463 default:
2464 llvm_unreachable("Unexpected predicate");
2465 }
2466 if (Inverse) {
2467 Value *Res = Builder->CreateExtractValue(Call, 1);
2468 return BinaryOperator::CreateNot(Res);
2469 }
2470
2471 return ExtractValueInst::Create(Call, 1);
2472}
2473
Owen Andersond490c2d2011-01-11 00:36:45 +00002474// DemandedBitsLHSMask - When performing a comparison against a constant,
2475// it is possible that not all the bits in the LHS are demanded. This helper
2476// method computes the mask that IS demanded.
2477static APInt DemandedBitsLHSMask(ICmpInst &I,
2478 unsigned BitWidth, bool isSignCheck) {
2479 if (isSignCheck)
2480 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002481
Owen Andersond490c2d2011-01-11 00:36:45 +00002482 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2483 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00002484 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002485
Owen Andersond490c2d2011-01-11 00:36:45 +00002486 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002487 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00002488 // correspond to the trailing ones of the comparand. The value of these
2489 // bits doesn't impact the outcome of the comparison, because any value
2490 // greater than the RHS must differ in a bit higher than these due to carry.
2491 case ICmpInst::ICMP_UGT: {
2492 unsigned trailingOnes = RHS.countTrailingOnes();
2493 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2494 return ~lowBitsSet;
2495 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002496
Owen Andersond490c2d2011-01-11 00:36:45 +00002497 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2498 // Any value less than the RHS must differ in a higher bit because of carries.
2499 case ICmpInst::ICMP_ULT: {
2500 unsigned trailingZeros = RHS.countTrailingZeros();
2501 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2502 return ~lowBitsSet;
2503 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002504
Owen Andersond490c2d2011-01-11 00:36:45 +00002505 default:
2506 return APInt::getAllOnesValue(BitWidth);
2507 }
Owen Andersond490c2d2011-01-11 00:36:45 +00002508}
Chris Lattner2188e402010-01-04 07:37:31 +00002509
Quentin Colombet5ab55552013-09-09 20:56:48 +00002510/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2511/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00002512/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00002513/// as subtract operands and their positions in those instructions.
2514/// The rational is that several architectures use the same instruction for
2515/// both subtract and cmp, thus it is better if the order of those operands
2516/// match.
2517/// \return true if Op0 and Op1 should be swapped.
2518static bool swapMayExposeCSEOpportunities(const Value * Op0,
2519 const Value * Op1) {
2520 // Filter out pointer value as those cannot appears directly in subtract.
2521 // FIXME: we may want to go through inttoptrs or bitcasts.
2522 if (Op0->getType()->isPointerTy())
2523 return false;
2524 // Count every uses of both Op0 and Op1 in a subtract.
2525 // Each time Op0 is the first operand, count -1: swapping is bad, the
2526 // subtract has already the same layout as the compare.
2527 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00002528 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002529 // At the end, if the benefit is greater than 0, Op0 should come second to
2530 // expose more CSE opportunities.
2531 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002532 for (const User *U : Op0->users()) {
2533 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002534 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2535 continue;
2536 // If Op0 is the first argument, this is not beneficial to swap the
2537 // arguments.
2538 int LocalSwapBenefits = -1;
2539 unsigned Op1Idx = 1;
2540 if (BinOp->getOperand(Op1Idx) == Op0) {
2541 Op1Idx = 0;
2542 LocalSwapBenefits = 1;
2543 }
2544 if (BinOp->getOperand(Op1Idx) != Op1)
2545 continue;
2546 GlobalSwapBenefits += LocalSwapBenefits;
2547 }
2548 return GlobalSwapBenefits > 0;
2549}
2550
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00002551/// \brief Check that one use is in the same block as the definition and all
2552/// other uses are in blocks dominated by a given block
2553///
2554/// \param DI Definition
2555/// \param UI Use
2556/// \param DB Block that must dominate all uses of \p DI outside
2557/// the parent block
2558/// \return true when \p UI is the only use of \p DI in the parent block
2559/// and all other uses of \p DI are in blocks dominated by \p DB.
2560///
2561bool InstCombiner::dominatesAllUses(const Instruction *DI,
2562 const Instruction *UI,
2563 const BasicBlock *DB) const {
2564 assert(DI && UI && "Instruction not defined\n");
2565 // ignore incomplete definitions
2566 if (!DI->getParent())
2567 return false;
2568 // DI and UI must be in the same block
2569 if (DI->getParent() != UI->getParent())
2570 return false;
2571 // Protect from self-referencing blocks
2572 if (DI->getParent() == DB)
2573 return false;
2574 // DominatorTree available?
2575 if (!DT)
2576 return false;
2577 for (const User *U : DI->users()) {
2578 auto *Usr = cast<Instruction>(U);
2579 if (Usr != UI && !DT->dominates(DB, Usr->getParent()))
2580 return false;
2581 }
2582 return true;
2583}
2584
2585///
2586/// true when the instruction sequence within a block is select-cmp-br.
2587///
2588static bool isChainSelectCmpBranch(const SelectInst *SI) {
2589 const BasicBlock *BB = SI->getParent();
2590 if (!BB)
2591 return false;
2592 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
2593 if (!BI || BI->getNumSuccessors() != 2)
2594 return false;
2595 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
2596 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
2597 return false;
2598 return true;
2599}
2600
2601///
2602/// \brief True when a select result is replaced by one of its operands
2603/// in select-icmp sequence. This will eventually result in the elimination
2604/// of the select.
2605///
2606/// \param SI Select instruction
2607/// \param Icmp Compare instruction
2608/// \param SIOpd Operand that replaces the select
2609///
2610/// Notes:
2611/// - The replacement is global and requires dominator information
2612/// - The caller is responsible for the actual replacement
2613///
2614/// Example:
2615///
2616/// entry:
2617/// %4 = select i1 %3, %C* %0, %C* null
2618/// %5 = icmp eq %C* %4, null
2619/// br i1 %5, label %9, label %7
2620/// ...
2621/// ; <label>:7 ; preds = %entry
2622/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
2623/// ...
2624///
2625/// can be transformed to
2626///
2627/// %5 = icmp eq %C* %0, null
2628/// %6 = select i1 %3, i1 %5, i1 true
2629/// br i1 %6, label %9, label %7
2630/// ...
2631/// ; <label>:7 ; preds = %entry
2632/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
2633///
2634/// Similar when the first operand of the select is a constant or/and
2635/// the compare is for not equal rather than equal.
2636///
2637/// NOTE: The function is only called when the select and compare constants
2638/// are equal, the optimization can work only for EQ predicates. This is not a
2639/// major restriction since a NE compare should be 'normalized' to an equal
2640/// compare, which usually happens in the combiner and test case
2641/// select-cmp-br.ll
2642/// checks for it.
2643bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
2644 const ICmpInst *Icmp,
2645 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00002646 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00002647 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
2648 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
2649 // The check for the unique predecessor is not the best that can be
2650 // done. But it protects efficiently against cases like when SI's
2651 // home block has two successors, Succ and Succ1, and Succ1 predecessor
2652 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
2653 // replaced can be reached on either path. So the uniqueness check
2654 // guarantees that the path all uses of SI (outside SI's parent) are on
2655 // is disjoint from all other paths out of SI. But that information
2656 // is more expensive to compute, and the trade-off here is in favor
2657 // of compile-time.
2658 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
2659 NumSel++;
2660 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
2661 return true;
2662 }
2663 }
2664 return false;
2665}
2666
Chris Lattner2188e402010-01-04 07:37:31 +00002667Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
2668 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00002669 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002670 unsigned Op0Cplxity = getComplexity(Op0);
2671 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002672
Chris Lattner2188e402010-01-04 07:37:31 +00002673 /// Orders the operands of the compare so that they are listed from most
2674 /// complex to least complex. This puts constants before unary operators,
2675 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002676 if (Op0Cplxity < Op1Cplxity ||
2677 (Op0Cplxity == Op1Cplxity &&
2678 swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002679 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00002680 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00002681 Changed = true;
2682 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002683
Jingyue Wu5e34ce32015-06-25 20:14:47 +00002684 if (Value *V =
2685 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AC, &I))
Chris Lattner2188e402010-01-04 07:37:31 +00002686 return ReplaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002687
Pete Cooperbc5c5242011-12-01 03:58:40 +00002688 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00002689 // ie, abs(val) != 0 -> val != 0
Pete Cooperbc5c5242011-12-01 03:58:40 +00002690 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
2691 {
Pete Cooperfdddc272011-12-01 19:13:26 +00002692 Value *Cond, *SelectTrue, *SelectFalse;
2693 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00002694 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00002695 if (Value *V = dyn_castNegVal(SelectTrue)) {
2696 if (V == SelectFalse)
2697 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2698 }
2699 else if (Value *V = dyn_castNegVal(SelectFalse)) {
2700 if (V == SelectTrue)
2701 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00002702 }
2703 }
2704 }
2705
Chris Lattner229907c2011-07-18 04:54:35 +00002706 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002707
2708 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sands9dff9be2010-02-15 16:12:20 +00002709 if (Ty->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00002710 switch (I.getPredicate()) {
2711 default: llvm_unreachable("Invalid icmp instruction!");
2712 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
2713 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
2714 return BinaryOperator::CreateNot(Xor);
2715 }
2716 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
2717 return BinaryOperator::CreateXor(Op0, Op1);
2718
2719 case ICmpInst::ICMP_UGT:
2720 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
2721 // FALL THROUGH
2722 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
2723 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2724 return BinaryOperator::CreateAnd(Not, Op1);
2725 }
2726 case ICmpInst::ICMP_SGT:
2727 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
2728 // FALL THROUGH
2729 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
2730 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2731 return BinaryOperator::CreateAnd(Not, Op0);
2732 }
2733 case ICmpInst::ICMP_UGE:
2734 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
2735 // FALL THROUGH
2736 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
2737 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2738 return BinaryOperator::CreateOr(Not, Op1);
2739 }
2740 case ICmpInst::ICMP_SGE:
2741 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
2742 // FALL THROUGH
2743 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
2744 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2745 return BinaryOperator::CreateOr(Not, Op0);
2746 }
2747 }
2748 }
2749
2750 unsigned BitWidth = 0;
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002751 if (Ty->isIntOrIntVectorTy())
Chris Lattner2188e402010-01-04 07:37:31 +00002752 BitWidth = Ty->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002753 else // Get pointer size.
2754 BitWidth = DL.getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002755
Chris Lattner2188e402010-01-04 07:37:31 +00002756 bool isSignBit = false;
2757
2758 // See if we are doing a comparison with a constant.
2759 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002760 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002761
Owen Anderson1294ea72010-12-17 18:08:00 +00002762 // Match the following pattern, which is a common idiom when writing
2763 // overflow-safe integer arithmetic function. The source performs an
2764 // addition in wider type, and explicitly checks for overflow using
2765 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
2766 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00002767 //
2768 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00002769 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00002770 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00002771 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00002772 // sum = a + b
2773 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00002774 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00002775 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00002776 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00002777 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00002778 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00002779 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00002780 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002781
David Majnemera0afb552015-01-14 19:26:56 +00002782 // The following transforms are only 'worth it' if the only user of the
2783 // subtraction is the icmp.
2784 if (Op0->hasOneUse()) {
2785 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2786 if (I.isEquality() && CI->isZero() &&
2787 match(Op0, m_Sub(m_Value(A), m_Value(B))))
2788 return new ICmpInst(I.getPredicate(), A, B);
2789
2790 // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
2791 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
2792 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
2793 return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
2794
2795 // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
2796 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
2797 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
2798 return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
2799
2800 // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
2801 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
2802 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
2803 return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
2804
2805 // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
2806 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
2807 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
2808 return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
Chris Lattner2188e402010-01-04 07:37:31 +00002809 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002810
Chris Lattner2188e402010-01-04 07:37:31 +00002811 // If we have an icmp le or icmp ge instruction, turn it into the
2812 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
2813 // them being folded in the code below. The SimplifyICmpInst code has
2814 // already handled the edge cases for us, so we just assert on them.
2815 switch (I.getPredicate()) {
2816 default: break;
2817 case ICmpInst::ICMP_ULE:
2818 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
2819 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002820 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002821 case ICmpInst::ICMP_SLE:
2822 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
2823 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002824 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002825 case ICmpInst::ICMP_UGE:
Nick Lewycky6b4454192011-02-28 06:20:05 +00002826 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner2188e402010-01-04 07:37:31 +00002827 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002828 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002829 case ICmpInst::ICMP_SGE:
Nick Lewycky6b4454192011-02-28 06:20:05 +00002830 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner2188e402010-01-04 07:37:31 +00002831 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002832 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002833 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002834
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00002835 if (I.isEquality()) {
2836 ConstantInt *CI2;
2837 if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
2838 match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
David Majnemer59939ac2014-10-19 08:23:08 +00002839 // (icmp eq/ne (ashr/lshr const2, A), const1)
David Majnemer2abb8182014-10-25 07:13:13 +00002840 if (Instruction *Inst = FoldICmpCstShrCst(I, Op0, A, CI, CI2))
2841 return Inst;
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00002842 }
David Majnemer59939ac2014-10-19 08:23:08 +00002843 if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
2844 // (icmp eq/ne (shl const2, A), const1)
David Majnemer2abb8182014-10-25 07:13:13 +00002845 if (Instruction *Inst = FoldICmpCstShlCst(I, Op0, A, CI, CI2))
2846 return Inst;
David Majnemer59939ac2014-10-19 08:23:08 +00002847 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00002848 }
2849
Chris Lattner2188e402010-01-04 07:37:31 +00002850 // If this comparison is a normal comparison, it demands all
2851 // bits, if it is a sign bit comparison, it only demands the sign bit.
2852 bool UnusedBit;
2853 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2854 }
2855
2856 // See if we can fold the comparison based on range information we can get
2857 // by checking whether bits are known to be zero or one in the input.
2858 if (BitWidth != 0) {
2859 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2860 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2861
2862 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersond490c2d2011-01-11 00:36:45 +00002863 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner2188e402010-01-04 07:37:31 +00002864 Op0KnownZero, Op0KnownOne, 0))
2865 return &I;
2866 if (SimplifyDemandedBits(I.getOperandUse(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002867 APInt::getAllOnesValue(BitWidth), Op1KnownZero,
2868 Op1KnownOne, 0))
Chris Lattner2188e402010-01-04 07:37:31 +00002869 return &I;
2870
2871 // Given the known and unknown bits, compute a range that the LHS could be
2872 // in. Compute the Min, Max and RHS values based on the known bits. For the
2873 // EQ and NE we use unsigned values.
2874 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2875 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2876 if (I.isSigned()) {
2877 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2878 Op0Min, Op0Max);
2879 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2880 Op1Min, Op1Max);
2881 } else {
2882 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2883 Op0Min, Op0Max);
2884 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2885 Op1Min, Op1Max);
2886 }
2887
2888 // If Min and Max are known to be the same, then SimplifyDemandedBits
2889 // figured out that the LHS is a constant. Just constant fold this now so
2890 // that code below can assume that Min != Max.
2891 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2892 return new ICmpInst(I.getPredicate(),
Nick Lewycky92db8e82011-03-06 03:36:19 +00002893 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00002894 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2895 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewycky92db8e82011-03-06 03:36:19 +00002896 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner2188e402010-01-04 07:37:31 +00002897
2898 // Based on the range information we know about the LHS, see if we can
Nick Lewycky6b4454192011-02-28 06:20:05 +00002899 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner2188e402010-01-04 07:37:31 +00002900 switch (I.getPredicate()) {
2901 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattnerf7e89612010-11-21 06:44:42 +00002902 case ICmpInst::ICMP_EQ: {
Chris Lattner2188e402010-01-04 07:37:31 +00002903 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewycky92db8e82011-03-06 03:36:19 +00002904 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002905
Chris Lattnerf7e89612010-11-21 06:44:42 +00002906 // If all bits are known zero except for one, then we know at most one
2907 // bit is set. If the comparison is against zero, then this is a check
2908 // to see if *that* bit is set.
2909 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002910 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00002911 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00002912 Value *LHS = nullptr;
2913 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002914 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2915 LHSC->getValue() != Op0KnownZeroInverted)
2916 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002917
Chris Lattnerf7e89612010-11-21 06:44:42 +00002918 // 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 +00002919 // then turn "((1 << x)&8) == 0" into "x != 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002920 // or turn "((1 << x)&7) == 0" into "x > 2".
Craig Topperf40110f2014-04-25 05:29:35 +00002921 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002922 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002923 APInt ValToCheck = Op0KnownZeroInverted;
2924 if (ValToCheck.isPowerOf2()) {
2925 unsigned CmpVal = ValToCheck.countTrailingZeros();
2926 return new ICmpInst(ICmpInst::ICMP_NE, X,
2927 ConstantInt::get(X->getType(), CmpVal));
2928 } else if ((++ValToCheck).isPowerOf2()) {
2929 unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
2930 return new ICmpInst(ICmpInst::ICMP_UGT, X,
2931 ConstantInt::get(X->getType(), CmpVal));
2932 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00002933 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002934
Chris Lattnerf7e89612010-11-21 06:44:42 +00002935 // 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 +00002936 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattner98457102011-02-10 05:23:05 +00002937 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002938 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00002939 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00002940 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner98457102011-02-10 05:23:05 +00002941 ConstantInt::get(X->getType(),
2942 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00002943 }
Chris Lattner2188e402010-01-04 07:37:31 +00002944 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002945 }
2946 case ICmpInst::ICMP_NE: {
Chris Lattner2188e402010-01-04 07:37:31 +00002947 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewycky92db8e82011-03-06 03:36:19 +00002948 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002949
Chris Lattnerf7e89612010-11-21 06:44:42 +00002950 // If all bits are known zero except for one, then we know at most one
2951 // bit is set. If the comparison is against zero, then this is a check
2952 // to see if *that* bit is set.
2953 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002954 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00002955 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00002956 Value *LHS = nullptr;
2957 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002958 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2959 LHSC->getValue() != Op0KnownZeroInverted)
2960 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002961
Chris Lattnerf7e89612010-11-21 06:44:42 +00002962 // 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 +00002963 // then turn "((1 << x)&8) != 0" into "x == 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002964 // or turn "((1 << x)&7) != 0" into "x < 3".
Craig Topperf40110f2014-04-25 05:29:35 +00002965 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002966 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002967 APInt ValToCheck = Op0KnownZeroInverted;
2968 if (ValToCheck.isPowerOf2()) {
2969 unsigned CmpVal = ValToCheck.countTrailingZeros();
2970 return new ICmpInst(ICmpInst::ICMP_EQ, X,
2971 ConstantInt::get(X->getType(), CmpVal));
2972 } else if ((++ValToCheck).isPowerOf2()) {
2973 unsigned CmpVal = ValToCheck.countTrailingZeros();
2974 return new ICmpInst(ICmpInst::ICMP_ULT, X,
2975 ConstantInt::get(X->getType(), CmpVal));
2976 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00002977 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002978
Chris Lattnerf7e89612010-11-21 06:44:42 +00002979 // 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 +00002980 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattner98457102011-02-10 05:23:05 +00002981 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002982 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00002983 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00002984 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner98457102011-02-10 05:23:05 +00002985 ConstantInt::get(X->getType(),
2986 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00002987 }
Chris Lattner2188e402010-01-04 07:37:31 +00002988 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002989 }
Chris Lattner2188e402010-01-04 07:37:31 +00002990 case ICmpInst::ICMP_ULT:
2991 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002992 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002993 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002994 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002995 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2996 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2997 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2998 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2999 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003000 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003001
3002 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
3003 if (CI->isMinValue(true))
3004 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
3005 Constant::getAllOnesValue(Op0->getType()));
3006 }
3007 break;
3008 case ICmpInst::ICMP_UGT:
3009 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003010 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003011 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003012 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003013
3014 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
3015 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3016 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3017 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
3018 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003019 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003020
3021 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
3022 if (CI->isMaxValue(true))
3023 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
3024 Constant::getNullValue(Op0->getType()));
3025 }
3026 break;
3027 case ICmpInst::ICMP_SLT:
3028 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003029 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003030 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003031 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003032 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
3033 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3034 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3035 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
3036 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003037 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003038 }
3039 break;
3040 case ICmpInst::ICMP_SGT:
3041 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003042 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003043 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003044 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003045
3046 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
3047 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3048 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3049 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
3050 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003051 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003052 }
3053 break;
3054 case ICmpInst::ICMP_SGE:
3055 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
3056 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003057 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003058 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003059 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003060 break;
3061 case ICmpInst::ICMP_SLE:
3062 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
3063 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003064 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003065 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003066 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003067 break;
3068 case ICmpInst::ICMP_UGE:
3069 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
3070 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003071 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003072 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003073 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003074 break;
3075 case ICmpInst::ICMP_ULE:
3076 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
3077 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003078 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003079 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003080 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003081 break;
3082 }
3083
3084 // Turn a signed comparison into an unsigned one if both operands
3085 // are known to have the same sign.
3086 if (I.isSigned() &&
3087 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
3088 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
3089 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
3090 }
3091
3092 // Test if the ICmpInst instruction is used exclusively by a select as
3093 // part of a minimum or maximum operation. If so, refrain from doing
3094 // any other folding. This helps out other analyses which understand
3095 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
3096 // and CodeGen. And in this case, at least one of the comparison
3097 // operands has at least one user besides the compare (the select),
3098 // which would often largely negate the benefit of folding anyway.
3099 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00003100 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00003101 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
3102 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00003103 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003104
3105 // See if we are doing a comparison between a constant and an instruction that
3106 // can be folded into the comparison.
3107 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003108 // Since the RHS is a ConstantInt (CI), if the left hand side is an
3109 // instruction, see if that instruction also has constants so that the
3110 // instruction can be folded into the icmp
Chris Lattner2188e402010-01-04 07:37:31 +00003111 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3112 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
3113 return Res;
3114 }
3115
3116 // Handle icmp with constant (but not simple integer constant) RHS
3117 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3118 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3119 switch (LHSI->getOpcode()) {
3120 case Instruction::GetElementPtr:
3121 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3122 if (RHSC->isNullValue() &&
3123 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3124 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3125 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3126 break;
3127 case Instruction::PHI:
3128 // Only fold icmp into the PHI if the phi and icmp are in the same
3129 // block. If in the same block, we're encouraging jump threading. If
3130 // not, we are just pessimizing the code by making an i1 phi.
3131 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003132 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003133 return NV;
3134 break;
3135 case Instruction::Select: {
3136 // If either operand of the select is a constant, we can fold the
3137 // comparison into the select arms, which will cause one to be
3138 // constant folded and the select turned into a bitwise or.
Craig Topperf40110f2014-04-25 05:29:35 +00003139 Value *Op1 = nullptr, *Op2 = nullptr;
Hans Wennborg083ca9b2015-10-06 23:24:35 +00003140 ConstantInt *CI = nullptr;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003141 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003142 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003143 CI = dyn_cast<ConstantInt>(Op1);
3144 }
3145 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003146 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003147 CI = dyn_cast<ConstantInt>(Op2);
3148 }
Chris Lattner2188e402010-01-04 07:37:31 +00003149
3150 // We only want to perform this transformation if it will not lead to
3151 // additional code. This is true if either both sides of the select
3152 // fold to a constant (in which case the icmp is replaced with a select
3153 // which will usually simplify) or this is the only user of the
3154 // select (in which case we are trading a select+icmp for a simpler
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003155 // select+icmp) or all uses of the select can be replaced based on
3156 // dominance information ("Global cases").
3157 bool Transform = false;
3158 if (Op1 && Op2)
3159 Transform = true;
3160 else if (Op1 || Op2) {
3161 // Local case
3162 if (LHSI->hasOneUse())
3163 Transform = true;
3164 // Global cases
3165 else if (CI && !CI->isZero())
3166 // When Op1 is constant try replacing select with second operand.
3167 // Otherwise Op2 is constant and try replacing select with first
3168 // operand.
3169 Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
3170 Op1 ? 2 : 1);
3171 }
3172 if (Transform) {
Chris Lattner2188e402010-01-04 07:37:31 +00003173 if (!Op1)
3174 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3175 RHSC, I.getName());
3176 if (!Op2)
3177 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3178 RHSC, I.getName());
3179 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3180 }
3181 break;
3182 }
Chris Lattner2188e402010-01-04 07:37:31 +00003183 case Instruction::IntToPtr:
3184 // icmp pred inttoptr(X), null -> icmp pred X, 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003185 if (RHSC->isNullValue() &&
3186 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
Chris Lattner2188e402010-01-04 07:37:31 +00003187 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3188 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3189 break;
3190
3191 case Instruction::Load:
3192 // Try to optimize things like "A[i] > 4" to index computations.
3193 if (GetElementPtrInst *GEP =
3194 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3195 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3196 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3197 !cast<LoadInst>(LHSI)->isVolatile())
3198 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3199 return Res;
3200 }
3201 break;
3202 }
3203 }
3204
3205 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3206 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
3207 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
3208 return NI;
3209 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
3210 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
3211 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3212 return NI;
3213
3214 // Test to see if the operands of the icmp are casted versions of other
3215 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3216 // now.
3217 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003218 if (Op0->getType()->isPointerTy() &&
3219 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003220 // We keep moving the cast from the left operand over to the right
3221 // operand, where it can often be eliminated completely.
3222 Op0 = CI->getOperand(0);
3223
3224 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3225 // so eliminate it as well.
3226 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3227 Op1 = CI2->getOperand(0);
3228
3229 // If Op1 is a constant, we can fold the cast into the constant.
3230 if (Op0->getType() != Op1->getType()) {
3231 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3232 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3233 } else {
3234 // Otherwise, cast the RHS right before the icmp
3235 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3236 }
3237 }
3238 return new ICmpInst(I.getPredicate(), Op0, Op1);
3239 }
3240 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003241
Chris Lattner2188e402010-01-04 07:37:31 +00003242 if (isa<CastInst>(Op0)) {
3243 // Handle the special case of: icmp (cast bool to X), <cst>
3244 // This comes up when you have code like
3245 // int X = A < B;
3246 // if (X) ...
3247 // For generality, we handle any zero-extension of any operand comparison
3248 // with a constant or another cast from the same type.
3249 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
3250 if (Instruction *R = visitICmpInstWithCastAndCast(I))
3251 return R;
3252 }
Chris Lattner2188e402010-01-04 07:37:31 +00003253
Duncan Sandse5220012011-02-17 07:46:37 +00003254 // Special logic for binary operators.
3255 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3256 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3257 if (BO0 || BO1) {
3258 CmpInst::Predicate Pred = I.getPredicate();
3259 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3260 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3261 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3262 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3263 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3264 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3265 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3266 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3267 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3268
3269 // Analyze the case when either Op0 or Op1 is an add instruction.
3270 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
Craig Topperf40110f2014-04-25 05:29:35 +00003271 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Duncan Sandse5220012011-02-17 07:46:37 +00003272 if (BO0 && BO0->getOpcode() == Instruction::Add)
3273 A = BO0->getOperand(0), B = BO0->getOperand(1);
3274 if (BO1 && BO1->getOpcode() == Instruction::Add)
3275 C = BO1->getOperand(0), D = BO1->getOperand(1);
3276
David Majnemer549f4f22014-11-01 09:09:51 +00003277 // icmp (X+cst) < 0 --> X < -cst
3278 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
3279 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
3280 if (!RHSC->isMinValue(/*isSigned=*/true))
3281 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
3282
Duncan Sandse5220012011-02-17 07:46:37 +00003283 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3284 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3285 return new ICmpInst(Pred, A == Op1 ? B : A,
3286 Constant::getNullValue(Op1->getType()));
3287
3288 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3289 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3290 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3291 C == Op0 ? D : C);
3292
Duncan Sands84653b32011-02-18 16:25:37 +00003293 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003294 if (A && C && (A == C || A == D || B == C || B == D) &&
3295 NoOp0WrapProblem && NoOp1WrapProblem &&
3296 // Try not to increase register pressure.
3297 BO0->hasOneUse() && BO1->hasOneUse()) {
3298 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003299 Value *Y, *Z;
3300 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003301 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003302 Y = B;
3303 Z = D;
3304 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003305 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003306 Y = B;
3307 Z = C;
3308 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003309 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003310 Y = A;
3311 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003312 } else {
3313 assert(B == D);
3314 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003315 Y = A;
3316 Z = C;
3317 }
Duncan Sandse5220012011-02-17 07:46:37 +00003318 return new ICmpInst(Pred, Y, Z);
3319 }
3320
David Majnemerb81cd632013-04-11 20:05:46 +00003321 // icmp slt (X + -1), Y -> icmp sle X, Y
3322 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3323 match(B, m_AllOnes()))
3324 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3325
3326 // icmp sge (X + -1), Y -> icmp sgt X, Y
3327 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3328 match(B, m_AllOnes()))
3329 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3330
3331 // icmp sle (X + 1), Y -> icmp slt X, Y
3332 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3333 match(B, m_One()))
3334 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3335
3336 // icmp sgt (X + 1), Y -> icmp sge X, Y
3337 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3338 match(B, m_One()))
3339 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3340
3341 // if C1 has greater magnitude than C2:
3342 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3343 // s.t. C3 = C1 - C2
3344 //
3345 // if C2 has greater magnitude than C1:
3346 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3347 // s.t. C3 = C2 - C1
3348 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3349 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3350 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3351 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3352 const APInt &AP1 = C1->getValue();
3353 const APInt &AP2 = C2->getValue();
3354 if (AP1.isNegative() == AP2.isNegative()) {
3355 APInt AP1Abs = C1->getValue().abs();
3356 APInt AP2Abs = C2->getValue().abs();
3357 if (AP1Abs.uge(AP2Abs)) {
3358 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
3359 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
3360 return new ICmpInst(Pred, NewAdd, C);
3361 } else {
3362 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
3363 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
3364 return new ICmpInst(Pred, A, NewAdd);
3365 }
3366 }
3367 }
3368
3369
Duncan Sandse5220012011-02-17 07:46:37 +00003370 // Analyze the case when either Op0 or Op1 is a sub instruction.
3371 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
Craig Topperf40110f2014-04-25 05:29:35 +00003372 A = nullptr; B = nullptr; C = nullptr; D = nullptr;
Duncan Sandse5220012011-02-17 07:46:37 +00003373 if (BO0 && BO0->getOpcode() == Instruction::Sub)
3374 A = BO0->getOperand(0), B = BO0->getOperand(1);
3375 if (BO1 && BO1->getOpcode() == Instruction::Sub)
3376 C = BO1->getOperand(0), D = BO1->getOperand(1);
3377
Duncan Sands84653b32011-02-18 16:25:37 +00003378 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3379 if (A == Op1 && NoOp0WrapProblem)
3380 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3381
3382 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
3383 if (C == Op0 && NoOp1WrapProblem)
3384 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3385
3386 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003387 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
3388 // Try not to increase register pressure.
3389 BO0->hasOneUse() && BO1->hasOneUse())
3390 return new ICmpInst(Pred, A, C);
3391
Duncan Sands84653b32011-02-18 16:25:37 +00003392 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
3393 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3394 // Try not to increase register pressure.
3395 BO0->hasOneUse() && BO1->hasOneUse())
3396 return new ICmpInst(Pred, D, B);
3397
David Majnemer186c9422014-05-15 00:02:20 +00003398 // icmp (0-X) < cst --> x > -cst
3399 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3400 Value *X;
3401 if (match(BO0, m_Neg(m_Value(X))))
3402 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
3403 if (!RHSC->isMinValue(/*isSigned=*/true))
3404 return new ICmpInst(I.getSwappedPredicate(), X,
3405 ConstantExpr::getNeg(RHSC));
3406 }
3407
Craig Topperf40110f2014-04-25 05:29:35 +00003408 BinaryOperator *SRem = nullptr;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003409 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00003410 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
3411 Op1 == BO0->getOperand(1))
3412 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003413 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00003414 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3415 Op0 == BO1->getOperand(1))
3416 SRem = BO1;
3417 if (SRem) {
3418 // We don't check hasOneUse to avoid increasing register pressure because
3419 // the value we use is the same value this instruction was already using.
3420 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
3421 default: break;
3422 case ICmpInst::ICMP_EQ:
Nick Lewycky92db8e82011-03-06 03:36:19 +00003423 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003424 case ICmpInst::ICMP_NE:
Nick Lewycky92db8e82011-03-06 03:36:19 +00003425 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003426 case ICmpInst::ICMP_SGT:
3427 case ICmpInst::ICMP_SGE:
3428 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
3429 Constant::getAllOnesValue(SRem->getType()));
3430 case ICmpInst::ICMP_SLT:
3431 case ICmpInst::ICMP_SLE:
3432 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
3433 Constant::getNullValue(SRem->getType()));
3434 }
3435 }
3436
Duncan Sandse5220012011-02-17 07:46:37 +00003437 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
3438 BO0->hasOneUse() && BO1->hasOneUse() &&
3439 BO0->getOperand(1) == BO1->getOperand(1)) {
3440 switch (BO0->getOpcode()) {
3441 default: break;
3442 case Instruction::Add:
3443 case Instruction::Sub:
3444 case Instruction::Xor:
3445 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
3446 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3447 BO1->getOperand(0));
3448 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
3449 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3450 if (CI->getValue().isSignBit()) {
3451 ICmpInst::Predicate Pred = I.isSigned()
3452 ? I.getUnsignedPredicate()
3453 : I.getSignedPredicate();
3454 return new ICmpInst(Pred, BO0->getOperand(0),
3455 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00003456 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003457
Chris Lattnerb1a15122011-07-15 06:08:15 +00003458 if (CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00003459 ICmpInst::Predicate Pred = I.isSigned()
3460 ? I.getUnsignedPredicate()
3461 : I.getSignedPredicate();
3462 Pred = I.getSwappedPredicate(Pred);
3463 return new ICmpInst(Pred, BO0->getOperand(0),
3464 BO1->getOperand(0));
3465 }
Chris Lattner2188e402010-01-04 07:37:31 +00003466 }
Duncan Sandse5220012011-02-17 07:46:37 +00003467 break;
3468 case Instruction::Mul:
3469 if (!I.isEquality())
3470 break;
3471
3472 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3473 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
3474 // Mask = -1 >> count-trailing-zeros(Cst).
3475 if (!CI->isZero() && !CI->isOne()) {
3476 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003477 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00003478 APInt::getLowBitsSet(AP.getBitWidth(),
3479 AP.getBitWidth() -
3480 AP.countTrailingZeros()));
3481 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
3482 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
3483 return new ICmpInst(I.getPredicate(), And1, And2);
3484 }
3485 }
3486 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00003487 case Instruction::UDiv:
3488 case Instruction::LShr:
3489 if (I.isSigned())
3490 break;
3491 // fall-through
3492 case Instruction::SDiv:
3493 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00003494 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00003495 break;
3496 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3497 BO1->getOperand(0));
3498 case Instruction::Shl: {
3499 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
3500 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
3501 if (!NUW && !NSW)
3502 break;
3503 if (!NSW && I.isSigned())
3504 break;
3505 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3506 BO1->getOperand(0));
3507 }
Chris Lattner2188e402010-01-04 07:37:31 +00003508 }
3509 }
Sanjoy Dasc86c1622015-08-21 22:22:37 +00003510
3511 if (BO0) {
3512 // Transform A & (L - 1) `ult` L --> L != 0
3513 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
3514 auto BitwiseAnd =
3515 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
3516
3517 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
3518 auto *Zero = Constant::getNullValue(BO0->getType());
3519 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
3520 }
3521 }
Chris Lattner2188e402010-01-04 07:37:31 +00003522 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003523
Chris Lattner2188e402010-01-04 07:37:31 +00003524 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00003525 // Transform (A & ~B) == 0 --> (A & B) != 0
3526 // and (A & ~B) != 0 --> (A & B) == 0
3527 // if A is a power of 2.
3528 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00003529 match(Op1, m_Zero()) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003530 isKnownToBeAPowerOfTwo(A, DL, false, 0, AC, &I, DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00003531 return new ICmpInst(I.getInversePredicate(),
3532 Builder->CreateAnd(A, B),
3533 Op1);
3534
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00003535 // ~x < ~y --> y < x
3536 // ~x < cst --> ~cst < x
3537 if (match(Op0, m_Not(m_Value(A)))) {
3538 if (match(Op1, m_Not(m_Value(B))))
3539 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00003540 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00003541 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
3542 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003543
Sanjoy Dasb6c59142015-04-10 21:07:09 +00003544 Instruction *AddI = nullptr;
3545 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
3546 m_Instruction(AddI))) &&
3547 isa<IntegerType>(A->getType())) {
3548 Value *Result;
3549 Constant *Overflow;
3550 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
3551 Overflow)) {
3552 ReplaceInstUsesWith(*AddI, Result);
3553 return ReplaceInstUsesWith(I, Overflow);
3554 }
3555 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003556
3557 // (zext a) * (zext b) --> llvm.umul.with.overflow.
3558 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
3559 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
3560 return R;
3561 }
3562 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
3563 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
3564 return R;
3565 }
Chris Lattner2188e402010-01-04 07:37:31 +00003566 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003567
Chris Lattner2188e402010-01-04 07:37:31 +00003568 if (I.isEquality()) {
3569 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00003570
Chris Lattner2188e402010-01-04 07:37:31 +00003571 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3572 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
3573 Value *OtherVal = A == Op1 ? B : A;
3574 return new ICmpInst(I.getPredicate(), OtherVal,
3575 Constant::getNullValue(A->getType()));
3576 }
3577
3578 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
3579 // A^c1 == C^c2 --> A == C^(c1^c2)
3580 ConstantInt *C1, *C2;
3581 if (match(B, m_ConstantInt(C1)) &&
3582 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00003583 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003584 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00003585 return new ICmpInst(I.getPredicate(), A, Xor);
3586 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003587
Chris Lattner2188e402010-01-04 07:37:31 +00003588 // A^B == A^D -> B == D
3589 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
3590 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
3591 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
3592 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
3593 }
3594 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003595
Chris Lattner2188e402010-01-04 07:37:31 +00003596 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
3597 (A == Op0 || B == Op0)) {
3598 // A == (A^B) -> B == 0
3599 Value *OtherVal = A == Op0 ? B : A;
3600 return new ICmpInst(I.getPredicate(), OtherVal,
3601 Constant::getNullValue(A->getType()));
3602 }
3603
Chris Lattner2188e402010-01-04 07:37:31 +00003604 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00003605 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00003606 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Craig Topperf40110f2014-04-25 05:29:35 +00003607 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003608
Chris Lattner2188e402010-01-04 07:37:31 +00003609 if (A == C) {
3610 X = B; Y = D; Z = A;
3611 } else if (A == D) {
3612 X = B; Y = C; Z = A;
3613 } else if (B == C) {
3614 X = A; Y = D; Z = B;
3615 } else if (B == D) {
3616 X = A; Y = C; Z = B;
3617 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003618
Chris Lattner2188e402010-01-04 07:37:31 +00003619 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003620 Op1 = Builder->CreateXor(X, Y);
3621 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00003622 I.setOperand(0, Op1);
3623 I.setOperand(1, Constant::getNullValue(Op1->getType()));
3624 return &I;
3625 }
3626 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003627
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00003628 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00003629 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00003630 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00003631 if ((Op0->hasOneUse() &&
3632 match(Op0, m_ZExt(m_Value(A))) &&
3633 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
3634 (Op1->hasOneUse() &&
3635 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
3636 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00003637 APInt Pow2 = Cst1->getValue() + 1;
3638 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
3639 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
3640 return new ICmpInst(I.getPredicate(), A,
3641 Builder->CreateTrunc(B, A->getType()));
3642 }
3643
Benjamin Kramer03f3e242013-11-16 16:00:48 +00003644 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
3645 // For lshr and ashr pairs.
3646 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3647 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
3648 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3649 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
3650 unsigned TypeBits = Cst1->getBitWidth();
3651 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3652 if (ShAmt < TypeBits && ShAmt != 0) {
3653 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
3654 ? ICmpInst::ICMP_UGE
3655 : ICmpInst::ICMP_ULT;
3656 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
3657 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
3658 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
3659 }
3660 }
3661
Benjamin Kramer7fa8c432015-03-26 17:12:06 +00003662 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
3663 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
3664 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
3665 unsigned TypeBits = Cst1->getBitWidth();
3666 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3667 if (ShAmt < TypeBits && ShAmt != 0) {
3668 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
3669 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
3670 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
3671 I.getName() + ".mask");
3672 return new ICmpInst(I.getPredicate(), And,
3673 Constant::getNullValue(Cst1->getType()));
3674 }
3675 }
3676
Chris Lattner1b06c712011-04-26 20:18:20 +00003677 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
3678 // "icmp (and X, mask), cst"
3679 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00003680 if (Op0->hasOneUse() &&
3681 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
3682 m_ConstantInt(ShAmt))))) &&
3683 match(Op1, m_ConstantInt(Cst1)) &&
3684 // Only do this when A has multiple uses. This is most important to do
3685 // when it exposes other optimizations.
3686 !A->hasOneUse()) {
3687 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003688
Chris Lattner1b06c712011-04-26 20:18:20 +00003689 if (ShAmt < ASize) {
3690 APInt MaskV =
3691 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
3692 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003693
Chris Lattner1b06c712011-04-26 20:18:20 +00003694 APInt CmpV = Cst1->getValue().zext(ASize);
3695 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003696
Chris Lattner1b06c712011-04-26 20:18:20 +00003697 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
3698 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
3699 }
3700 }
Chris Lattner2188e402010-01-04 07:37:31 +00003701 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003702
David Majnemerc1eca5a2014-11-06 23:23:30 +00003703 // The 'cmpxchg' instruction returns an aggregate containing the old value and
3704 // an i1 which indicates whether or not we successfully did the swap.
3705 //
3706 // Replace comparisons between the old value and the expected value with the
3707 // indicator that 'cmpxchg' returns.
3708 //
3709 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
3710 // spuriously fail. In those cases, the old value may equal the expected
3711 // value but it is possible for the swap to not occur.
3712 if (I.getPredicate() == ICmpInst::ICMP_EQ)
3713 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
3714 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
3715 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
3716 !ACXI->isWeak())
3717 return ExtractValueInst::Create(ACXI, 1);
3718
Chris Lattner2188e402010-01-04 07:37:31 +00003719 {
3720 Value *X; ConstantInt *Cst;
3721 // icmp X+Cst, X
3722 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00003723 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00003724
3725 // icmp X, X+Cst
3726 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00003727 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00003728 }
Craig Topperf40110f2014-04-25 05:29:35 +00003729 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003730}
3731
Chris Lattner2188e402010-01-04 07:37:31 +00003732/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
Chris Lattner2188e402010-01-04 07:37:31 +00003733Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
3734 Instruction *LHSI,
3735 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00003736 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003737 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003738
Chris Lattner2188e402010-01-04 07:37:31 +00003739 // Get the width of the mantissa. We don't want to hack on conversions that
3740 // might lose information from the integer, e.g. "i64 -> float"
3741 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00003742 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003743
Matt Arsenault55e73122015-01-06 15:50:59 +00003744 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
3745
Chris Lattner2188e402010-01-04 07:37:31 +00003746 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003747
Matt Arsenault55e73122015-01-06 15:50:59 +00003748 if (I.isEquality()) {
3749 FCmpInst::Predicate P = I.getPredicate();
3750 bool IsExact = false;
3751 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
3752 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
3753
3754 // If the floating point constant isn't an integer value, we know if we will
3755 // ever compare equal / not equal to it.
3756 if (!IsExact) {
3757 // TODO: Can never be -0.0 and other non-representable values
3758 APFloat RHSRoundInt(RHS);
3759 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
3760 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
3761 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
3762 return ReplaceInstUsesWith(I, Builder->getFalse());
3763
3764 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
3765 return ReplaceInstUsesWith(I, Builder->getTrue());
3766 }
3767 }
3768
3769 // TODO: If the constant is exactly representable, is it always OK to do
3770 // equality compares as integer?
3771 }
3772
Arch D. Robison8ed08542015-09-15 17:51:59 +00003773 // Check to see that the input is converted from an integer type that is small
3774 // enough that preserves all bits. TODO: check here for "known" sign bits.
3775 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
3776 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00003777
Arch D. Robison8ed08542015-09-15 17:51:59 +00003778 // Following test does NOT adjust InputSize downwards for signed inputs,
3779 // because the most negative value still requires all the mantissa bits
3780 // to distinguish it from one less than that value.
3781 if ((int)InputSize > MantissaWidth) {
3782 // Conversion would lose accuracy. Check if loss can impact comparison.
3783 int Exp = ilogb(RHS);
3784 if (Exp == APFloat::IEK_Inf) {
3785 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
3786 if (MaxExponent < (int)InputSize - !LHSUnsigned)
3787 // Conversion could create infinity.
3788 return nullptr;
3789 } else {
3790 // Note that if RHS is zero or NaN, then Exp is negative
3791 // and first condition is trivially false.
3792 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
3793 // Conversion could affect comparison.
3794 return nullptr;
3795 }
3796 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003797
Chris Lattner2188e402010-01-04 07:37:31 +00003798 // Otherwise, we can potentially simplify the comparison. We know that it
3799 // will always come through as an integer value and we know the constant is
3800 // not a NAN (it would have been previously simplified).
3801 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00003802
Chris Lattner2188e402010-01-04 07:37:31 +00003803 ICmpInst::Predicate Pred;
3804 switch (I.getPredicate()) {
3805 default: llvm_unreachable("Unexpected predicate!");
3806 case FCmpInst::FCMP_UEQ:
3807 case FCmpInst::FCMP_OEQ:
3808 Pred = ICmpInst::ICMP_EQ;
3809 break;
3810 case FCmpInst::FCMP_UGT:
3811 case FCmpInst::FCMP_OGT:
3812 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
3813 break;
3814 case FCmpInst::FCMP_UGE:
3815 case FCmpInst::FCMP_OGE:
3816 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
3817 break;
3818 case FCmpInst::FCMP_ULT:
3819 case FCmpInst::FCMP_OLT:
3820 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
3821 break;
3822 case FCmpInst::FCMP_ULE:
3823 case FCmpInst::FCMP_OLE:
3824 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
3825 break;
3826 case FCmpInst::FCMP_UNE:
3827 case FCmpInst::FCMP_ONE:
3828 Pred = ICmpInst::ICMP_NE;
3829 break;
3830 case FCmpInst::FCMP_ORD:
Jakub Staszakbddea112013-06-06 20:18:46 +00003831 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003832 case FCmpInst::FCMP_UNO:
Jakub Staszakbddea112013-06-06 20:18:46 +00003833 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003834 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003835
Chris Lattner2188e402010-01-04 07:37:31 +00003836 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003837
Chris Lattner2188e402010-01-04 07:37:31 +00003838 // See if the FP constant is too large for the integer. For example,
3839 // comparing an i8 to 300.0.
3840 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003841
Chris Lattner2188e402010-01-04 07:37:31 +00003842 if (!LHSUnsigned) {
3843 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
3844 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00003845 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003846 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
3847 APFloat::rmNearestTiesToEven);
3848 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
3849 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
3850 Pred == ICmpInst::ICMP_SLE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003851 return ReplaceInstUsesWith(I, Builder->getTrue());
3852 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003853 }
3854 } else {
3855 // If the RHS value is > UnsignedMax, fold the comparison. This handles
3856 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00003857 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003858 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
3859 APFloat::rmNearestTiesToEven);
3860 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
3861 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
3862 Pred == ICmpInst::ICMP_ULE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003863 return ReplaceInstUsesWith(I, Builder->getTrue());
3864 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003865 }
3866 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003867
Chris Lattner2188e402010-01-04 07:37:31 +00003868 if (!LHSUnsigned) {
3869 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00003870 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003871 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
3872 APFloat::rmNearestTiesToEven);
3873 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
3874 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
3875 Pred == ICmpInst::ICMP_SGE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003876 return ReplaceInstUsesWith(I, Builder->getTrue());
3877 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003878 }
Devang Patel698452b2012-02-13 23:05:18 +00003879 } else {
3880 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00003881 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00003882 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
3883 APFloat::rmNearestTiesToEven);
3884 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
3885 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
3886 Pred == ICmpInst::ICMP_UGE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003887 return ReplaceInstUsesWith(I, Builder->getTrue());
3888 return ReplaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00003889 }
Chris Lattner2188e402010-01-04 07:37:31 +00003890 }
3891
3892 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
3893 // [0, UMAX], but it may still be fractional. See if it is fractional by
3894 // casting the FP value to the integer value and back, checking for equality.
3895 // Don't do this for zero, because -0.0 is not fractional.
3896 Constant *RHSInt = LHSUnsigned
3897 ? ConstantExpr::getFPToUI(RHSC, IntTy)
3898 : ConstantExpr::getFPToSI(RHSC, IntTy);
3899 if (!RHS.isZero()) {
3900 bool Equal = LHSUnsigned
3901 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
3902 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
3903 if (!Equal) {
3904 // If we had a comparison against a fractional value, we have to adjust
3905 // the compare predicate and sometimes the value. RHSC is rounded towards
3906 // zero at this point.
3907 switch (Pred) {
3908 default: llvm_unreachable("Unexpected integer comparison!");
3909 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Jakub Staszakbddea112013-06-06 20:18:46 +00003910 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003911 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Jakub Staszakbddea112013-06-06 20:18:46 +00003912 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003913 case ICmpInst::ICMP_ULE:
3914 // (float)int <= 4.4 --> int <= 4
3915 // (float)int <= -4.4 --> false
3916 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003917 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003918 break;
3919 case ICmpInst::ICMP_SLE:
3920 // (float)int <= 4.4 --> int <= 4
3921 // (float)int <= -4.4 --> int < -4
3922 if (RHS.isNegative())
3923 Pred = ICmpInst::ICMP_SLT;
3924 break;
3925 case ICmpInst::ICMP_ULT:
3926 // (float)int < -4.4 --> false
3927 // (float)int < 4.4 --> int <= 4
3928 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003929 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003930 Pred = ICmpInst::ICMP_ULE;
3931 break;
3932 case ICmpInst::ICMP_SLT:
3933 // (float)int < -4.4 --> int < -4
3934 // (float)int < 4.4 --> int <= 4
3935 if (!RHS.isNegative())
3936 Pred = ICmpInst::ICMP_SLE;
3937 break;
3938 case ICmpInst::ICMP_UGT:
3939 // (float)int > 4.4 --> int > 4
3940 // (float)int > -4.4 --> true
3941 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003942 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003943 break;
3944 case ICmpInst::ICMP_SGT:
3945 // (float)int > 4.4 --> int > 4
3946 // (float)int > -4.4 --> int >= -4
3947 if (RHS.isNegative())
3948 Pred = ICmpInst::ICMP_SGE;
3949 break;
3950 case ICmpInst::ICMP_UGE:
3951 // (float)int >= -4.4 --> true
3952 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00003953 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003954 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003955 Pred = ICmpInst::ICMP_UGT;
3956 break;
3957 case ICmpInst::ICMP_SGE:
3958 // (float)int >= -4.4 --> int >= -4
3959 // (float)int >= 4.4 --> int > 4
3960 if (!RHS.isNegative())
3961 Pred = ICmpInst::ICMP_SGT;
3962 break;
3963 }
3964 }
3965 }
3966
3967 // Lower this FP comparison into an appropriate integer version of the
3968 // comparison.
3969 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
3970}
3971
3972Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
3973 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003974
Chris Lattner2188e402010-01-04 07:37:31 +00003975 /// Orders the operands of the compare so that they are listed from most
3976 /// complex to least complex. This puts constants before unary operators,
3977 /// before binary operators.
3978 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
3979 I.swapOperands();
3980 Changed = true;
3981 }
3982
3983 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003984
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003985 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
3986 I.getFastMathFlags(), DL, TLI, DT, AC, &I))
Chris Lattner2188e402010-01-04 07:37:31 +00003987 return ReplaceInstUsesWith(I, V);
3988
3989 // Simplify 'fcmp pred X, X'
3990 if (Op0 == Op1) {
3991 switch (I.getPredicate()) {
3992 default: llvm_unreachable("Unknown predicate!");
3993 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
3994 case FCmpInst::FCMP_ULT: // True if unordered or less than
3995 case FCmpInst::FCMP_UGT: // True if unordered or greater than
3996 case FCmpInst::FCMP_UNE: // True if unordered or not equal
3997 // Canonicalize these to be 'fcmp uno %X, 0.0'.
3998 I.setPredicate(FCmpInst::FCMP_UNO);
3999 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4000 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004001
Chris Lattner2188e402010-01-04 07:37:31 +00004002 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4003 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4004 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4005 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4006 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4007 I.setPredicate(FCmpInst::FCMP_ORD);
4008 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4009 return &I;
4010 }
4011 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004012
James Molloy2b21a7c2015-05-20 18:41:25 +00004013 // Test if the FCmpInst instruction is used exclusively by a select as
4014 // part of a minimum or maximum operation. If so, refrain from doing
4015 // any other folding. This helps out other analyses which understand
4016 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4017 // and CodeGen. And in this case, at least one of the comparison
4018 // operands has at least one user besides the compare (the select),
4019 // which would often largely negate the benefit of folding anyway.
4020 if (I.hasOneUse())
4021 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4022 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4023 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4024 return nullptr;
4025
Chris Lattner2188e402010-01-04 07:37:31 +00004026 // Handle fcmp with constant RHS
4027 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4028 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4029 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004030 case Instruction::FPExt: {
4031 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4032 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4033 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4034 if (!RHSF)
4035 break;
4036
4037 const fltSemantics *Sem;
4038 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004039 if (LHSExt->getSrcTy()->isHalfTy())
4040 Sem = &APFloat::IEEEhalf;
4041 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004042 Sem = &APFloat::IEEEsingle;
4043 else if (LHSExt->getSrcTy()->isDoubleTy())
4044 Sem = &APFloat::IEEEdouble;
4045 else if (LHSExt->getSrcTy()->isFP128Ty())
4046 Sem = &APFloat::IEEEquad;
4047 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
4048 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004049 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
4050 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004051 else
4052 break;
4053
4054 bool Lossy;
4055 APFloat F = RHSF->getValueAPF();
4056 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4057
Jim Grosbach24ff8342011-09-30 18:45:50 +00004058 // Avoid lossy conversions and denormals. Zero is a special case
4059 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004060 APFloat Fabs = F;
4061 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004062 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004063 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4064 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004065
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004066 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4067 ConstantFP::get(RHSC->getContext(), F));
4068 break;
4069 }
Chris Lattner2188e402010-01-04 07:37:31 +00004070 case Instruction::PHI:
4071 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4072 // block. If in the same block, we're encouraging jump threading. If
4073 // not, we are just pessimizing the code by making an i1 phi.
4074 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004075 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004076 return NV;
4077 break;
4078 case Instruction::SIToFP:
4079 case Instruction::UIToFP:
4080 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
4081 return NV;
4082 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004083 case Instruction::FSub: {
4084 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4085 Value *Op;
4086 if (match(LHSI, m_FNeg(m_Value(Op))))
4087 return new FCmpInst(I.getSwappedPredicate(), Op,
4088 ConstantExpr::getFNeg(RHSC));
4089 break;
4090 }
Dan Gohman94732022010-02-24 06:46:09 +00004091 case Instruction::Load:
4092 if (GetElementPtrInst *GEP =
4093 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4094 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4095 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4096 !cast<LoadInst>(LHSI)->isVolatile())
4097 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
4098 return Res;
4099 }
4100 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004101 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004102 if (!RHSC->isNullValue())
4103 break;
4104
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004105 CallInst *CI = cast<CallInst>(LHSI);
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004106 const Function *F = CI->getCalledFunction();
4107 if (!F)
4108 break;
4109
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004110 // Various optimization for fabs compared with zero.
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004111 LibFunc::Func Func;
4112 if (F->getIntrinsicID() == Intrinsic::fabs ||
4113 (TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
4114 (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
4115 Func == LibFunc::fabsl))) {
4116 switch (I.getPredicate()) {
4117 default:
4118 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004119 // fabs(x) < 0 --> false
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004120 case FCmpInst::FCMP_OLT:
4121 return ReplaceInstUsesWith(I, Builder->getFalse());
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004122 // fabs(x) > 0 --> x != 0
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004123 case FCmpInst::FCMP_OGT:
4124 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004125 // fabs(x) <= 0 --> x == 0
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004126 case FCmpInst::FCMP_OLE:
4127 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004128 // fabs(x) >= 0 --> !isnan(x)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004129 case FCmpInst::FCMP_OGE:
4130 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004131 // fabs(x) == 0 --> x == 0
4132 // fabs(x) != 0 --> x != 0
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004133 case FCmpInst::FCMP_OEQ:
4134 case FCmpInst::FCMP_UEQ:
4135 case FCmpInst::FCMP_ONE:
4136 case FCmpInst::FCMP_UNE:
4137 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004138 }
4139 }
4140 }
Chris Lattner2188e402010-01-04 07:37:31 +00004141 }
Chris Lattner2188e402010-01-04 07:37:31 +00004142 }
4143
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004144 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004145 Value *X, *Y;
4146 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004147 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004148
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004149 // fcmp (fpext x), (fpext y) -> fcmp x, y
4150 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4151 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4152 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4153 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4154 RHSExt->getOperand(0));
4155
Craig Topperf40110f2014-04-25 05:29:35 +00004156 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004157}