blob: aead00073759fb725c004f19f3f363819129f7b1 [file] [log] [blame]
Chris Lattner2188e402010-01-04 07:37:31 +00001//===- InstCombineCompares.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitICmp and visitFCmp functions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2188e402010-01-04 07:37:31 +000016#include "llvm/Analysis/InstructionSimplify.h"
17#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000018#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000020#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000022#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Target/TargetLibraryInfo.h"
Gerolf Hoflehnerc0b4c202014-10-07 00:16:12 +000024
Chris Lattner2188e402010-01-04 07:37:31 +000025using namespace llvm;
26using namespace PatternMatch;
27
Chandler Carruth964daaa2014-04-22 02:55:47 +000028#define DEBUG_TYPE "instcombine"
29
Chris Lattner98457102011-02-10 05:23:05 +000030static ConstantInt *getOne(Constant *C) {
31 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
32}
33
Chris Lattner2188e402010-01-04 07:37:31 +000034static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
35 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
36}
37
38static bool HasAddOverflow(ConstantInt *Result,
39 ConstantInt *In1, ConstantInt *In2,
40 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000041 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000042 return Result->getValue().ult(In1->getValue());
Chris Lattnerb1a15122011-07-15 06:08:15 +000043
44 if (In2->isNegative())
45 return Result->getValue().sgt(In1->getValue());
46 return Result->getValue().slt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000047}
48
49/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
50/// overflowed for this type.
51static bool AddWithOverflow(Constant *&Result, Constant *In1,
52 Constant *In2, bool IsSigned = false) {
53 Result = ConstantExpr::getAdd(In1, In2);
54
Chris Lattner229907c2011-07-18 04:54:35 +000055 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000056 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
57 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
58 if (HasAddOverflow(ExtractElement(Result, Idx),
59 ExtractElement(In1, Idx),
60 ExtractElement(In2, Idx),
61 IsSigned))
62 return true;
63 }
64 return false;
65 }
66
67 return HasAddOverflow(cast<ConstantInt>(Result),
68 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
69 IsSigned);
70}
71
72static bool HasSubOverflow(ConstantInt *Result,
73 ConstantInt *In1, ConstantInt *In2,
74 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000075 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000076 return Result->getValue().ugt(In1->getValue());
Jim Grosbach129c52a2011-09-30 18:09:53 +000077
Chris Lattnerb1a15122011-07-15 06:08:15 +000078 if (In2->isNegative())
79 return Result->getValue().slt(In1->getValue());
80
81 return Result->getValue().sgt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000082}
83
84/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
85/// overflowed for this type.
86static bool SubWithOverflow(Constant *&Result, Constant *In1,
87 Constant *In2, bool IsSigned = false) {
88 Result = ConstantExpr::getSub(In1, In2);
89
Chris Lattner229907c2011-07-18 04:54:35 +000090 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000091 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
92 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
93 if (HasSubOverflow(ExtractElement(Result, Idx),
94 ExtractElement(In1, Idx),
95 ExtractElement(In2, Idx),
96 IsSigned))
97 return true;
98 }
99 return false;
100 }
101
102 return HasSubOverflow(cast<ConstantInt>(Result),
103 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
104 IsSigned);
105}
106
107/// isSignBitCheck - Given an exploded icmp instruction, return true if the
108/// comparison only checks the sign bit. If it only checks the sign bit, set
109/// TrueIfSigned if the result of the comparison is true when the input value is
110/// signed.
111static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
112 bool &TrueIfSigned) {
113 switch (pred) {
114 case ICmpInst::ICMP_SLT: // True if LHS s< 0
115 TrueIfSigned = true;
116 return RHS->isZero();
117 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
118 TrueIfSigned = true;
119 return RHS->isAllOnesValue();
120 case ICmpInst::ICMP_SGT: // True if LHS s> -1
121 TrueIfSigned = false;
122 return RHS->isAllOnesValue();
123 case ICmpInst::ICMP_UGT:
124 // True if LHS u> RHS and RHS == high-bit-mask - 1
125 TrueIfSigned = true;
Chris Lattnerb1a15122011-07-15 06:08:15 +0000126 return RHS->isMaxValue(true);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000127 case ICmpInst::ICMP_UGE:
Chris Lattner2188e402010-01-04 07:37:31 +0000128 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
129 TrueIfSigned = true;
130 return RHS->getValue().isSignBit();
131 default:
132 return false;
133 }
134}
135
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000136/// Returns true if the exploded icmp can be expressed as a signed comparison
137/// to zero and updates the predicate accordingly.
138/// The signedness of the comparison is preserved.
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000139static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
140 if (!ICmpInst::isSigned(pred))
141 return false;
142
143 if (RHS->isZero())
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000144 return ICmpInst::isRelational(pred);
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000145
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000146 if (RHS->isOne()) {
147 if (pred == ICmpInst::ICMP_SLT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000148 pred = ICmpInst::ICMP_SLE;
149 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000150 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000151 } else if (RHS->isAllOnesValue()) {
152 if (pred == ICmpInst::ICMP_SGT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000153 pred = ICmpInst::ICMP_SGE;
154 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000155 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000156 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000157
158 return false;
159}
160
Chris Lattner2188e402010-01-04 07:37:31 +0000161// isHighOnes - Return true if the constant is of the form 1+0+.
162// This is the same as lowones(~X).
163static bool isHighOnes(const ConstantInt *CI) {
164 return (~CI->getValue() + 1).isPowerOf2();
165}
166
Jim Grosbach129c52a2011-09-30 18:09:53 +0000167/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
Chris Lattner2188e402010-01-04 07:37:31 +0000168/// set of known zero and one bits, compute the maximum and minimum values that
169/// could have the specified known zero and known one bits, returning them in
170/// min/max.
171static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
172 const APInt& KnownOne,
173 APInt& Min, APInt& Max) {
174 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
175 KnownZero.getBitWidth() == Min.getBitWidth() &&
176 KnownZero.getBitWidth() == Max.getBitWidth() &&
177 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
178 APInt UnknownBits = ~(KnownZero|KnownOne);
179
180 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
181 // bit if it is unknown.
182 Min = KnownOne;
183 Max = KnownOne|UnknownBits;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000184
Chris Lattner2188e402010-01-04 07:37:31 +0000185 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000186 Min.setBit(Min.getBitWidth()-1);
187 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000188 }
189}
190
191// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
192// a set of known zero and one bits, compute the maximum and minimum values that
193// could have the specified known zero and known one bits, returning them in
194// min/max.
195static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
196 const APInt &KnownOne,
197 APInt &Min, APInt &Max) {
198 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
199 KnownZero.getBitWidth() == Min.getBitWidth() &&
200 KnownZero.getBitWidth() == Max.getBitWidth() &&
201 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
202 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000203
Chris Lattner2188e402010-01-04 07:37:31 +0000204 // The minimum value is when the unknown bits are all zeros.
205 Min = KnownOne;
206 // The maximum value is when the unknown bits are all ones.
207 Max = KnownOne|UnknownBits;
208}
209
210
211
212/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
213/// cmp pred (load (gep GV, ...)), cmpcst
214/// where GV is a global variable with a constant initializer. Try to simplify
215/// this into some simple computation that does not need the load. For example
216/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
217///
218/// If AndCst is non-null, then the loaded value is masked with that constant
219/// before doing the comparison. This handles cases like "A[i]&4 == 0".
220Instruction *InstCombiner::
221FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
222 CmpInst &ICI, ConstantInt *AndCst) {
Matt Arsenault5aeae182013-08-19 21:40:31 +0000223 // We need TD information to know the pointer size unless this is inbounds.
Craig Topperf40110f2014-04-25 05:29:35 +0000224 if (!GEP->isInBounds() && !DL)
225 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000226
Chris Lattnerfe741762012-01-31 02:55:06 +0000227 Constant *Init = GV->getInitializer();
228 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
Craig Topperf40110f2014-04-25 05:29:35 +0000229 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000230
Chris Lattnerfe741762012-01-31 02:55:06 +0000231 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +0000232 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000233
Chris Lattner2188e402010-01-04 07:37:31 +0000234 // There are many forms of this optimization we can handle, for now, just do
235 // the simple index into a single-dimensional array.
236 //
237 // Require: GEP GV, 0, i {{, constant indices}}
238 if (GEP->getNumOperands() < 3 ||
239 !isa<ConstantInt>(GEP->getOperand(1)) ||
240 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
241 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000242 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000243
244 // Check that indices after the variable are constants and in-range for the
245 // type they index. Collect the indices. This is typically for arrays of
246 // structs.
247 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000248
Chris Lattnerfe741762012-01-31 02:55:06 +0000249 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000250 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
251 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000252 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000253
Chris Lattner2188e402010-01-04 07:37:31 +0000254 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000255 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000256
Chris Lattner229907c2011-07-18 04:54:35 +0000257 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000258 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000259 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000260 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000261 EltTy = ATy->getElementType();
262 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000263 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000264 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000265
Chris Lattner2188e402010-01-04 07:37:31 +0000266 LaterIndices.push_back(IdxVal);
267 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000268
Chris Lattner2188e402010-01-04 07:37:31 +0000269 enum { Overdefined = -3, Undefined = -2 };
270
271 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000272
Chris Lattner2188e402010-01-04 07:37:31 +0000273 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
274 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
275 // and 87 is the second (and last) index. FirstTrueElement is -2 when
276 // undefined, otherwise set to the first true element. SecondTrueElement is
277 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
278 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
279
280 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
281 // form "i != 47 & i != 87". Same state transitions as for true elements.
282 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000283
Chris Lattner2188e402010-01-04 07:37:31 +0000284 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
285 /// define a state machine that triggers for ranges of values that the index
286 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
287 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
288 /// index in the range (inclusive). We use -2 for undefined here because we
289 /// use relative comparisons and don't want 0-1 to match -1.
290 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000291
Chris Lattner2188e402010-01-04 07:37:31 +0000292 // MagicBitvector - This is a magic bitvector where we set a bit if the
293 // comparison is true for element 'i'. If there are 64 elements or less in
294 // the array, this will fully represent all the comparison results.
295 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000296
297
Chris Lattner2188e402010-01-04 07:37:31 +0000298 // Scan the array and see if one of our patterns matches.
299 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000300 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
301 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000302 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000303
Chris Lattner2188e402010-01-04 07:37:31 +0000304 // If this is indexing an array of structures, get the structure element.
305 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000306 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000307
Chris Lattner2188e402010-01-04 07:37:31 +0000308 // If the element is masked, handle it.
309 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000310
Chris Lattner2188e402010-01-04 07:37:31 +0000311 // Find out if the comparison would be true or false for the i'th element.
312 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000313 CompareRHS, DL, TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000314 // If the result is undef for this element, ignore it.
315 if (isa<UndefValue>(C)) {
316 // Extend range state machines to cover this element in case there is an
317 // undef in the middle of the range.
318 if (TrueRangeEnd == (int)i-1)
319 TrueRangeEnd = i;
320 if (FalseRangeEnd == (int)i-1)
321 FalseRangeEnd = i;
322 continue;
323 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000324
Chris Lattner2188e402010-01-04 07:37:31 +0000325 // If we can't compute the result for any of the elements, we have to give
326 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000327 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000328
Chris Lattner2188e402010-01-04 07:37:31 +0000329 // Otherwise, we know if the comparison is true or false for this element,
330 // update our state machines.
331 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000332
Chris Lattner2188e402010-01-04 07:37:31 +0000333 // State machine for single/double/range index comparison.
334 if (IsTrueForElt) {
335 // Update the TrueElement state machine.
336 if (FirstTrueElement == Undefined)
337 FirstTrueElement = TrueRangeEnd = i; // First true element.
338 else {
339 // Update double-compare state machine.
340 if (SecondTrueElement == Undefined)
341 SecondTrueElement = i;
342 else
343 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000344
Chris Lattner2188e402010-01-04 07:37:31 +0000345 // Update range state machine.
346 if (TrueRangeEnd == (int)i-1)
347 TrueRangeEnd = i;
348 else
349 TrueRangeEnd = Overdefined;
350 }
351 } else {
352 // Update the FalseElement state machine.
353 if (FirstFalseElement == Undefined)
354 FirstFalseElement = FalseRangeEnd = i; // First false element.
355 else {
356 // Update double-compare state machine.
357 if (SecondFalseElement == Undefined)
358 SecondFalseElement = i;
359 else
360 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000361
Chris Lattner2188e402010-01-04 07:37:31 +0000362 // Update range state machine.
363 if (FalseRangeEnd == (int)i-1)
364 FalseRangeEnd = i;
365 else
366 FalseRangeEnd = Overdefined;
367 }
368 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000369
370
Chris Lattner2188e402010-01-04 07:37:31 +0000371 // If this element is in range, update our magic bitvector.
372 if (i < 64 && IsTrueForElt)
373 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000374
Chris Lattner2188e402010-01-04 07:37:31 +0000375 // If all of our states become overdefined, bail out early. Since the
376 // predicate is expensive, only check it every 8 elements. This is only
377 // really useful for really huge arrays.
378 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
379 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
380 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000381 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000382 }
383
384 // Now that we've scanned the entire array, emit our new comparison(s). We
385 // order the state machines in complexity of the generated code.
386 Value *Idx = GEP->getOperand(2);
387
Matt Arsenault5aeae182013-08-19 21:40:31 +0000388 // If the index is larger than the pointer size of the target, truncate the
389 // index down like the GEP would do implicitly. We don't have to do this for
390 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000391 if (!GEP->isInBounds()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000392 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000393 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
394 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
395 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
396 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000397
Chris Lattner2188e402010-01-04 07:37:31 +0000398 // If the comparison is only true for one or two elements, emit direct
399 // comparisons.
400 if (SecondTrueElement != Overdefined) {
401 // None true -> false.
402 if (FirstTrueElement == Undefined)
Jakub Staszakbddea112013-06-06 20:18:46 +0000403 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000404
Chris Lattner2188e402010-01-04 07:37:31 +0000405 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000406
Chris Lattner2188e402010-01-04 07:37:31 +0000407 // True for one element -> 'i == 47'.
408 if (SecondTrueElement == Undefined)
409 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000410
Chris Lattner2188e402010-01-04 07:37:31 +0000411 // True for two elements -> 'i == 47 | i == 72'.
412 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
413 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
414 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
415 return BinaryOperator::CreateOr(C1, C2);
416 }
417
418 // If the comparison is only false for one or two elements, emit direct
419 // comparisons.
420 if (SecondFalseElement != Overdefined) {
421 // None false -> true.
422 if (FirstFalseElement == Undefined)
Jakub Staszakbddea112013-06-06 20:18:46 +0000423 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000424
Chris Lattner2188e402010-01-04 07:37:31 +0000425 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
426
427 // False for one element -> 'i != 47'.
428 if (SecondFalseElement == Undefined)
429 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000430
Chris Lattner2188e402010-01-04 07:37:31 +0000431 // False for two elements -> 'i != 47 & i != 72'.
432 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
433 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
434 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
435 return BinaryOperator::CreateAnd(C1, C2);
436 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000437
Chris Lattner2188e402010-01-04 07:37:31 +0000438 // If the comparison can be replaced with a range comparison for the elements
439 // where it is true, emit the range check.
440 if (TrueRangeEnd != Overdefined) {
441 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000442
Chris Lattner2188e402010-01-04 07:37:31 +0000443 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
444 if (FirstTrueElement) {
445 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
446 Idx = Builder->CreateAdd(Idx, Offs);
447 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000448
Chris Lattner2188e402010-01-04 07:37:31 +0000449 Value *End = ConstantInt::get(Idx->getType(),
450 TrueRangeEnd-FirstTrueElement+1);
451 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
452 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000453
Chris Lattner2188e402010-01-04 07:37:31 +0000454 // False range check.
455 if (FalseRangeEnd != Overdefined) {
456 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
457 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
458 if (FirstFalseElement) {
459 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
460 Idx = Builder->CreateAdd(Idx, Offs);
461 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000462
Chris Lattner2188e402010-01-04 07:37:31 +0000463 Value *End = ConstantInt::get(Idx->getType(),
464 FalseRangeEnd-FirstFalseElement);
465 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
466 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000467
468
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();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000481 else if (DL)
482 Ty = DL->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000483 else if (ArrayElementCount <= 32)
Chris Lattner2188e402010-01-04 07:37:31 +0000484 Ty = Type::getInt32Ty(Init->getContext());
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000485
Craig Topperf40110f2014-04-25 05:29:35 +0000486 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000487 Value *V = Builder->CreateIntCast(Idx, Ty, false);
488 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
489 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
490 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
491 }
Chris Lattner2188e402010-01-04 07:37:31 +0000492 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000493
Craig Topperf40110f2014-04-25 05:29:35 +0000494 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000495}
496
497
498/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
499/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
500/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
501/// be complex, and scales are involved. The above expression would also be
502/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
503/// This later form is less amenable to optimization though, and we are allowed
504/// to generate the first by knowing that pointer arithmetic doesn't overflow.
505///
506/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000507///
Eli Friedman1754a252011-05-18 23:11:30 +0000508static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000509 const DataLayout &DL = *IC.getDataLayout();
Chris Lattner2188e402010-01-04 07:37:31 +0000510 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000511
Chris Lattner2188e402010-01-04 07:37:31 +0000512 // Check to see if this gep only has a single variable index. If so, and if
513 // any constant indices are a multiple of its scale, then we can compute this
514 // in terms of the scale of the variable index. For example, if the GEP
515 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
516 // because the expression will cross zero at the same point.
517 unsigned i, e = GEP->getNumOperands();
518 int64_t Offset = 0;
519 for (i = 1; i != e; ++i, ++GTI) {
520 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
521 // Compute the aggregate offset of constant indices.
522 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000523
Chris Lattner2188e402010-01-04 07:37:31 +0000524 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000525 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000526 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000527 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000528 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000529 Offset += Size*CI->getSExtValue();
530 }
531 } else {
532 // Found our variable index.
533 break;
534 }
535 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000536
Chris Lattner2188e402010-01-04 07:37:31 +0000537 // If there are no variable indices, we must have a constant offset, just
538 // evaluate it the general way.
Craig Topperf40110f2014-04-25 05:29:35 +0000539 if (i == e) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000540
Chris Lattner2188e402010-01-04 07:37:31 +0000541 Value *VariableIdx = GEP->getOperand(i);
542 // Determine the scale factor of the variable element. For example, this is
543 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000544 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000545
Chris Lattner2188e402010-01-04 07:37:31 +0000546 // Verify that there are no other variable indices. If so, emit the hard way.
547 for (++i, ++GTI; i != e; ++i, ++GTI) {
548 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000549 if (!CI) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000550
Chris Lattner2188e402010-01-04 07:37:31 +0000551 // Compute the aggregate offset of constant indices.
552 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000553
Chris Lattner2188e402010-01-04 07:37:31 +0000554 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000555 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000556 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000557 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000558 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000559 Offset += Size*CI->getSExtValue();
560 }
561 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000562
Matt Arsenault745101d2013-08-21 19:53:10 +0000563
564
Chris Lattner2188e402010-01-04 07:37:31 +0000565 // Okay, we know we have a single variable index, which must be a
566 // pointer/array/vector index. If there is no offset, life is simple, return
567 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000568 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000569 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000570 if (Offset == 0) {
571 // Cast to intptrty in case a truncation occurs. If an extension is needed,
572 // we don't need to bother extending: the extension won't affect where the
573 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000574 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000575 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
576 }
Chris Lattner2188e402010-01-04 07:37:31 +0000577 return VariableIdx;
578 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000579
Chris Lattner2188e402010-01-04 07:37:31 +0000580 // Otherwise, there is an index. The computation we will do will be modulo
581 // the pointer size, so get it.
582 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000583
Chris Lattner2188e402010-01-04 07:37:31 +0000584 Offset &= PtrSizeMask;
585 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000586
Chris Lattner2188e402010-01-04 07:37:31 +0000587 // To do this transformation, any constant index must be a multiple of the
588 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
589 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
590 // multiple of the variable scale.
591 int64_t NewOffs = Offset / (int64_t)VariableScale;
592 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000593 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000594
Chris Lattner2188e402010-01-04 07:37:31 +0000595 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000596 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000597 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
598 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000599 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000600 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000601}
602
603/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
604/// else. At this point we know that the GEP is on the LHS of the comparison.
605Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
606 ICmpInst::Predicate Cond,
607 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000608 // Don't transform signed compares of GEPs into index compares. Even if the
609 // GEP is inbounds, the final add of the base pointer can have signed overflow
610 // and would change the result of the icmp.
611 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000612 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000613 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000614 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000615
Matt Arsenault44f60d02014-06-09 19:20:29 +0000616 // Look through bitcasts and addrspacecasts. We do not however want to remove
617 // 0 GEPs.
618 if (!isa<GetElementPtrInst>(RHS))
619 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000620
621 Value *PtrBase = GEPLHS->getOperand(0);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000622 if (DL && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000623 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
624 // This transformation (ignoring the base and scales) is valid because we
625 // know pointers can't overflow since the gep is inbounds. See if we can
626 // output an optimized form.
Eli Friedman1754a252011-05-18 23:11:30 +0000627 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000628
Chris Lattner2188e402010-01-04 07:37:31 +0000629 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000630 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000631 Offset = EmitGEPOffset(GEPLHS);
632 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
633 Constant::getNullValue(Offset->getType()));
634 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
635 // If the base pointers are different, but the indices are the same, just
636 // compare the base pointer.
637 if (PtrBase != GEPRHS->getOperand(0)) {
638 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
639 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
640 GEPRHS->getOperand(0)->getType();
641 if (IndicesTheSame)
642 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
643 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
644 IndicesTheSame = false;
645 break;
646 }
647
648 // If all indices are the same, just compare the base pointers.
649 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000650 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000651
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000652 // If we're comparing GEPs with two base pointers that only differ in type
653 // and both GEPs have only constant indices or just one use, then fold
654 // the compare with the adjusted indices.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000655 if (DL && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000656 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
657 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
658 PtrBase->stripPointerCasts() ==
659 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000660 Value *LOffset = EmitGEPOffset(GEPLHS);
661 Value *ROffset = EmitGEPOffset(GEPRHS);
662
663 // If we looked through an addrspacecast between different sized address
664 // spaces, the LHS and RHS pointers are different sized
665 // integers. Truncate to the smaller one.
666 Type *LHSIndexTy = LOffset->getType();
667 Type *RHSIndexTy = ROffset->getType();
668 if (LHSIndexTy != RHSIndexTy) {
669 if (LHSIndexTy->getPrimitiveSizeInBits() <
670 RHSIndexTy->getPrimitiveSizeInBits()) {
671 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
672 } else
673 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
674 }
675
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000676 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000677 LOffset, ROffset);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000678 return ReplaceInstUsesWith(I, Cmp);
679 }
680
Chris Lattner2188e402010-01-04 07:37:31 +0000681 // Otherwise, the base pointers are different and the indices are
682 // different, bail out.
Craig Topperf40110f2014-04-25 05:29:35 +0000683 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000684 }
685
686 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +0000687 if (GEPLHS->hasAllZeroIndices())
Chris Lattner2188e402010-01-04 07:37:31 +0000688 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +0000689 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +0000690
691 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +0000692 if (GEPRHS->hasAllZeroIndices())
Chris Lattner2188e402010-01-04 07:37:31 +0000693 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
694
Stuart Hastings66a82b92011-05-14 05:55:10 +0000695 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +0000696 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
697 // If the GEPs only differ by one index, compare it.
698 unsigned NumDifferences = 0; // Keep track of # differences.
699 unsigned DiffOperand = 0; // The operand that differs.
700 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
701 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
702 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
703 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
704 // Irreconcilable differences.
705 NumDifferences = 2;
706 break;
707 } else {
708 if (NumDifferences++) break;
709 DiffOperand = i;
710 }
711 }
712
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +0000713 if (NumDifferences == 0) // SAME GEP?
714 return ReplaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +0000715 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +0000716
Stuart Hastings66a82b92011-05-14 05:55:10 +0000717 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +0000718 Value *LHSV = GEPLHS->getOperand(DiffOperand);
719 Value *RHSV = GEPRHS->getOperand(DiffOperand);
720 // Make sure we do a signed comparison here.
721 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
722 }
723 }
724
725 // Only lower this if the icmp is the only user of the GEP or if we expect
726 // the result to fold to a constant!
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000727 if (DL &&
Stuart Hastings66a82b92011-05-14 05:55:10 +0000728 GEPsInBounds &&
Chris Lattner2188e402010-01-04 07:37:31 +0000729 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
730 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
731 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
732 Value *L = EmitGEPOffset(GEPLHS);
733 Value *R = EmitGEPOffset(GEPRHS);
734 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
735 }
736 }
Craig Topperf40110f2014-04-25 05:29:35 +0000737 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000738}
739
740/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
Benjamin Kramer0e2d1622013-09-20 22:12:42 +0000741Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
Chris Lattner2188e402010-01-04 07:37:31 +0000742 Value *X, ConstantInt *CI,
Benjamin Kramer0e2d1622013-09-20 22:12:42 +0000743 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +0000744 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000745 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +0000746 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000747
Chris Lattner8c92b572010-01-08 17:48:19 +0000748 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +0000749 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
750 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
751 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +0000752 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +0000753 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +0000754 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
755 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000756
Chris Lattner2188e402010-01-04 07:37:31 +0000757 // (X+1) >u X --> X <u (0-1) --> X != 255
758 // (X+2) >u X --> X <u (0-2) --> X <u 254
759 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +0000760 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +0000761 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000762
Chris Lattner2188e402010-01-04 07:37:31 +0000763 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
764 ConstantInt *SMax = ConstantInt::get(X->getContext(),
765 APInt::getSignedMaxValue(BitWidth));
766
767 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
768 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
769 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
770 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
771 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
772 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +0000773 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +0000774 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000775
Chris Lattner2188e402010-01-04 07:37:31 +0000776 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
777 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
778 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
779 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
780 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
781 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +0000782
Chris Lattner2188e402010-01-04 07:37:31 +0000783 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +0000784 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000785 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
786}
787
788/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
789/// and CmpRHS are both known to be integer constants.
790Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
791 ConstantInt *DivRHS) {
792 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
793 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000794
795 // FIXME: If the operand types don't match the type of the divide
Chris Lattner2188e402010-01-04 07:37:31 +0000796 // then don't attempt this transform. The code below doesn't have the
797 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach129c52a2011-09-30 18:09:53 +0000798 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner2188e402010-01-04 07:37:31 +0000799 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach129c52a2011-09-30 18:09:53 +0000800 // (x /u C1) <u C2. Simply casting the operands and result won't
801 // work. :( The if statement below tests that condition and bails
Chris Lattner98457102011-02-10 05:23:05 +0000802 // if it finds it.
Chris Lattner2188e402010-01-04 07:37:31 +0000803 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
804 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Craig Topperf40110f2014-04-25 05:29:35 +0000805 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000806 if (DivRHS->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000807 return nullptr; // The ProdOV computation fails on divide by zero.
Chris Lattner2188e402010-01-04 07:37:31 +0000808 if (DivIsSigned && DivRHS->isAllOnesValue())
Craig Topperf40110f2014-04-25 05:29:35 +0000809 return nullptr; // The overflow computation also screws up here
Chris Lattner43273af2011-02-13 08:07:21 +0000810 if (DivRHS->isOne()) {
811 // This eliminates some funny cases with INT_MIN.
812 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
813 return &ICI;
814 }
Chris Lattner2188e402010-01-04 07:37:31 +0000815
816 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach129c52a2011-09-30 18:09:53 +0000817 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
818 // C2 (CI). By solving for X we can turn this into a range check
819 // instead of computing a divide.
Chris Lattner2188e402010-01-04 07:37:31 +0000820 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
821
822 // Determine if the product overflows by seeing if the product is
823 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach129c52a2011-09-30 18:09:53 +0000824 // as in the LHS instruction that we're folding.
Chris Lattner2188e402010-01-04 07:37:31 +0000825 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
826 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
827
828 // Get the ICmp opcode
829 ICmpInst::Predicate Pred = ICI.getPredicate();
830
Chris Lattner98457102011-02-10 05:23:05 +0000831 /// If the division is known to be exact, then there is no remainder from the
832 /// divide, so the covered range size is unit, otherwise it is the divisor.
833 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000834
Chris Lattner2188e402010-01-04 07:37:31 +0000835 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach129c52a2011-09-30 18:09:53 +0000836 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner2188e402010-01-04 07:37:31 +0000837 // Compute this interval based on the constants involved and the signedness of
838 // the compare/divide. This computes a half-open interval, keeping track of
839 // whether either value in the interval overflows. After analysis each
840 // overflow variable is set to 0 if it's corresponding bound variable is valid
841 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
842 int LoOverflow = 0, HiOverflow = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000843 Constant *LoBound = nullptr, *HiBound = nullptr;
Chris Lattner98457102011-02-10 05:23:05 +0000844
Chris Lattner2188e402010-01-04 07:37:31 +0000845 if (!DivIsSigned) { // udiv
846 // e.g. X/5 op 3 --> [15, 20)
847 LoBound = Prod;
848 HiOverflow = LoOverflow = ProdOV;
Chris Lattner98457102011-02-10 05:23:05 +0000849 if (!HiOverflow) {
850 // If this is not an exact divide, then many values in the range collapse
851 // to the same result value.
852 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
853 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000854
Chris Lattner2188e402010-01-04 07:37:31 +0000855 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
856 if (CmpRHSV == 0) { // (X / pos) op 0
857 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner98457102011-02-10 05:23:05 +0000858 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
859 HiBound = RangeSize;
Chris Lattner2188e402010-01-04 07:37:31 +0000860 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
861 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
862 HiOverflow = LoOverflow = ProdOV;
863 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000864 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +0000865 } else { // (X / pos) op neg
866 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
867 HiBound = AddOne(Prod);
868 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
869 if (!LoOverflow) {
Chris Lattner98457102011-02-10 05:23:05 +0000870 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000871 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattner98457102011-02-10 05:23:05 +0000872 }
Chris Lattner2188e402010-01-04 07:37:31 +0000873 }
Chris Lattnerb1a15122011-07-15 06:08:15 +0000874 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattner98457102011-02-10 05:23:05 +0000875 if (DivI->isExact())
876 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000877 if (CmpRHSV == 0) { // (X / neg) op 0
878 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner98457102011-02-10 05:23:05 +0000879 LoBound = AddOne(RangeSize);
880 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000881 if (HiBound == DivRHS) { // -INTMIN = INTMIN
882 HiOverflow = 1; // [INTMIN+1, overflow)
Craig Topperf40110f2014-04-25 05:29:35 +0000883 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
Chris Lattner2188e402010-01-04 07:37:31 +0000884 }
885 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
886 // e.g. X/-5 op 3 --> [-19, -14)
887 HiBound = AddOne(Prod);
888 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
889 if (!LoOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000890 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner2188e402010-01-04 07:37:31 +0000891 } else { // (X / neg) op neg
892 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
893 LoOverflow = HiOverflow = ProdOV;
894 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000895 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +0000896 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000897
Chris Lattner2188e402010-01-04 07:37:31 +0000898 // Dividing by a negative swaps the condition. LT <-> GT
899 Pred = ICmpInst::getSwappedPredicate(Pred);
900 }
901
902 Value *X = DivI->getOperand(0);
903 switch (Pred) {
904 default: llvm_unreachable("Unhandled icmp opcode!");
905 case ICmpInst::ICMP_EQ:
906 if (LoOverflow && HiOverflow)
Jakub Staszakbddea112013-06-06 20:18:46 +0000907 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner067459c2010-03-05 08:46:26 +0000908 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000909 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
910 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000911 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000912 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
913 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +0000914 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
915 DivIsSigned, true));
Chris Lattner2188e402010-01-04 07:37:31 +0000916 case ICmpInst::ICMP_NE:
917 if (LoOverflow && HiOverflow)
Jakub Staszakbddea112013-06-06 20:18:46 +0000918 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner067459c2010-03-05 08:46:26 +0000919 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000920 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
921 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000922 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000923 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
924 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000925 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
926 DivIsSigned, false));
Chris Lattner2188e402010-01-04 07:37:31 +0000927 case ICmpInst::ICMP_ULT:
928 case ICmpInst::ICMP_SLT:
929 if (LoOverflow == +1) // Low bound is greater than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000930 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +0000931 if (LoOverflow == -1) // Low bound is less than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000932 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +0000933 return new ICmpInst(Pred, X, LoBound);
934 case ICmpInst::ICMP_UGT:
935 case ICmpInst::ICMP_SGT:
936 if (HiOverflow == +1) // High bound greater than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000937 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner98457102011-02-10 05:23:05 +0000938 if (HiOverflow == -1) // High bound less than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000939 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +0000940 if (Pred == ICmpInst::ICMP_UGT)
941 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +0000942 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner2188e402010-01-04 07:37:31 +0000943 }
944}
945
Chris Lattnerd369f572011-02-13 07:43:07 +0000946/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
947Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
948 ConstantInt *ShAmt) {
Chris Lattnerd369f572011-02-13 07:43:07 +0000949 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000950
Chris Lattnerd369f572011-02-13 07:43:07 +0000951 // Check that the shift amount is in range. If not, don't perform
952 // undefined shifts. When the shift is visited it will be
953 // simplified.
954 uint32_t TypeBits = CmpRHSV.getBitWidth();
955 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner43273af2011-02-13 08:07:21 +0000956 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000957 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000958
Chris Lattner43273af2011-02-13 08:07:21 +0000959 if (!ICI.isEquality()) {
960 // If we have an unsigned comparison and an ashr, we can't simplify this.
961 // Similarly for signed comparisons with lshr.
962 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
Craig Topperf40110f2014-04-25 05:29:35 +0000963 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000964
Eli Friedman865866e2011-05-25 23:26:20 +0000965 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
966 // by a power of 2. Since we already have logic to simplify these,
967 // transform to div and then simplify the resultant comparison.
Chris Lattner43273af2011-02-13 08:07:21 +0000968 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedman865866e2011-05-25 23:26:20 +0000969 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Craig Topperf40110f2014-04-25 05:29:35 +0000970 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000971
Chris Lattner43273af2011-02-13 08:07:21 +0000972 // Revisit the shift (to delete it).
973 Worklist.Add(Shr);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000974
Chris Lattner43273af2011-02-13 08:07:21 +0000975 Constant *DivCst =
976 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000977
Chris Lattner43273af2011-02-13 08:07:21 +0000978 Value *Tmp =
979 Shr->getOpcode() == Instruction::AShr ?
980 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
981 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000982
Chris Lattner43273af2011-02-13 08:07:21 +0000983 ICI.setOperand(0, Tmp);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000984
Chris Lattner43273af2011-02-13 08:07:21 +0000985 // If the builder folded the binop, just return it.
986 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
Craig Topperf40110f2014-04-25 05:29:35 +0000987 if (!TheDiv)
Chris Lattner43273af2011-02-13 08:07:21 +0000988 return &ICI;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000989
Chris Lattner43273af2011-02-13 08:07:21 +0000990 // Otherwise, fold this div/compare.
991 assert(TheDiv->getOpcode() == Instruction::SDiv ||
992 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000993
Chris Lattner43273af2011-02-13 08:07:21 +0000994 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
995 assert(Res && "This div/cst should have folded!");
996 return Res;
997 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000998
999
Chris Lattnerd369f572011-02-13 07:43:07 +00001000 // If we are comparing against bits always shifted out, the
1001 // comparison cannot succeed.
1002 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszakbddea112013-06-06 20:18:46 +00001003 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattnerd369f572011-02-13 07:43:07 +00001004 if (Shr->getOpcode() == Instruction::LShr)
1005 Comp = Comp.lshr(ShAmtVal);
1006 else
1007 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001008
Chris Lattnerd369f572011-02-13 07:43:07 +00001009 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1010 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001011 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattnerd369f572011-02-13 07:43:07 +00001012 return ReplaceInstUsesWith(ICI, Cst);
1013 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001014
Chris Lattnerd369f572011-02-13 07:43:07 +00001015 // Otherwise, check to see if the bits shifted out are known to be zero.
1016 // If so, we can compare against the unshifted value:
1017 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattner9bd7fdf2011-02-13 18:30:09 +00001018 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattnerd369f572011-02-13 07:43:07 +00001019 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001020
Chris Lattnerd369f572011-02-13 07:43:07 +00001021 if (Shr->hasOneUse()) {
1022 // Otherwise strength reduce the shift into an and.
1023 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszakbddea112013-06-06 20:18:46 +00001024 Constant *Mask = Builder->getInt(Val);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001025
Chris Lattnerd369f572011-02-13 07:43:07 +00001026 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1027 Mask, Shr->getName()+".mask");
1028 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1029 }
Craig Topperf40110f2014-04-25 05:29:35 +00001030 return nullptr;
Chris Lattnerd369f572011-02-13 07:43:07 +00001031}
1032
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001033/// FoldICmpCstShrCst - Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
1034/// (icmp eq/ne A, Log2(const2/const1)) ->
1035/// (icmp eq/ne A, Log2(const2) - Log2(const1)).
1036Instruction *InstCombiner::FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
1037 ConstantInt *CI1,
1038 ConstantInt *CI2) {
1039 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1040
1041 auto getConstant = [&I, this](bool IsTrue) {
1042 if (I.getPredicate() == I.ICMP_NE)
1043 IsTrue = !IsTrue;
1044 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
1045 };
1046
1047 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1048 if (I.getPredicate() == I.ICMP_NE)
1049 Pred = CmpInst::getInversePredicate(Pred);
1050 return new ICmpInst(Pred, LHS, RHS);
1051 };
1052
1053 APInt AP1 = CI1->getValue();
1054 APInt AP2 = CI2->getValue();
1055
1056 if (!AP1) {
1057 if (!AP2) {
1058 // Both Constants are 0.
1059 return getConstant(true);
1060 }
1061
1062 if (cast<BinaryOperator>(Op)->isExact())
1063 return getConstant(false);
1064
1065 if (AP2.isNegative()) {
1066 // MSB is set, so a lshr with a large enough 'A' would be undefined.
1067 return getConstant(false);
1068 }
1069
1070 // 'A' must be large enough to shift out the highest set bit.
1071 return getICmp(I.ICMP_UGT, A,
1072 ConstantInt::get(A->getType(), AP2.logBase2()));
1073 }
1074
1075 if (!AP2) {
1076 // Shifting 0 by any value gives 0.
1077 return getConstant(false);
1078 }
1079
1080 bool IsAShr = isa<AShrOperator>(Op);
1081 if (AP1 == AP2) {
1082 if (AP1.isAllOnesValue() && IsAShr) {
1083 // Arithmatic shift of -1 is always -1.
1084 return getConstant(true);
1085 }
1086 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1087 }
1088
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001089 bool IsNegative = false;
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001090 if (IsAShr) {
1091 if (AP1.isNegative() != AP2.isNegative()) {
1092 // Arithmetic shift will never change the sign.
1093 return getConstant(false);
1094 }
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001095 // Both the constants are negative, take their positive to calculate log.
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001096 if (AP1.isNegative()) {
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001097 if (AP1.slt(AP2))
1098 // Right-shifting won't increase the magnitude.
1099 return getConstant(false);
1100 IsNegative = true;
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001101 }
1102 }
1103
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001104 if (!IsNegative && AP1.ugt(AP2))
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001105 // Right-shifting will not increase the value.
1106 return getConstant(false);
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001107
1108 // Get the distance between the highest bit that's set.
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001109 int Shift;
1110 if (IsNegative)
1111 Shift = (-AP2).logBase2() - (-AP1).logBase2();
1112 else
1113 Shift = AP2.logBase2() - AP1.logBase2();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001114
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001115 if (IsAShr ? AP1 == AP2.ashr(Shift) : AP1 == AP2.lshr(Shift))
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001116 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1117
1118 // Shifting const2 will never be equal to const1.
1119 return getConstant(false);
1120}
Chris Lattner2188e402010-01-04 07:37:31 +00001121
1122/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1123///
1124Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1125 Instruction *LHSI,
1126 ConstantInt *RHS) {
1127 const APInt &RHSV = RHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001128
Chris Lattner2188e402010-01-04 07:37:31 +00001129 switch (LHSI->getOpcode()) {
1130 case Instruction::Trunc:
1131 if (ICI.isEquality() && LHSI->hasOneUse()) {
1132 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1133 // of the high bits truncated out of x are known.
1134 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1135 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner2188e402010-01-04 07:37:31 +00001136 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001137 computeKnownBits(LHSI->getOperand(0), KnownZero, KnownOne, 0, &ICI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001138
Chris Lattner2188e402010-01-04 07:37:31 +00001139 // If all the high bits are known, we can do this xform.
1140 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1141 // Pull in the high bits from known-ones set.
Jay Foad583abbc2010-12-07 08:25:19 +00001142 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedmane0a64d82012-05-11 01:32:59 +00001143 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner2188e402010-01-04 07:37:31 +00001144 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001145 Builder->getInt(NewRHS));
Chris Lattner2188e402010-01-04 07:37:31 +00001146 }
1147 }
1148 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001149
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001150 case Instruction::Xor: // (icmp pred (xor X, XorCst), CI)
1151 if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001152 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1153 // fold the xor.
1154 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1155 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1156 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001157
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001158 // If the sign bit of the XorCst is not set, there is no change to
Chris Lattner2188e402010-01-04 07:37:31 +00001159 // the operation, just stop using the Xor.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001160 if (!XorCst->isNegative()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001161 ICI.setOperand(0, CompareVal);
1162 Worklist.Add(LHSI);
1163 return &ICI;
1164 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001165
Chris Lattner2188e402010-01-04 07:37:31 +00001166 // Was the old condition true if the operand is positive?
1167 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001168
Chris Lattner2188e402010-01-04 07:37:31 +00001169 // If so, the new one isn't.
1170 isTrueIfPositive ^= true;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001171
Chris Lattner2188e402010-01-04 07:37:31 +00001172 if (isTrueIfPositive)
1173 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1174 SubOne(RHS));
1175 else
1176 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1177 AddOne(RHS));
1178 }
1179
1180 if (LHSI->hasOneUse()) {
1181 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001182 if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1183 const APInt &SignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001184 ICmpInst::Predicate Pred = ICI.isSigned()
1185 ? ICI.getUnsignedPredicate()
1186 : ICI.getSignedPredicate();
1187 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001188 Builder->getInt(RHSV ^ SignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001189 }
1190
1191 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001192 if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1193 const APInt &NotSignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001194 ICmpInst::Predicate Pred = ICI.isSigned()
1195 ? ICI.getUnsignedPredicate()
1196 : ICI.getSignedPredicate();
1197 Pred = ICI.getSwappedPredicate(Pred);
1198 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001199 Builder->getInt(RHSV ^ NotSignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001200 }
1201 }
David Majnemer72d76272013-07-09 09:20:58 +00001202
1203 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1204 // iff -C is a power of 2
1205 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001206 XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1207 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
David Majnemer72d76272013-07-09 09:20:58 +00001208
1209 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1210 // iff -C is a power of 2
1211 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001212 XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1213 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001214 }
1215 break;
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001216 case Instruction::And: // (icmp pred (and X, AndCst), RHS)
Chris Lattner2188e402010-01-04 07:37:31 +00001217 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1218 LHSI->getOperand(0)->hasOneUse()) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001219 ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001220
Chris Lattner2188e402010-01-04 07:37:31 +00001221 // If the LHS is an AND of a truncating cast, we can widen the
1222 // and/compare to be the input width without changing the value
1223 // produced, eliminating a cast.
1224 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1225 // We can do this transformation if either the AND constant does not
Jim Grosbach129c52a2011-09-30 18:09:53 +00001226 // have its sign bit set or if it is an equality comparison.
Chris Lattner2188e402010-01-04 07:37:31 +00001227 // Extending a relational comparison when we're checking the sign
1228 // bit would not work.
Benjamin Kramer35159c12011-06-12 22:47:53 +00001229 if (ICI.isEquality() ||
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001230 (!AndCst->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer35159c12011-06-12 22:47:53 +00001231 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001232 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001233 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
Benjamin Kramer35159c12011-06-12 22:47:53 +00001234 NewAnd->takeName(LHSI);
Chris Lattner2188e402010-01-04 07:37:31 +00001235 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer35159c12011-06-12 22:47:53 +00001236 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner2188e402010-01-04 07:37:31 +00001237 }
1238 }
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001239
1240 // If the LHS is an AND of a zext, and we have an equality compare, we can
1241 // shrink the and/compare to the smaller type, eliminating the cast.
1242 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattner229907c2011-07-18 04:54:35 +00001243 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001244 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1245 // should fold the icmp to true/false in that case.
1246 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1247 Value *NewAnd =
1248 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001249 ConstantExpr::getTrunc(AndCst, Ty));
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001250 NewAnd->takeName(LHSI);
1251 return new ICmpInst(ICI.getPredicate(), NewAnd,
1252 ConstantExpr::getTrunc(RHS, Ty));
1253 }
1254 }
1255
Chris Lattner2188e402010-01-04 07:37:31 +00001256 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1257 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1258 // happens a LOT in code produced by the C front-end, for bitfield
1259 // access.
1260 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1261 if (Shift && !Shift->isShift())
Craig Topperf40110f2014-04-25 05:29:35 +00001262 Shift = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001263
Chris Lattner2188e402010-01-04 07:37:31 +00001264 ConstantInt *ShAmt;
Craig Topperf40110f2014-04-25 05:29:35 +00001265 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001266
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001267 // This seemingly simple opportunity to fold away a shift turns out to
1268 // be rather complicated. See PR17827
1269 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
Chris Lattner2188e402010-01-04 07:37:31 +00001270 if (ShAmt) {
Kay Tiong Khoo5389f742013-12-02 18:43:59 +00001271 bool CanFold = false;
1272 unsigned ShiftOpcode = Shift->getOpcode();
1273 if (ShiftOpcode == Instruction::AShr) {
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001274 // There may be some constraints that make this possible,
1275 // but nothing simple has been discovered yet.
1276 CanFold = false;
1277 } else if (ShiftOpcode == Instruction::Shl) {
1278 // For a left shift, we can fold if the comparison is not signed.
1279 // We can also fold a signed comparison if the mask value and
1280 // comparison value are not negative. These constraints may not be
1281 // obvious, but we can prove that they are correct using an SMT
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001282 // solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001283 if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
Chris Lattner2188e402010-01-04 07:37:31 +00001284 CanFold = true;
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001285 } else if (ShiftOpcode == Instruction::LShr) {
1286 // For a logical right shift, we can fold if the comparison is not
1287 // signed. We can also fold a signed comparison if the shifted mask
1288 // value and the shifted comparison value are not negative.
1289 // These constraints may not be obvious, but we can prove that they
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001290 // are correct using an SMT solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001291 if (!ICI.isSigned())
1292 CanFold = true;
1293 else {
1294 ConstantInt *ShiftedAndCst =
1295 cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1296 ConstantInt *ShiftedRHSCst =
1297 cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1298
1299 if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1300 CanFold = true;
1301 }
Chris Lattner2188e402010-01-04 07:37:31 +00001302 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001303
Chris Lattner2188e402010-01-04 07:37:31 +00001304 if (CanFold) {
1305 Constant *NewCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001306 if (ShiftOpcode == Instruction::Shl)
Chris Lattner2188e402010-01-04 07:37:31 +00001307 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1308 else
1309 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001310
Chris Lattner2188e402010-01-04 07:37:31 +00001311 // Check to see if we are shifting out any of the bits being
1312 // compared.
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001313 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001314 // If we shifted bits out, the fold is not going to work out.
1315 // As a special case, check to see if this means that the
1316 // result is always true or false now.
1317 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Jakub Staszakbddea112013-06-06 20:18:46 +00001318 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001319 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Jakub Staszakbddea112013-06-06 20:18:46 +00001320 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001321 } else {
1322 ICI.setOperand(1, NewCst);
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001323 Constant *NewAndCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001324 if (ShiftOpcode == Instruction::Shl)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001325 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
Chris Lattner2188e402010-01-04 07:37:31 +00001326 else
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001327 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1328 LHSI->setOperand(1, NewAndCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001329 LHSI->setOperand(0, Shift->getOperand(0));
1330 Worklist.Add(Shift); // Shift is dead.
1331 return &ICI;
1332 }
1333 }
1334 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001335
Chris Lattner2188e402010-01-04 07:37:31 +00001336 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1337 // preferable because it allows the C<<Y expression to be hoisted out
1338 // of a loop if Y is invariant and X is not.
1339 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1340 ICI.isEquality() && !Shift->isArithmeticShift() &&
1341 !isa<Constant>(Shift->getOperand(0))) {
1342 // Compute C << Y.
1343 Value *NS;
1344 if (Shift->getOpcode() == Instruction::LShr) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001345 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001346 } else {
1347 // Insert a logical shift.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001348 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001349 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001350
Chris Lattner2188e402010-01-04 07:37:31 +00001351 // Compute X & (C << Y).
Jim Grosbach129c52a2011-09-30 18:09:53 +00001352 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001353 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001354
Chris Lattner2188e402010-01-04 07:37:31 +00001355 ICI.setOperand(0, NewAnd);
1356 return &ICI;
1357 }
Paul Redmond5917f4c2012-12-19 19:47:13 +00001358
David Majnemer0ffccf72014-08-24 09:10:57 +00001359 // (icmp pred (and (or (lshr X, Y), X), 1), 0) -->
1360 // (icmp pred (and X, (or (shl 1, Y), 1), 0))
1361 //
1362 // iff pred isn't signed
1363 {
1364 Value *X, *Y, *LShr;
1365 if (!ICI.isSigned() && RHSV == 0) {
1366 if (match(LHSI->getOperand(1), m_One())) {
1367 Constant *One = cast<Constant>(LHSI->getOperand(1));
1368 Value *Or = LHSI->getOperand(0);
1369 if (match(Or, m_Or(m_Value(LShr), m_Value(X))) &&
1370 match(LShr, m_LShr(m_Specific(X), m_Value(Y)))) {
1371 unsigned UsesRemoved = 0;
1372 if (LHSI->hasOneUse())
1373 ++UsesRemoved;
1374 if (Or->hasOneUse())
1375 ++UsesRemoved;
1376 if (LShr->hasOneUse())
1377 ++UsesRemoved;
1378 Value *NewOr = nullptr;
1379 // Compute X & ((1 << Y) | 1)
1380 if (auto *C = dyn_cast<Constant>(Y)) {
1381 if (UsesRemoved >= 1)
1382 NewOr =
1383 ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1384 } else {
1385 if (UsesRemoved >= 3)
1386 NewOr = Builder->CreateOr(Builder->CreateShl(One, Y,
1387 LShr->getName(),
1388 /*HasNUW=*/true),
1389 One, Or->getName());
1390 }
1391 if (NewOr) {
1392 Value *NewAnd = Builder->CreateAnd(X, NewOr, LHSI->getName());
1393 ICI.setOperand(0, NewAnd);
1394 return &ICI;
1395 }
1396 }
1397 }
1398 }
1399 }
1400
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001401 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1402 // bit set in (X & AndCst) will produce a result greater than RHSV.
Paul Redmond5917f4c2012-12-19 19:47:13 +00001403 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001404 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1405 if ((NTZ < AndCst->getBitWidth()) &&
1406 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
Paul Redmond5917f4c2012-12-19 19:47:13 +00001407 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1408 Constant::getNullValue(RHS->getType()));
1409 }
Chris Lattner2188e402010-01-04 07:37:31 +00001410 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001411
Chris Lattner2188e402010-01-04 07:37:31 +00001412 // Try to optimize things like "A[i]&42 == 0" to index computations.
1413 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1414 if (GetElementPtrInst *GEP =
1415 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1416 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1417 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1418 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1419 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1420 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1421 return Res;
1422 }
1423 }
David Majnemer414d4e52013-07-09 08:09:32 +00001424
1425 // X & -C == -C -> X > u ~C
1426 // X & -C != -C -> X <= u ~C
1427 // iff C is a power of 2
1428 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1429 return new ICmpInst(
1430 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1431 : ICmpInst::ICMP_ULE,
1432 LHSI->getOperand(0), SubOne(RHS));
Chris Lattner2188e402010-01-04 07:37:31 +00001433 break;
1434
1435 case Instruction::Or: {
1436 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1437 break;
1438 Value *P, *Q;
1439 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1440 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1441 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner2188e402010-01-04 07:37:31 +00001442 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1443 Constant::getNullValue(P->getType()));
1444 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1445 Constant::getNullValue(Q->getType()));
1446 Instruction *Op;
1447 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1448 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1449 else
1450 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1451 return Op;
1452 }
1453 break;
1454 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001455
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001456 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1457 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1458 if (!Val) break;
1459
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001460 // If this is a signed comparison to 0 and the mul is sign preserving,
1461 // use the mul LHS operand instead.
1462 ICmpInst::Predicate pred = ICI.getPredicate();
1463 if (isSignTest(pred, RHS) && !Val->isZero() &&
1464 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1465 return new ICmpInst(Val->isNegative() ?
1466 ICmpInst::getSwappedPredicate(pred) : pred,
1467 LHSI->getOperand(0),
1468 Constant::getNullValue(RHS->getType()));
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001469
1470 break;
1471 }
1472
Chris Lattner2188e402010-01-04 07:37:31 +00001473 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
Chris Lattner2188e402010-01-04 07:37:31 +00001474 uint32_t TypeBits = RHSV.getBitWidth();
David Majnemerb889e402013-06-28 23:42:03 +00001475 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1476 if (!ShAmt) {
1477 Value *X;
1478 // (1 << X) pred P2 -> X pred Log2(P2)
1479 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1480 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1481 ICmpInst::Predicate Pred = ICI.getPredicate();
1482 if (ICI.isUnsigned()) {
1483 if (!RHSVIsPowerOf2) {
1484 // (1 << X) < 30 -> X <= 4
1485 // (1 << X) <= 30 -> X <= 4
1486 // (1 << X) >= 30 -> X > 4
1487 // (1 << X) > 30 -> X > 4
1488 if (Pred == ICmpInst::ICMP_ULT)
1489 Pred = ICmpInst::ICMP_ULE;
1490 else if (Pred == ICmpInst::ICMP_UGE)
1491 Pred = ICmpInst::ICMP_UGT;
1492 }
1493 unsigned RHSLog2 = RHSV.logBase2();
1494
1495 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
David Majnemerb889e402013-06-28 23:42:03 +00001496 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1497 if (RHSLog2 == TypeBits-1) {
1498 if (Pred == ICmpInst::ICMP_UGE)
1499 Pred = ICmpInst::ICMP_EQ;
David Majnemerb889e402013-06-28 23:42:03 +00001500 else if (Pred == ICmpInst::ICMP_ULT)
1501 Pred = ICmpInst::ICMP_NE;
1502 }
1503
1504 return new ICmpInst(Pred, X,
1505 ConstantInt::get(RHS->getType(), RHSLog2));
1506 } else if (ICI.isSigned()) {
1507 if (RHSV.isAllOnesValue()) {
1508 // (1 << X) <= -1 -> X == 31
1509 if (Pred == ICmpInst::ICMP_SLE)
1510 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1511 ConstantInt::get(RHS->getType(), TypeBits-1));
1512
1513 // (1 << X) > -1 -> X != 31
1514 if (Pred == ICmpInst::ICMP_SGT)
1515 return new ICmpInst(ICmpInst::ICMP_NE, X,
1516 ConstantInt::get(RHS->getType(), TypeBits-1));
1517 } else if (!RHSV) {
1518 // (1 << X) < 0 -> X == 31
1519 // (1 << X) <= 0 -> X == 31
1520 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1521 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1522 ConstantInt::get(RHS->getType(), TypeBits-1));
1523
1524 // (1 << X) >= 0 -> X != 31
1525 // (1 << X) > 0 -> X != 31
1526 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1527 return new ICmpInst(ICmpInst::ICMP_NE, X,
1528 ConstantInt::get(RHS->getType(), TypeBits-1));
1529 }
1530 } else if (ICI.isEquality()) {
1531 if (RHSVIsPowerOf2)
1532 return new ICmpInst(
1533 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
David Majnemerb889e402013-06-28 23:42:03 +00001534 }
1535 }
1536 break;
1537 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001538
Chris Lattner2188e402010-01-04 07:37:31 +00001539 // Check that the shift amount is in range. If not, don't perform
1540 // undefined shifts. When the shift is visited it will be
1541 // simplified.
1542 if (ShAmt->uge(TypeBits))
1543 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001544
Chris Lattner2188e402010-01-04 07:37:31 +00001545 if (ICI.isEquality()) {
1546 // If we are comparing against bits always shifted out, the
1547 // comparison cannot succeed.
1548 Constant *Comp =
1549 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1550 ShAmt);
1551 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1552 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001553 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattner2188e402010-01-04 07:37:31 +00001554 return ReplaceInstUsesWith(ICI, Cst);
1555 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001556
Chris Lattner98457102011-02-10 05:23:05 +00001557 // If the shift is NUW, then it is just shifting out zeros, no need for an
1558 // AND.
1559 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1560 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1561 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001562
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001563 // If the shift is NSW and we compare to 0, then it is just shifting out
1564 // sign bits, no need for an AND either.
1565 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1566 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1567 ConstantExpr::getLShr(RHS, ShAmt));
1568
Chris Lattner2188e402010-01-04 07:37:31 +00001569 if (LHSI->hasOneUse()) {
1570 // Otherwise strength reduce the shift into an and.
1571 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Jakub Staszakbddea112013-06-06 20:18:46 +00001572 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
1573 TypeBits - ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001574
Chris Lattner2188e402010-01-04 07:37:31 +00001575 Value *And =
1576 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1577 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner98457102011-02-10 05:23:05 +00001578 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner2188e402010-01-04 07:37:31 +00001579 }
1580 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001581
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001582 // If this is a signed comparison to 0 and the shift is sign preserving,
1583 // use the shift LHS operand instead.
1584 ICmpInst::Predicate pred = ICI.getPredicate();
1585 if (isSignTest(pred, RHS) &&
1586 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1587 return new ICmpInst(pred,
1588 LHSI->getOperand(0),
1589 Constant::getNullValue(RHS->getType()));
1590
Chris Lattner2188e402010-01-04 07:37:31 +00001591 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1592 bool TrueIfSigned = false;
1593 if (LHSI->hasOneUse() &&
1594 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1595 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattner43273af2011-02-13 08:07:21 +00001596 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach129c52a2011-09-30 18:09:53 +00001597 APInt::getOneBitSet(TypeBits,
Chris Lattner43273af2011-02-13 08:07:21 +00001598 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00001599 Value *And =
1600 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1601 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1602 And, Constant::getNullValue(And->getType()));
1603 }
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001604
1605 // Transform (icmp pred iM (shl iM %v, N), CI)
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00001606 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1607 // 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 +00001608 // This enables to get rid of the shift in favor of a trunc which can be
1609 // free on the target. It has the additional benefit of comparing to a
1610 // smaller constant, which will be target friendly.
1611 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00001612 if (LHSI->hasOneUse() &&
1613 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001614 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1615 Constant *NCI = ConstantExpr::getTrunc(
1616 ConstantExpr::getAShr(RHS,
1617 ConstantInt::get(RHS->getType(), Amt)),
1618 NTy);
1619 return new ICmpInst(ICI.getPredicate(),
1620 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaison1fd843e2013-02-15 15:18:17 +00001621 NCI);
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001622 }
1623
Chris Lattner2188e402010-01-04 07:37:31 +00001624 break;
1625 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001626
Chris Lattner2188e402010-01-04 07:37:31 +00001627 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewycky174a7052011-02-28 08:31:40 +00001628 case Instruction::AShr: {
1629 // Handle equality comparisons of shift-by-constant.
1630 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1631 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1632 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattnerd369f572011-02-13 07:43:07 +00001633 return Res;
Nick Lewycky174a7052011-02-28 08:31:40 +00001634 }
1635
1636 // Handle exact shr's.
1637 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1638 if (RHSV.isMinValue())
1639 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1640 }
Chris Lattner2188e402010-01-04 07:37:31 +00001641 break;
Nick Lewycky174a7052011-02-28 08:31:40 +00001642 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001643
Chris Lattner2188e402010-01-04 07:37:31 +00001644 case Instruction::SDiv:
1645 case Instruction::UDiv:
1646 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach129c52a2011-09-30 18:09:53 +00001647 // Fold this div into the comparison, producing a range check.
1648 // Determine, based on the divide type, what the range is being
1649 // checked. If there is an overflow on the low or high side, remember
Chris Lattner2188e402010-01-04 07:37:31 +00001650 // it, otherwise compute the range [low, hi) bounding the new value.
1651 // See: InsertRangeTest above for the kinds of replacements possible.
1652 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1653 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1654 DivRHS))
1655 return R;
1656 break;
1657
David Majnemerf2a9a512013-07-09 07:50:59 +00001658 case Instruction::Sub: {
1659 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
1660 if (!LHSC) break;
1661 const APInt &LHSV = LHSC->getValue();
1662
1663 // C1-X <u C2 -> (X|(C2-1)) == C1
1664 // iff C1 & (C2-1) == C2-1
1665 // C2 is a power of 2
1666 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1667 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
1668 return new ICmpInst(ICmpInst::ICMP_EQ,
1669 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
1670 LHSC);
1671
David Majnemereeed73b2013-07-09 09:24:35 +00001672 // C1-X >u C2 -> (X|C2) != C1
David Majnemerf2a9a512013-07-09 07:50:59 +00001673 // iff C1 & C2 == C2
1674 // C2+1 is a power of 2
1675 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1676 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
1677 return new ICmpInst(ICmpInst::ICMP_NE,
1678 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
1679 break;
1680 }
1681
Chris Lattner2188e402010-01-04 07:37:31 +00001682 case Instruction::Add:
1683 // Fold: icmp pred (add X, C1), C2
1684 if (!ICI.isEquality()) {
1685 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1686 if (!LHSC) break;
1687 const APInt &LHSV = LHSC->getValue();
1688
1689 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1690 .subtract(LHSV);
1691
1692 if (ICI.isSigned()) {
1693 if (CR.getLower().isSignBit()) {
1694 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001695 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00001696 } else if (CR.getUpper().isSignBit()) {
1697 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001698 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00001699 }
1700 } else {
1701 if (CR.getLower().isMinValue()) {
1702 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001703 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00001704 } else if (CR.getUpper().isMinValue()) {
1705 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001706 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00001707 }
1708 }
David Majnemerfa90a0b2013-07-08 11:53:08 +00001709
David Majnemerbafa5372013-07-09 07:58:32 +00001710 // X-C1 <u C2 -> (X & -C2) == C1
1711 // iff C1 & (C2-1) == 0
1712 // C2 is a power of 2
David Majnemerfa90a0b2013-07-08 11:53:08 +00001713 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
David Majnemerbafa5372013-07-09 07:58:32 +00001714 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
David Majnemerfa90a0b2013-07-08 11:53:08 +00001715 return new ICmpInst(ICmpInst::ICMP_EQ,
1716 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
1717 ConstantExpr::getNeg(LHSC));
David Majnemerbafa5372013-07-09 07:58:32 +00001718
David Majnemereeed73b2013-07-09 09:24:35 +00001719 // X-C1 >u C2 -> (X & ~C2) != C1
David Majnemerbafa5372013-07-09 07:58:32 +00001720 // iff C1 & C2 == 0
1721 // C2+1 is a power of 2
1722 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1723 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
1724 return new ICmpInst(ICmpInst::ICMP_NE,
1725 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
1726 ConstantExpr::getNeg(LHSC));
Chris Lattner2188e402010-01-04 07:37:31 +00001727 }
1728 break;
1729 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001730
Chris Lattner2188e402010-01-04 07:37:31 +00001731 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1732 if (ICI.isEquality()) {
1733 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001734
1735 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner2188e402010-01-04 07:37:31 +00001736 // the second operand is a constant, simplify a bit.
1737 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1738 switch (BO->getOpcode()) {
1739 case Instruction::SRem:
1740 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1741 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1742 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohman4ce1fb12010-04-08 23:03:40 +00001743 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001744 Value *NewRem =
1745 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1746 BO->getName());
1747 return new ICmpInst(ICI.getPredicate(), NewRem,
1748 Constant::getNullValue(BO->getType()));
1749 }
1750 }
1751 break;
1752 case Instruction::Add:
1753 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1754 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1755 if (BO->hasOneUse())
1756 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1757 ConstantExpr::getSub(RHS, BOp1C));
1758 } else if (RHSV == 0) {
1759 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1760 // efficiently invertible, or if the add has just this one use.
1761 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001762
Chris Lattner2188e402010-01-04 07:37:31 +00001763 if (Value *NegVal = dyn_castNegVal(BOp1))
1764 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner31b106d2011-04-26 20:02:45 +00001765 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner2188e402010-01-04 07:37:31 +00001766 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner31b106d2011-04-26 20:02:45 +00001767 if (BO->hasOneUse()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001768 Value *Neg = Builder->CreateNeg(BOp1);
1769 Neg->takeName(BO);
1770 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1771 }
1772 }
1773 break;
1774 case Instruction::Xor:
1775 // For the xor case, we can xor two constants together, eliminating
1776 // the explicit xor.
Benjamin Kramerc9708492011-06-13 15:24:24 +00001777 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1778 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner2188e402010-01-04 07:37:31 +00001779 ConstantExpr::getXor(RHS, BOC));
Benjamin Kramerc9708492011-06-13 15:24:24 +00001780 } else if (RHSV == 0) {
1781 // Replace ((xor A, B) != 0) with (A != B)
Chris Lattner2188e402010-01-04 07:37:31 +00001782 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1783 BO->getOperand(1));
Benjamin Kramerc9708492011-06-13 15:24:24 +00001784 }
Chris Lattner2188e402010-01-04 07:37:31 +00001785 break;
Benjamin Kramerc9708492011-06-13 15:24:24 +00001786 case Instruction::Sub:
1787 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1788 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1789 if (BO->hasOneUse())
1790 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1791 ConstantExpr::getSub(BOp0C, RHS));
1792 } else if (RHSV == 0) {
1793 // Replace ((sub A, B) != 0) with (A != B)
1794 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1795 BO->getOperand(1));
1796 }
1797 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001798 case Instruction::Or:
1799 // If bits are being or'd in that are not present in the constant we
1800 // are comparing against, then the comparison could never succeed!
Eli Friedman0428a612010-07-29 18:03:33 +00001801 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001802 Constant *NotCI = ConstantExpr::getNot(RHS);
1803 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Jakub Staszakbddea112013-06-06 20:18:46 +00001804 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Chris Lattner2188e402010-01-04 07:37:31 +00001805 }
1806 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001807
Chris Lattner2188e402010-01-04 07:37:31 +00001808 case Instruction::And:
1809 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1810 // If bits are being compared against that are and'd out, then the
1811 // comparison can never succeed!
1812 if ((RHSV & ~BOC->getValue()) != 0)
Jakub Staszakbddea112013-06-06 20:18:46 +00001813 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001814
Chris Lattner2188e402010-01-04 07:37:31 +00001815 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1816 if (RHS == BOC && RHSV.isPowerOf2())
1817 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1818 ICmpInst::ICMP_NE, LHSI,
1819 Constant::getNullValue(RHS->getType()));
Benjamin Kramer9eca5fe2011-07-04 20:16:36 +00001820
1821 // Don't perform the following transforms if the AND has multiple uses
1822 if (!BO->hasOneUse())
1823 break;
1824
Chris Lattner2188e402010-01-04 07:37:31 +00001825 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1826 if (BOC->getValue().isSignBit()) {
1827 Value *X = BO->getOperand(0);
1828 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001829 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00001830 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1831 return new ICmpInst(pred, X, Zero);
1832 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001833
Chris Lattner2188e402010-01-04 07:37:31 +00001834 // ((X & ~7) == 0) --> X < 8
1835 if (RHSV == 0 && isHighOnes(BOC)) {
1836 Value *X = BO->getOperand(0);
1837 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001838 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00001839 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1840 return new ICmpInst(pred, X, NegX);
1841 }
1842 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001843 break;
1844 case Instruction::Mul:
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001845 if (RHSV == 0 && BO->hasNoSignedWrap()) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001846 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1847 // The trivial case (mul X, 0) is handled by InstSimplify
1848 // General case : (mul X, C) != 0 iff X != 0
1849 // (mul X, C) == 0 iff X == 0
1850 if (!BOC->isZero())
1851 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1852 Constant::getNullValue(RHS->getType()));
1853 }
1854 }
1855 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001856 default: break;
1857 }
1858 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1859 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner54f4e392010-01-05 18:09:56 +00001860 switch (II->getIntrinsicID()) {
1861 case Intrinsic::bswap:
Chris Lattner2188e402010-01-04 07:37:31 +00001862 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001863 ICI.setOperand(0, II->getArgOperand(0));
Jakub Staszakbddea112013-06-06 20:18:46 +00001864 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
Chris Lattner2188e402010-01-04 07:37:31 +00001865 return &ICI;
Chris Lattner54f4e392010-01-05 18:09:56 +00001866 case Intrinsic::ctlz:
1867 case Intrinsic::cttz:
1868 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1869 if (RHSV == RHS->getType()->getBitWidth()) {
1870 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001871 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00001872 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1873 return &ICI;
1874 }
1875 break;
1876 case Intrinsic::ctpop:
1877 // popcount(A) == 0 -> A == 0 and likewise for !=
1878 if (RHS->isZero()) {
1879 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001880 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00001881 ICI.setOperand(1, RHS);
1882 return &ICI;
1883 }
1884 break;
1885 default:
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001886 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001887 }
1888 }
1889 }
Craig Topperf40110f2014-04-25 05:29:35 +00001890 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001891}
1892
1893/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1894/// We only handle extending casts so far.
1895///
1896Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1897 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1898 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001899 Type *SrcTy = LHSCIOp->getType();
1900 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00001901 Value *RHSCIOp;
1902
Jim Grosbach129c52a2011-09-30 18:09:53 +00001903 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00001904 // integer type is the same size as the pointer type.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001905 if (DL && LHSCI->getOpcode() == Instruction::PtrToInt &&
1906 DL->getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001907 Value *RHSOp = nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001908 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1909 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1910 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1911 RHSOp = RHSC->getOperand(0);
1912 // If the pointer types don't match, insert a bitcast.
1913 if (LHSCIOp->getType() != RHSOp->getType())
1914 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1915 }
1916
1917 if (RHSOp)
1918 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1919 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001920
Chris Lattner2188e402010-01-04 07:37:31 +00001921 // The code below only handles extension cast instructions, so far.
1922 // Enforce this.
1923 if (LHSCI->getOpcode() != Instruction::ZExt &&
1924 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00001925 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001926
1927 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1928 bool isSignedCmp = ICI.isSigned();
1929
1930 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1931 // Not an extension from the same type?
1932 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001933 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001934 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001935
Chris Lattner2188e402010-01-04 07:37:31 +00001936 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1937 // and the other is a zext), then we can't handle this.
1938 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00001939 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001940
1941 // Deal with equality cases early.
1942 if (ICI.isEquality())
1943 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1944
1945 // A signed comparison of sign extended values simplifies into a
1946 // signed comparison.
1947 if (isSignedCmp && isSignedExt)
1948 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1949
1950 // The other three cases all fold into an unsigned comparison.
1951 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1952 }
1953
1954 // If we aren't dealing with a constant on the RHS, exit early
1955 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1956 if (!CI)
Craig Topperf40110f2014-04-25 05:29:35 +00001957 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001958
1959 // Compute the constant that would happen if we truncated to SrcTy then
1960 // reextended to DestTy.
1961 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1962 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1963 Res1, DestTy);
1964
1965 // If the re-extended constant didn't change...
1966 if (Res2 == CI) {
1967 // Deal with equality cases early.
1968 if (ICI.isEquality())
1969 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1970
1971 // A signed comparison of sign extended values simplifies into a
1972 // signed comparison.
1973 if (isSignedExt && isSignedCmp)
1974 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1975
1976 // The other three cases all fold into an unsigned comparison.
1977 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1978 }
1979
Jim Grosbach129c52a2011-09-30 18:09:53 +00001980 // The re-extended constant changed so the constant cannot be represented
Chris Lattner2188e402010-01-04 07:37:31 +00001981 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00001982 // All the cases that fold to true or false will have already been handled
1983 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00001984
Duncan Sands8fb2c382011-01-20 13:21:55 +00001985 if (isSignedCmp || !isSignedExt)
Craig Topperf40110f2014-04-25 05:29:35 +00001986 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001987
1988 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1989 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00001990
1991 // We're performing an unsigned comp with a sign extended value.
1992 // This is true if the input is >= 0. [aka >s -1]
1993 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1994 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00001995
1996 // Finally, return the value computed.
Duncan Sands8fb2c382011-01-20 13:21:55 +00001997 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner2188e402010-01-04 07:37:31 +00001998 return ReplaceInstUsesWith(ICI, Result);
1999
Duncan Sands8fb2c382011-01-20 13:21:55 +00002000 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00002001 return BinaryOperator::CreateNot(Result);
2002}
2003
Chris Lattneree61c1d2010-12-19 17:52:50 +00002004/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
2005/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00002006/// If this is of the form:
2007/// sum = a + b
2008/// if (sum+128 >u 255)
2009/// Then replace it with llvm.sadd.with.overflow.i8.
2010///
Chris Lattneree61c1d2010-12-19 17:52:50 +00002011static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2012 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00002013 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00002014 // The transformation we're trying to do here is to transform this into an
2015 // llvm.sadd.with.overflow. To do this, we have to replace the original add
2016 // with a narrower add, and discard the add-with-constant that is part of the
2017 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00002018
Chris Lattnerf29562d2010-12-19 17:59:02 +00002019 // In order to eliminate the add-with-constant, the compare can be its only
2020 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00002021 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00002022 if (!AddWithCst->hasOneUse()) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002023
Chris Lattnerc56c8452010-12-19 18:22:06 +00002024 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
Craig Topperf40110f2014-04-25 05:29:35 +00002025 if (!CI2->getValue().isPowerOf2()) return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002026 unsigned NewWidth = CI2->getValue().countTrailingZeros();
Craig Topperf40110f2014-04-25 05:29:35 +00002027 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002028
Chris Lattnerc56c8452010-12-19 18:22:06 +00002029 // The width of the new add formed is 1 more than the bias.
2030 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002031
Chris Lattnerc56c8452010-12-19 18:22:06 +00002032 // Check to see that CI1 is an all-ones value with NewWidth bits.
2033 if (CI1->getBitWidth() == NewWidth ||
2034 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
Craig Topperf40110f2014-04-25 05:29:35 +00002035 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002036
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002037 // This is only really a signed overflow check if the inputs have been
2038 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2039 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2040 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
Hal Finkel60db0582014-09-07 18:57:58 +00002041 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2042 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
Craig Topperf40110f2014-04-25 05:29:35 +00002043 return nullptr;
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002044
Jim Grosbach129c52a2011-09-30 18:09:53 +00002045 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00002046 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2047 // and truncates that discard the high bits of the add. Verify that this is
2048 // the case.
2049 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00002050 for (User *U : OrigAdd->users()) {
2051 if (U == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002052
Chris Lattnerc56c8452010-12-19 18:22:06 +00002053 // Only accept truncates for now. We would really like a nice recursive
2054 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2055 // chain to see which bits of a value are actually demanded. If the
2056 // original add had another add which was then immediately truncated, we
2057 // could still do the transformation.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002058 TruncInst *TI = dyn_cast<TruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00002059 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2060 return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002061 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002062
Chris Lattneree61c1d2010-12-19 17:52:50 +00002063 // If the pattern matches, truncate the inputs to the narrower type and
2064 // use the sadd_with_overflow intrinsic to efficiently compute both the
2065 // result and the overflow bit.
Chris Lattner79874562010-12-19 18:35:09 +00002066 Module *M = I.getParent()->getParent()->getParent();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002067
Jay Foadb804a2b2011-07-12 14:06:48 +00002068 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Chris Lattner79874562010-12-19 18:35:09 +00002069 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
Benjamin Kramere6e19332011-07-14 17:45:39 +00002070 NewType);
Chris Lattner79874562010-12-19 18:35:09 +00002071
Chris Lattnerce2995a2010-12-19 18:38:44 +00002072 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002073
Chris Lattner79874562010-12-19 18:35:09 +00002074 // Put the new code above the original add, in case there are any uses of the
2075 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002076 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002077
Chris Lattner79874562010-12-19 18:35:09 +00002078 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2079 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
2080 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
2081 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2082 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002083
Chris Lattneree61c1d2010-12-19 17:52:50 +00002084 // The inner add was the result of the narrow add, zero extended to the
2085 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattnerce2995a2010-12-19 18:38:44 +00002086 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002087
Chris Lattner79874562010-12-19 18:35:09 +00002088 // The original icmp gets replaced with the overflow value.
2089 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00002090}
Chris Lattner2188e402010-01-04 07:37:31 +00002091
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002092static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
2093 InstCombiner &IC) {
2094 // Don't bother doing this transformation for pointers, don't do it for
2095 // vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00002096 if (!isa<IntegerType>(OrigAddV->getType())) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002097
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002098 // If the add is a constant expr, then we don't bother transforming it.
2099 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
Craig Topperf40110f2014-04-25 05:29:35 +00002100 if (!OrigAdd) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002101
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002102 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002103
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002104 // Put the new code above the original add, in case there are any uses of the
2105 // add between the add and the compare.
2106 InstCombiner::BuilderTy *Builder = IC.Builder;
2107 Builder->SetInsertPoint(OrigAdd);
2108
2109 Module *M = I.getParent()->getParent()->getParent();
Jay Foadb804a2b2011-07-12 14:06:48 +00002110 Type *Ty = LHS->getType();
Benjamin Kramere6e19332011-07-14 17:45:39 +00002111 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002112 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
2113 Value *Add = Builder->CreateExtractValue(Call, 0);
2114
2115 IC.ReplaceInstUsesWith(*OrigAdd, Add);
2116
2117 // The original icmp gets replaced with the overflow value.
2118 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
2119}
2120
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002121/// \brief Recognize and process idiom involving test for multiplication
2122/// overflow.
2123///
2124/// The caller has matched a pattern of the form:
2125/// I = cmp u (mul(zext A, zext B), V
2126/// The function checks if this is a test for overflow and if so replaces
2127/// multiplication with call to 'mul.with.overflow' intrinsic.
2128///
2129/// \param I Compare instruction.
2130/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2131/// the compare instruction. Must be of integer type.
2132/// \param OtherVal The other argument of compare instruction.
2133/// \returns Instruction which must replace the compare instruction, NULL if no
2134/// replacement required.
2135static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2136 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00002137 // Don't bother doing this transformation for pointers, don't do it for
2138 // vectors.
2139 if (!isa<IntegerType>(MulVal->getType()))
2140 return nullptr;
2141
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002142 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2143 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002144 Instruction *MulInstr = cast<Instruction>(MulVal);
2145 assert(MulInstr->getOpcode() == Instruction::Mul);
2146
2147 Instruction *LHS = cast<Instruction>(MulInstr->getOperand(0)),
2148 *RHS = cast<Instruction>(MulInstr->getOperand(1));
2149 assert(LHS->getOpcode() == Instruction::ZExt);
2150 assert(RHS->getOpcode() == Instruction::ZExt);
2151 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2152
2153 // Calculate type and width of the result produced by mul.with.overflow.
2154 Type *TyA = A->getType(), *TyB = B->getType();
2155 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2156 WidthB = TyB->getPrimitiveSizeInBits();
2157 unsigned MulWidth;
2158 Type *MulType;
2159 if (WidthB > WidthA) {
2160 MulWidth = WidthB;
2161 MulType = TyB;
2162 } else {
2163 MulWidth = WidthA;
2164 MulType = TyA;
2165 }
2166
2167 // In order to replace the original mul with a narrower mul.with.overflow,
2168 // all uses must ignore upper bits of the product. The number of used low
2169 // bits must be not greater than the width of mul.with.overflow.
2170 if (MulVal->hasNUsesOrMore(2))
2171 for (User *U : MulVal->users()) {
2172 if (U == &I)
2173 continue;
2174 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2175 // Check if truncation ignores bits above MulWidth.
2176 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2177 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002178 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002179 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2180 // Check if AND ignores bits above MulWidth.
2181 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00002182 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002183 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2184 const APInt &CVal = CI->getValue();
2185 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002186 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002187 }
2188 } else {
2189 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00002190 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002191 }
2192 }
2193
2194 // Recognize patterns
2195 switch (I.getPredicate()) {
2196 case ICmpInst::ICMP_EQ:
2197 case ICmpInst::ICMP_NE:
2198 // Recognize pattern:
2199 // mulval = mul(zext A, zext B)
2200 // cmp eq/neq mulval, zext trunc mulval
2201 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2202 if (Zext->hasOneUse()) {
2203 Value *ZextArg = Zext->getOperand(0);
2204 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2205 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2206 break; //Recognized
2207 }
2208
2209 // Recognize pattern:
2210 // mulval = mul(zext A, zext B)
2211 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2212 ConstantInt *CI;
2213 Value *ValToMask;
2214 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2215 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00002216 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002217 const APInt &CVal = CI->getValue() + 1;
2218 if (CVal.isPowerOf2()) {
2219 unsigned MaskWidth = CVal.logBase2();
2220 if (MaskWidth == MulWidth)
2221 break; // Recognized
2222 }
2223 }
Craig Topperf40110f2014-04-25 05:29:35 +00002224 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002225
2226 case ICmpInst::ICMP_UGT:
2227 // Recognize pattern:
2228 // mulval = mul(zext A, zext B)
2229 // cmp ugt mulval, max
2230 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2231 APInt MaxVal = APInt::getMaxValue(MulWidth);
2232 MaxVal = MaxVal.zext(CI->getBitWidth());
2233 if (MaxVal.eq(CI->getValue()))
2234 break; // Recognized
2235 }
Craig Topperf40110f2014-04-25 05:29:35 +00002236 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002237
2238 case ICmpInst::ICMP_UGE:
2239 // Recognize pattern:
2240 // mulval = mul(zext A, zext B)
2241 // cmp uge mulval, max+1
2242 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2243 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2244 if (MaxVal.eq(CI->getValue()))
2245 break; // Recognized
2246 }
Craig Topperf40110f2014-04-25 05:29:35 +00002247 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002248
2249 case ICmpInst::ICMP_ULE:
2250 // Recognize pattern:
2251 // mulval = mul(zext A, zext B)
2252 // cmp ule mulval, max
2253 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2254 APInt MaxVal = APInt::getMaxValue(MulWidth);
2255 MaxVal = MaxVal.zext(CI->getBitWidth());
2256 if (MaxVal.eq(CI->getValue()))
2257 break; // Recognized
2258 }
Craig Topperf40110f2014-04-25 05:29:35 +00002259 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002260
2261 case ICmpInst::ICMP_ULT:
2262 // Recognize pattern:
2263 // mulval = mul(zext A, zext B)
2264 // cmp ule mulval, max + 1
2265 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002266 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002267 if (MaxVal.eq(CI->getValue()))
2268 break; // Recognized
2269 }
Craig Topperf40110f2014-04-25 05:29:35 +00002270 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002271
2272 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002273 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002274 }
2275
2276 InstCombiner::BuilderTy *Builder = IC.Builder;
2277 Builder->SetInsertPoint(MulInstr);
2278 Module *M = I.getParent()->getParent()->getParent();
2279
2280 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2281 Value *MulA = A, *MulB = B;
2282 if (WidthA < MulWidth)
2283 MulA = Builder->CreateZExt(A, MulType);
2284 if (WidthB < MulWidth)
2285 MulB = Builder->CreateZExt(B, MulType);
2286 Value *F =
2287 Intrinsic::getDeclaration(M, Intrinsic::umul_with_overflow, MulType);
2288 CallInst *Call = Builder->CreateCall2(F, MulA, MulB, "umul");
2289 IC.Worklist.Add(MulInstr);
2290
2291 // If there are uses of mul result other than the comparison, we know that
2292 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002293 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002294 if (MulVal->hasNUsesOrMore(2)) {
2295 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2296 for (User *U : MulVal->users()) {
2297 if (U == &I || U == OtherVal)
2298 continue;
2299 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2300 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
2301 IC.ReplaceInstUsesWith(*TI, Mul);
2302 else
2303 TI->setOperand(0, Mul);
2304 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2305 assert(BO->getOpcode() == Instruction::And);
2306 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2307 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2308 APInt ShortMask = CI->getValue().trunc(MulWidth);
2309 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2310 Instruction *Zext =
2311 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2312 IC.Worklist.Add(Zext);
2313 IC.ReplaceInstUsesWith(*BO, Zext);
2314 } else {
2315 llvm_unreachable("Unexpected Binary operation");
2316 }
2317 IC.Worklist.Add(cast<Instruction>(U));
2318 }
2319 }
2320 if (isa<Instruction>(OtherVal))
2321 IC.Worklist.Add(cast<Instruction>(OtherVal));
2322
2323 // The original icmp gets replaced with the overflow value, maybe inverted
2324 // depending on predicate.
2325 bool Inverse = false;
2326 switch (I.getPredicate()) {
2327 case ICmpInst::ICMP_NE:
2328 break;
2329 case ICmpInst::ICMP_EQ:
2330 Inverse = true;
2331 break;
2332 case ICmpInst::ICMP_UGT:
2333 case ICmpInst::ICMP_UGE:
2334 if (I.getOperand(0) == MulVal)
2335 break;
2336 Inverse = true;
2337 break;
2338 case ICmpInst::ICMP_ULT:
2339 case ICmpInst::ICMP_ULE:
2340 if (I.getOperand(1) == MulVal)
2341 break;
2342 Inverse = true;
2343 break;
2344 default:
2345 llvm_unreachable("Unexpected predicate");
2346 }
2347 if (Inverse) {
2348 Value *Res = Builder->CreateExtractValue(Call, 1);
2349 return BinaryOperator::CreateNot(Res);
2350 }
2351
2352 return ExtractValueInst::Create(Call, 1);
2353}
2354
Owen Andersond490c2d2011-01-11 00:36:45 +00002355// DemandedBitsLHSMask - When performing a comparison against a constant,
2356// it is possible that not all the bits in the LHS are demanded. This helper
2357// method computes the mask that IS demanded.
2358static APInt DemandedBitsLHSMask(ICmpInst &I,
2359 unsigned BitWidth, bool isSignCheck) {
2360 if (isSignCheck)
2361 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002362
Owen Andersond490c2d2011-01-11 00:36:45 +00002363 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2364 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00002365 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002366
Owen Andersond490c2d2011-01-11 00:36:45 +00002367 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002368 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00002369 // correspond to the trailing ones of the comparand. The value of these
2370 // bits doesn't impact the outcome of the comparison, because any value
2371 // greater than the RHS must differ in a bit higher than these due to carry.
2372 case ICmpInst::ICMP_UGT: {
2373 unsigned trailingOnes = RHS.countTrailingOnes();
2374 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2375 return ~lowBitsSet;
2376 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002377
Owen Andersond490c2d2011-01-11 00:36:45 +00002378 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2379 // Any value less than the RHS must differ in a higher bit because of carries.
2380 case ICmpInst::ICMP_ULT: {
2381 unsigned trailingZeros = RHS.countTrailingZeros();
2382 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2383 return ~lowBitsSet;
2384 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002385
Owen Andersond490c2d2011-01-11 00:36:45 +00002386 default:
2387 return APInt::getAllOnesValue(BitWidth);
2388 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002389
Owen Andersond490c2d2011-01-11 00:36:45 +00002390}
Chris Lattner2188e402010-01-04 07:37:31 +00002391
Quentin Colombet5ab55552013-09-09 20:56:48 +00002392/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2393/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00002394/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00002395/// as subtract operands and their positions in those instructions.
2396/// The rational is that several architectures use the same instruction for
2397/// both subtract and cmp, thus it is better if the order of those operands
2398/// match.
2399/// \return true if Op0 and Op1 should be swapped.
2400static bool swapMayExposeCSEOpportunities(const Value * Op0,
2401 const Value * Op1) {
2402 // Filter out pointer value as those cannot appears directly in subtract.
2403 // FIXME: we may want to go through inttoptrs or bitcasts.
2404 if (Op0->getType()->isPointerTy())
2405 return false;
2406 // Count every uses of both Op0 and Op1 in a subtract.
2407 // Each time Op0 is the first operand, count -1: swapping is bad, the
2408 // subtract has already the same layout as the compare.
2409 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00002410 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002411 // At the end, if the benefit is greater than 0, Op0 should come second to
2412 // expose more CSE opportunities.
2413 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002414 for (const User *U : Op0->users()) {
2415 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002416 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2417 continue;
2418 // If Op0 is the first argument, this is not beneficial to swap the
2419 // arguments.
2420 int LocalSwapBenefits = -1;
2421 unsigned Op1Idx = 1;
2422 if (BinOp->getOperand(Op1Idx) == Op0) {
2423 Op1Idx = 0;
2424 LocalSwapBenefits = 1;
2425 }
2426 if (BinOp->getOperand(Op1Idx) != Op1)
2427 continue;
2428 GlobalSwapBenefits += LocalSwapBenefits;
2429 }
2430 return GlobalSwapBenefits > 0;
2431}
2432
Gerolf Hoflehnerc0b4c202014-10-07 00:16:12 +00002433/// \brief Check that one use is in the same block as the definition and all
2434/// other uses are in blocks dominated by a given block
2435///
2436/// \param DI Definition
2437/// \param UI Use
2438/// \param DB Block that must dominate all uses of \p DI outside
2439/// the parent block
2440/// \return true when \p UI is the only use of \p DI in the parent block
2441/// and all other uses of \p DI are in blocks dominated by \p DB.
2442///
2443bool InstCombiner::dominatesAllUses(const Instruction *DI,
2444 const Instruction *UI,
2445 const BasicBlock *DB) const {
2446 assert(DI && UI && "Instruction not defined\n");
2447 if (DI->getParent() != UI->getParent())
2448 return false;
2449 // DominatorTree available?
2450 if (!DT)
2451 return false;
2452 for (const User *U : DI->users()) {
2453 auto *Usr = cast<Instruction>(U);
2454 if (Usr != UI && !DT->dominates(DB, Usr->getParent()))
2455 return false;
2456 }
2457 return true;
2458}
2459
2460///
2461/// true when the instruction sequence within a block is select-cmp-br.
2462///
2463static bool isChainSelectCmpBranch(const SelectInst *SI) {
2464 const BasicBlock *BB = SI->getParent();
2465 if (!BB)
2466 return false;
2467 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
2468 if (!BI || BI->getNumSuccessors() != 2)
2469 return false;
2470 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
2471 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
2472 return false;
2473 return true;
2474}
2475
2476///
2477/// \brief True when a select result is replaced by one of its operands
2478/// in select-icmp sequence. This will eventually result in the elimination
2479/// of the select.
2480///
2481/// \param SI Select instruction
2482/// \param Icmp Compare instruction
2483/// \param CI1 'true' when first select operand is equal to RHSC of Icmp
2484/// \param CI2 'true' when second select operand is equal to RHSC of Icmp
2485///
2486/// Notes:
2487/// - The replacement is global and requires dominator information
2488/// - The caller is responsible for the actual replacement
2489///
2490/// Example:
2491///
2492/// entry:
2493/// %4 = select i1 %3, %C* %0, %C* null
2494/// %5 = icmp eq %C* %4, null
2495/// br i1 %5, label %9, label %7
2496/// ...
2497/// ; <label>:7 ; preds = %entry
2498/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
2499/// ...
2500///
2501/// can be transformed to
2502///
2503/// %5 = icmp eq %C* %0, null
2504/// %6 = select i1 %3, i1 %5, i1 true
2505/// br i1 %6, label %9, label %7
2506/// ...
2507/// ; <label>:7 ; preds = %entry
2508/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
2509///
2510/// Similar when the first operand of the select is a constant or/and
2511/// the compare is for not equal rather than equal.
2512///
2513/// FIXME: Currently the function considers equal compares only. It should be
2514/// possbile to extend it to not equal compares also.
2515///
2516bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
2517 const ICmpInst *Icmp,
2518 const ConstantInt *CI1,
2519 const ConstantInt *CI2) {
2520 if (isChainSelectCmpBranch(SI) && Icmp->isEquality()) {
2521 // Code sequence is select - icmp.[eq|ne] - br
2522 unsigned ReplaceWithOpd = 0;
2523 if (CI1 && !CI1->isZero())
2524 // The first constant operand of the select and the RHS of
2525 // the compare match, so try to substitute
2526 // the select results with its second operand
2527 // Example:
2528 // %4 = select i1 %3, %C* null, %C* %0
2529 // %5 = icmp eq %C* %4, null
2530 // ==> could replace select with second operand
2531 ReplaceWithOpd = 2;
2532 else if (CI2 && !CI2->isZero())
2533 // Similar when the second operand of the select is a constant
2534 // Example:
2535 // %4 = select i1 %3, %C* %0, %C* null
2536 // %5 = icmp eq %C* %4, null
2537 // ==> could replace select with first operand
2538 ReplaceWithOpd = 1;
2539 if (ReplaceWithOpd) {
2540 // Replace select with operand on else path for EQ compares.
2541 // Replace select with operand on then path for NE compares.
2542 BasicBlock *Succ =
2543 Icmp->getPredicate() == ICmpInst::ICMP_EQ
2544 ? SI->getParent()->getTerminator()->getSuccessor(1)
2545 : SI->getParent()->getTerminator()->getSuccessor(0);
2546 if (InstCombiner::dominatesAllUses(SI, Icmp, Succ)) {
2547 SI->replaceAllUsesWith(SI->getOperand(ReplaceWithOpd));
2548 return true;
2549 }
2550 }
2551 }
2552 return false;
2553}
2554
Chris Lattner2188e402010-01-04 07:37:31 +00002555Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
2556 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00002557 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002558 unsigned Op0Cplxity = getComplexity(Op0);
2559 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002560
Chris Lattner2188e402010-01-04 07:37:31 +00002561 /// Orders the operands of the compare so that they are listed from most
2562 /// complex to least complex. This puts constants before unary operators,
2563 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002564 if (Op0Cplxity < Op1Cplxity ||
2565 (Op0Cplxity == Op1Cplxity &&
2566 swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002567 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00002568 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00002569 Changed = true;
2570 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002571
Hal Finkel60db0582014-09-07 18:57:58 +00002572 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AT))
Chris Lattner2188e402010-01-04 07:37:31 +00002573 return ReplaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002574
Pete Cooperbc5c5242011-12-01 03:58:40 +00002575 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00002576 // ie, abs(val) != 0 -> val != 0
Pete Cooperbc5c5242011-12-01 03:58:40 +00002577 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
2578 {
Pete Cooperfdddc272011-12-01 19:13:26 +00002579 Value *Cond, *SelectTrue, *SelectFalse;
2580 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00002581 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00002582 if (Value *V = dyn_castNegVal(SelectTrue)) {
2583 if (V == SelectFalse)
2584 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2585 }
2586 else if (Value *V = dyn_castNegVal(SelectFalse)) {
2587 if (V == SelectTrue)
2588 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00002589 }
2590 }
2591 }
2592
Chris Lattner229907c2011-07-18 04:54:35 +00002593 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002594
2595 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sands9dff9be2010-02-15 16:12:20 +00002596 if (Ty->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00002597 switch (I.getPredicate()) {
2598 default: llvm_unreachable("Invalid icmp instruction!");
2599 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
2600 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
2601 return BinaryOperator::CreateNot(Xor);
2602 }
2603 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
2604 return BinaryOperator::CreateXor(Op0, Op1);
2605
2606 case ICmpInst::ICMP_UGT:
2607 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
2608 // FALL THROUGH
2609 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
2610 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2611 return BinaryOperator::CreateAnd(Not, Op1);
2612 }
2613 case ICmpInst::ICMP_SGT:
2614 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
2615 // FALL THROUGH
2616 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
2617 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2618 return BinaryOperator::CreateAnd(Not, Op0);
2619 }
2620 case ICmpInst::ICMP_UGE:
2621 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
2622 // FALL THROUGH
2623 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
2624 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2625 return BinaryOperator::CreateOr(Not, Op1);
2626 }
2627 case ICmpInst::ICMP_SGE:
2628 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
2629 // FALL THROUGH
2630 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
2631 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2632 return BinaryOperator::CreateOr(Not, Op0);
2633 }
2634 }
2635 }
2636
2637 unsigned BitWidth = 0;
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002638 if (Ty->isIntOrIntVectorTy())
Chris Lattner2188e402010-01-04 07:37:31 +00002639 BitWidth = Ty->getScalarSizeInBits();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002640 else if (DL) // Pointers require DL info to get their size.
2641 BitWidth = DL->getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002642
Chris Lattner2188e402010-01-04 07:37:31 +00002643 bool isSignBit = false;
2644
2645 // See if we are doing a comparison with a constant.
2646 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002647 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002648
Owen Anderson1294ea72010-12-17 18:08:00 +00002649 // Match the following pattern, which is a common idiom when writing
2650 // overflow-safe integer arithmetic function. The source performs an
2651 // addition in wider type, and explicitly checks for overflow using
2652 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
2653 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00002654 //
2655 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00002656 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00002657 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00002658 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00002659 // sum = a + b
2660 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00002661 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00002662 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00002663 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00002664 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00002665 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00002666 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00002667 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002668
Chris Lattner2188e402010-01-04 07:37:31 +00002669 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2670 if (I.isEquality() && CI->isZero() &&
2671 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
2672 // (icmp cond A B) if cond is equality
2673 return new ICmpInst(I.getPredicate(), A, B);
2674 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002675
Chris Lattner2188e402010-01-04 07:37:31 +00002676 // If we have an icmp le or icmp ge instruction, turn it into the
2677 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
2678 // them being folded in the code below. The SimplifyICmpInst code has
2679 // already handled the edge cases for us, so we just assert on them.
2680 switch (I.getPredicate()) {
2681 default: break;
2682 case ICmpInst::ICMP_ULE:
2683 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
2684 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002685 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002686 case ICmpInst::ICMP_SLE:
2687 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
2688 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002689 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002690 case ICmpInst::ICMP_UGE:
Nick Lewycky6b4454192011-02-28 06:20:05 +00002691 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner2188e402010-01-04 07:37:31 +00002692 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002693 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002694 case ICmpInst::ICMP_SGE:
Nick Lewycky6b4454192011-02-28 06:20:05 +00002695 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner2188e402010-01-04 07:37:31 +00002696 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002697 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002698 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002699
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00002700 // (icmp eq/ne (ashr/lshr const2, A), const1)
2701 if (I.isEquality()) {
2702 ConstantInt *CI2;
2703 if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
2704 match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
2705 return FoldICmpCstShrCst(I, Op0, A, CI, CI2);
2706 }
2707 }
2708
Chris Lattner2188e402010-01-04 07:37:31 +00002709 // If this comparison is a normal comparison, it demands all
2710 // bits, if it is a sign bit comparison, it only demands the sign bit.
2711 bool UnusedBit;
2712 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2713 }
2714
2715 // See if we can fold the comparison based on range information we can get
2716 // by checking whether bits are known to be zero or one in the input.
2717 if (BitWidth != 0) {
2718 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2719 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2720
2721 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersond490c2d2011-01-11 00:36:45 +00002722 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner2188e402010-01-04 07:37:31 +00002723 Op0KnownZero, Op0KnownOne, 0))
2724 return &I;
2725 if (SimplifyDemandedBits(I.getOperandUse(1),
2726 APInt::getAllOnesValue(BitWidth),
2727 Op1KnownZero, Op1KnownOne, 0))
2728 return &I;
2729
2730 // Given the known and unknown bits, compute a range that the LHS could be
2731 // in. Compute the Min, Max and RHS values based on the known bits. For the
2732 // EQ and NE we use unsigned values.
2733 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2734 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2735 if (I.isSigned()) {
2736 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2737 Op0Min, Op0Max);
2738 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2739 Op1Min, Op1Max);
2740 } else {
2741 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2742 Op0Min, Op0Max);
2743 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2744 Op1Min, Op1Max);
2745 }
2746
2747 // If Min and Max are known to be the same, then SimplifyDemandedBits
2748 // figured out that the LHS is a constant. Just constant fold this now so
2749 // that code below can assume that Min != Max.
2750 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2751 return new ICmpInst(I.getPredicate(),
Nick Lewycky92db8e82011-03-06 03:36:19 +00002752 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00002753 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2754 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewycky92db8e82011-03-06 03:36:19 +00002755 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner2188e402010-01-04 07:37:31 +00002756
2757 // Based on the range information we know about the LHS, see if we can
Nick Lewycky6b4454192011-02-28 06:20:05 +00002758 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner2188e402010-01-04 07:37:31 +00002759 switch (I.getPredicate()) {
2760 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattnerf7e89612010-11-21 06:44:42 +00002761 case ICmpInst::ICMP_EQ: {
Chris Lattner2188e402010-01-04 07:37:31 +00002762 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewycky92db8e82011-03-06 03:36:19 +00002763 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002764
Chris Lattnerf7e89612010-11-21 06:44:42 +00002765 // If all bits are known zero except for one, then we know at most one
2766 // bit is set. If the comparison is against zero, then this is a check
2767 // to see if *that* bit is set.
2768 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002769 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00002770 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00002771 Value *LHS = nullptr;
2772 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002773 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2774 LHSC->getValue() != Op0KnownZeroInverted)
2775 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002776
Chris Lattnerf7e89612010-11-21 06:44:42 +00002777 // 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 +00002778 // then turn "((1 << x)&8) == 0" into "x != 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002779 // or turn "((1 << x)&7) == 0" into "x > 2".
Craig Topperf40110f2014-04-25 05:29:35 +00002780 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002781 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002782 APInt ValToCheck = Op0KnownZeroInverted;
2783 if (ValToCheck.isPowerOf2()) {
2784 unsigned CmpVal = ValToCheck.countTrailingZeros();
2785 return new ICmpInst(ICmpInst::ICMP_NE, X,
2786 ConstantInt::get(X->getType(), CmpVal));
2787 } else if ((++ValToCheck).isPowerOf2()) {
2788 unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
2789 return new ICmpInst(ICmpInst::ICMP_UGT, X,
2790 ConstantInt::get(X->getType(), CmpVal));
2791 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00002792 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002793
Chris Lattnerf7e89612010-11-21 06:44:42 +00002794 // 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 +00002795 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattner98457102011-02-10 05:23:05 +00002796 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002797 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00002798 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00002799 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner98457102011-02-10 05:23:05 +00002800 ConstantInt::get(X->getType(),
2801 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00002802 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002803
Chris Lattner2188e402010-01-04 07:37:31 +00002804 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002805 }
2806 case ICmpInst::ICMP_NE: {
Chris Lattner2188e402010-01-04 07:37:31 +00002807 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewycky92db8e82011-03-06 03:36:19 +00002808 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002809
Chris Lattnerf7e89612010-11-21 06:44:42 +00002810 // If all bits are known zero except for one, then we know at most one
2811 // bit is set. If the comparison is against zero, then this is a check
2812 // to see if *that* bit is set.
2813 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002814 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00002815 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00002816 Value *LHS = nullptr;
2817 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002818 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2819 LHSC->getValue() != Op0KnownZeroInverted)
2820 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002821
Chris Lattnerf7e89612010-11-21 06:44:42 +00002822 // 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 +00002823 // then turn "((1 << x)&8) != 0" into "x == 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002824 // or turn "((1 << x)&7) != 0" into "x < 3".
Craig Topperf40110f2014-04-25 05:29:35 +00002825 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002826 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002827 APInt ValToCheck = Op0KnownZeroInverted;
2828 if (ValToCheck.isPowerOf2()) {
2829 unsigned CmpVal = ValToCheck.countTrailingZeros();
2830 return new ICmpInst(ICmpInst::ICMP_EQ, X,
2831 ConstantInt::get(X->getType(), CmpVal));
2832 } else if ((++ValToCheck).isPowerOf2()) {
2833 unsigned CmpVal = ValToCheck.countTrailingZeros();
2834 return new ICmpInst(ICmpInst::ICMP_ULT, X,
2835 ConstantInt::get(X->getType(), CmpVal));
2836 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00002837 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002838
Chris Lattnerf7e89612010-11-21 06:44:42 +00002839 // 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 +00002840 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattner98457102011-02-10 05:23:05 +00002841 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002842 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00002843 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00002844 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner98457102011-02-10 05:23:05 +00002845 ConstantInt::get(X->getType(),
2846 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00002847 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002848
Chris Lattner2188e402010-01-04 07:37:31 +00002849 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002850 }
Chris Lattner2188e402010-01-04 07:37:31 +00002851 case ICmpInst::ICMP_ULT:
2852 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002853 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002854 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002855 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002856 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2857 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2858 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2859 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2860 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002861 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002862
2863 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2864 if (CI->isMinValue(true))
2865 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2866 Constant::getAllOnesValue(Op0->getType()));
2867 }
2868 break;
2869 case ICmpInst::ICMP_UGT:
2870 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002871 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002872 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002873 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002874
2875 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2876 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2877 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2878 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2879 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002880 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002881
2882 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2883 if (CI->isMaxValue(true))
2884 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2885 Constant::getNullValue(Op0->getType()));
2886 }
2887 break;
2888 case ICmpInst::ICMP_SLT:
2889 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002890 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002891 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002892 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002893 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2894 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2895 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2896 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2897 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002898 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002899 }
2900 break;
2901 case ICmpInst::ICMP_SGT:
2902 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002903 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002904 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002905 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002906
2907 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2908 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2909 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2910 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2911 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002912 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002913 }
2914 break;
2915 case ICmpInst::ICMP_SGE:
2916 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2917 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002918 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002919 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002920 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002921 break;
2922 case ICmpInst::ICMP_SLE:
2923 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2924 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002925 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002926 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002927 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002928 break;
2929 case ICmpInst::ICMP_UGE:
2930 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2931 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002932 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002933 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002934 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002935 break;
2936 case ICmpInst::ICMP_ULE:
2937 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2938 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002939 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002940 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002941 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002942 break;
2943 }
2944
2945 // Turn a signed comparison into an unsigned one if both operands
2946 // are known to have the same sign.
2947 if (I.isSigned() &&
2948 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2949 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2950 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2951 }
2952
2953 // Test if the ICmpInst instruction is used exclusively by a select as
2954 // part of a minimum or maximum operation. If so, refrain from doing
2955 // any other folding. This helps out other analyses which understand
2956 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2957 // and CodeGen. And in this case, at least one of the comparison
2958 // operands has at least one user besides the compare (the select),
2959 // which would often largely negate the benefit of folding anyway.
2960 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00002961 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00002962 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2963 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00002964 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002965
2966 // See if we are doing a comparison between a constant and an instruction that
2967 // can be folded into the comparison.
2968 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002969 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2970 // instruction, see if that instruction also has constants so that the
2971 // instruction can be folded into the icmp
Chris Lattner2188e402010-01-04 07:37:31 +00002972 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2973 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2974 return Res;
2975 }
2976
2977 // Handle icmp with constant (but not simple integer constant) RHS
2978 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2979 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2980 switch (LHSI->getOpcode()) {
2981 case Instruction::GetElementPtr:
2982 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2983 if (RHSC->isNullValue() &&
2984 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2985 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2986 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2987 break;
2988 case Instruction::PHI:
2989 // Only fold icmp into the PHI if the phi and icmp are in the same
2990 // block. If in the same block, we're encouraging jump threading. If
2991 // not, we are just pessimizing the code by making an i1 phi.
2992 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00002993 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00002994 return NV;
2995 break;
2996 case Instruction::Select: {
2997 // If either operand of the select is a constant, we can fold the
2998 // comparison into the select arms, which will cause one to be
2999 // constant folded and the select turned into a bitwise or.
Craig Topperf40110f2014-04-25 05:29:35 +00003000 Value *Op1 = nullptr, *Op2 = nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003001 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
3002 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
3003 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
3004 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
3005
3006 // We only want to perform this transformation if it will not lead to
3007 // additional code. This is true if either both sides of the select
3008 // fold to a constant (in which case the icmp is replaced with a select
3009 // which will usually simplify) or this is the only user of the
3010 // select (in which case we are trading a select+icmp for a simpler
Gerolf Hoflehnerc0b4c202014-10-07 00:16:12 +00003011 // select+icmp) or all uses of the select can be replaced based on
3012 // dominance information ("Global cases").
3013 bool Transform = false;
3014 if (Op1 && Op2)
3015 Transform = true;
3016 else if (Op1 || Op2) {
3017 if (LHSI->hasOneUse())
3018 Transform = true;
3019 else
3020 // Global cases
3021 Transform = replacedSelectWithOperand(
3022 cast<SelectInst>(LHSI), &I, dyn_cast_or_null<ConstantInt>(Op1),
3023 dyn_cast_or_null<ConstantInt>(Op2));
3024 }
3025 if (Transform) {
Chris Lattner2188e402010-01-04 07:37:31 +00003026 if (!Op1)
3027 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3028 RHSC, I.getName());
3029 if (!Op2)
3030 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3031 RHSC, I.getName());
3032 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3033 }
3034 break;
3035 }
Chris Lattner2188e402010-01-04 07:37:31 +00003036 case Instruction::IntToPtr:
3037 // icmp pred inttoptr(X), null -> icmp pred X, 0
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003038 if (RHSC->isNullValue() && DL &&
3039 DL->getIntPtrType(RHSC->getType()) ==
Chris Lattner2188e402010-01-04 07:37:31 +00003040 LHSI->getOperand(0)->getType())
3041 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3042 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3043 break;
3044
3045 case Instruction::Load:
3046 // Try to optimize things like "A[i] > 4" to index computations.
3047 if (GetElementPtrInst *GEP =
3048 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3049 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3050 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3051 !cast<LoadInst>(LHSI)->isVolatile())
3052 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3053 return Res;
3054 }
3055 break;
3056 }
3057 }
3058
3059 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3060 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
3061 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
3062 return NI;
3063 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
3064 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
3065 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3066 return NI;
3067
3068 // Test to see if the operands of the icmp are casted versions of other
3069 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3070 // now.
3071 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003072 if (Op0->getType()->isPointerTy() &&
3073 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003074 // We keep moving the cast from the left operand over to the right
3075 // operand, where it can often be eliminated completely.
3076 Op0 = CI->getOperand(0);
3077
3078 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3079 // so eliminate it as well.
3080 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3081 Op1 = CI2->getOperand(0);
3082
3083 // If Op1 is a constant, we can fold the cast into the constant.
3084 if (Op0->getType() != Op1->getType()) {
3085 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3086 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3087 } else {
3088 // Otherwise, cast the RHS right before the icmp
3089 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3090 }
3091 }
3092 return new ICmpInst(I.getPredicate(), Op0, Op1);
3093 }
3094 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003095
Chris Lattner2188e402010-01-04 07:37:31 +00003096 if (isa<CastInst>(Op0)) {
3097 // Handle the special case of: icmp (cast bool to X), <cst>
3098 // This comes up when you have code like
3099 // int X = A < B;
3100 // if (X) ...
3101 // For generality, we handle any zero-extension of any operand comparison
3102 // with a constant or another cast from the same type.
3103 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
3104 if (Instruction *R = visitICmpInstWithCastAndCast(I))
3105 return R;
3106 }
Chris Lattner2188e402010-01-04 07:37:31 +00003107
Duncan Sandse5220012011-02-17 07:46:37 +00003108 // Special logic for binary operators.
3109 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3110 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3111 if (BO0 || BO1) {
3112 CmpInst::Predicate Pred = I.getPredicate();
3113 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3114 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3115 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3116 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3117 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3118 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3119 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3120 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3121 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3122
3123 // Analyze the case when either Op0 or Op1 is an add instruction.
3124 // 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 +00003125 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Duncan Sandse5220012011-02-17 07:46:37 +00003126 if (BO0 && BO0->getOpcode() == Instruction::Add)
3127 A = BO0->getOperand(0), B = BO0->getOperand(1);
3128 if (BO1 && BO1->getOpcode() == Instruction::Add)
3129 C = BO1->getOperand(0), D = BO1->getOperand(1);
3130
3131 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3132 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3133 return new ICmpInst(Pred, A == Op1 ? B : A,
3134 Constant::getNullValue(Op1->getType()));
3135
3136 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3137 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3138 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3139 C == Op0 ? D : C);
3140
Duncan Sands84653b32011-02-18 16:25:37 +00003141 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003142 if (A && C && (A == C || A == D || B == C || B == D) &&
3143 NoOp0WrapProblem && NoOp1WrapProblem &&
3144 // Try not to increase register pressure.
3145 BO0->hasOneUse() && BO1->hasOneUse()) {
3146 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003147 Value *Y, *Z;
3148 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003149 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003150 Y = B;
3151 Z = D;
3152 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003153 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003154 Y = B;
3155 Z = C;
3156 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003157 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003158 Y = A;
3159 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003160 } else {
3161 assert(B == D);
3162 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003163 Y = A;
3164 Z = C;
3165 }
Duncan Sandse5220012011-02-17 07:46:37 +00003166 return new ICmpInst(Pred, Y, Z);
3167 }
3168
David Majnemerb81cd632013-04-11 20:05:46 +00003169 // icmp slt (X + -1), Y -> icmp sle X, Y
3170 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3171 match(B, m_AllOnes()))
3172 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3173
3174 // icmp sge (X + -1), Y -> icmp sgt X, Y
3175 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3176 match(B, m_AllOnes()))
3177 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3178
3179 // icmp sle (X + 1), Y -> icmp slt X, Y
3180 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3181 match(B, m_One()))
3182 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3183
3184 // icmp sgt (X + 1), Y -> icmp sge X, Y
3185 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3186 match(B, m_One()))
3187 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3188
3189 // if C1 has greater magnitude than C2:
3190 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3191 // s.t. C3 = C1 - C2
3192 //
3193 // if C2 has greater magnitude than C1:
3194 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3195 // s.t. C3 = C2 - C1
3196 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3197 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3198 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3199 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3200 const APInt &AP1 = C1->getValue();
3201 const APInt &AP2 = C2->getValue();
3202 if (AP1.isNegative() == AP2.isNegative()) {
3203 APInt AP1Abs = C1->getValue().abs();
3204 APInt AP2Abs = C2->getValue().abs();
3205 if (AP1Abs.uge(AP2Abs)) {
3206 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
3207 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
3208 return new ICmpInst(Pred, NewAdd, C);
3209 } else {
3210 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
3211 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
3212 return new ICmpInst(Pred, A, NewAdd);
3213 }
3214 }
3215 }
3216
3217
Duncan Sandse5220012011-02-17 07:46:37 +00003218 // Analyze the case when either Op0 or Op1 is a sub instruction.
3219 // 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 +00003220 A = nullptr; B = nullptr; C = nullptr; D = nullptr;
Duncan Sandse5220012011-02-17 07:46:37 +00003221 if (BO0 && BO0->getOpcode() == Instruction::Sub)
3222 A = BO0->getOperand(0), B = BO0->getOperand(1);
3223 if (BO1 && BO1->getOpcode() == Instruction::Sub)
3224 C = BO1->getOperand(0), D = BO1->getOperand(1);
3225
Duncan Sands84653b32011-02-18 16:25:37 +00003226 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3227 if (A == Op1 && NoOp0WrapProblem)
3228 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3229
3230 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
3231 if (C == Op0 && NoOp1WrapProblem)
3232 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3233
3234 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003235 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
3236 // Try not to increase register pressure.
3237 BO0->hasOneUse() && BO1->hasOneUse())
3238 return new ICmpInst(Pred, A, C);
3239
Duncan Sands84653b32011-02-18 16:25:37 +00003240 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
3241 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3242 // Try not to increase register pressure.
3243 BO0->hasOneUse() && BO1->hasOneUse())
3244 return new ICmpInst(Pred, D, B);
3245
David Majnemer186c9422014-05-15 00:02:20 +00003246 // icmp (0-X) < cst --> x > -cst
3247 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3248 Value *X;
3249 if (match(BO0, m_Neg(m_Value(X))))
3250 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
3251 if (!RHSC->isMinValue(/*isSigned=*/true))
3252 return new ICmpInst(I.getSwappedPredicate(), X,
3253 ConstantExpr::getNeg(RHSC));
3254 }
3255
Craig Topperf40110f2014-04-25 05:29:35 +00003256 BinaryOperator *SRem = nullptr;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003257 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00003258 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
3259 Op1 == BO0->getOperand(1))
3260 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003261 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00003262 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3263 Op0 == BO1->getOperand(1))
3264 SRem = BO1;
3265 if (SRem) {
3266 // We don't check hasOneUse to avoid increasing register pressure because
3267 // the value we use is the same value this instruction was already using.
3268 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
3269 default: break;
3270 case ICmpInst::ICMP_EQ:
Nick Lewycky92db8e82011-03-06 03:36:19 +00003271 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003272 case ICmpInst::ICMP_NE:
Nick Lewycky92db8e82011-03-06 03:36:19 +00003273 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003274 case ICmpInst::ICMP_SGT:
3275 case ICmpInst::ICMP_SGE:
3276 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
3277 Constant::getAllOnesValue(SRem->getType()));
3278 case ICmpInst::ICMP_SLT:
3279 case ICmpInst::ICMP_SLE:
3280 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
3281 Constant::getNullValue(SRem->getType()));
3282 }
3283 }
3284
Duncan Sandse5220012011-02-17 07:46:37 +00003285 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
3286 BO0->hasOneUse() && BO1->hasOneUse() &&
3287 BO0->getOperand(1) == BO1->getOperand(1)) {
3288 switch (BO0->getOpcode()) {
3289 default: break;
3290 case Instruction::Add:
3291 case Instruction::Sub:
3292 case Instruction::Xor:
3293 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
3294 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3295 BO1->getOperand(0));
3296 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
3297 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3298 if (CI->getValue().isSignBit()) {
3299 ICmpInst::Predicate Pred = I.isSigned()
3300 ? I.getUnsignedPredicate()
3301 : I.getSignedPredicate();
3302 return new ICmpInst(Pred, BO0->getOperand(0),
3303 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00003304 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003305
Chris Lattnerb1a15122011-07-15 06:08:15 +00003306 if (CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00003307 ICmpInst::Predicate Pred = I.isSigned()
3308 ? I.getUnsignedPredicate()
3309 : I.getSignedPredicate();
3310 Pred = I.getSwappedPredicate(Pred);
3311 return new ICmpInst(Pred, BO0->getOperand(0),
3312 BO1->getOperand(0));
3313 }
Chris Lattner2188e402010-01-04 07:37:31 +00003314 }
Duncan Sandse5220012011-02-17 07:46:37 +00003315 break;
3316 case Instruction::Mul:
3317 if (!I.isEquality())
3318 break;
3319
3320 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3321 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
3322 // Mask = -1 >> count-trailing-zeros(Cst).
3323 if (!CI->isZero() && !CI->isOne()) {
3324 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003325 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00003326 APInt::getLowBitsSet(AP.getBitWidth(),
3327 AP.getBitWidth() -
3328 AP.countTrailingZeros()));
3329 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
3330 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
3331 return new ICmpInst(I.getPredicate(), And1, And2);
3332 }
3333 }
3334 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00003335 case Instruction::UDiv:
3336 case Instruction::LShr:
3337 if (I.isSigned())
3338 break;
3339 // fall-through
3340 case Instruction::SDiv:
3341 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00003342 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00003343 break;
3344 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3345 BO1->getOperand(0));
3346 case Instruction::Shl: {
3347 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
3348 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
3349 if (!NUW && !NSW)
3350 break;
3351 if (!NSW && I.isSigned())
3352 break;
3353 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3354 BO1->getOperand(0));
3355 }
Chris Lattner2188e402010-01-04 07:37:31 +00003356 }
3357 }
3358 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003359
Chris Lattner2188e402010-01-04 07:37:31 +00003360 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00003361 // Transform (A & ~B) == 0 --> (A & B) != 0
3362 // and (A & ~B) != 0 --> (A & B) == 0
3363 // if A is a power of 2.
3364 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00003365 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A, false,
3366 0, AT, &I, DT) &&
3367 I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00003368 return new ICmpInst(I.getInversePredicate(),
3369 Builder->CreateAnd(A, B),
3370 Op1);
3371
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00003372 // ~x < ~y --> y < x
3373 // ~x < cst --> ~cst < x
3374 if (match(Op0, m_Not(m_Value(A)))) {
3375 if (match(Op1, m_Not(m_Value(B))))
3376 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00003377 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00003378 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
3379 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003380
3381 // (a+b) <u a --> llvm.uadd.with.overflow.
3382 // (a+b) <u b --> llvm.uadd.with.overflow.
3383 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
Jim Grosbach129c52a2011-09-30 18:09:53 +00003384 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003385 (Op1 == A || Op1 == B))
3386 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
3387 return R;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003388
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003389 // a >u (a+b) --> llvm.uadd.with.overflow.
3390 // b >u (a+b) --> llvm.uadd.with.overflow.
3391 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
3392 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
3393 (Op0 == A || Op0 == B))
3394 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
3395 return R;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003396
3397 // (zext a) * (zext b) --> llvm.umul.with.overflow.
3398 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
3399 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
3400 return R;
3401 }
3402 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
3403 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
3404 return R;
3405 }
Chris Lattner2188e402010-01-04 07:37:31 +00003406 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003407
Chris Lattner2188e402010-01-04 07:37:31 +00003408 if (I.isEquality()) {
3409 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00003410
Chris Lattner2188e402010-01-04 07:37:31 +00003411 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3412 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
3413 Value *OtherVal = A == Op1 ? B : A;
3414 return new ICmpInst(I.getPredicate(), OtherVal,
3415 Constant::getNullValue(A->getType()));
3416 }
3417
3418 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
3419 // A^c1 == C^c2 --> A == C^(c1^c2)
3420 ConstantInt *C1, *C2;
3421 if (match(B, m_ConstantInt(C1)) &&
3422 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00003423 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003424 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00003425 return new ICmpInst(I.getPredicate(), A, Xor);
3426 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003427
Chris Lattner2188e402010-01-04 07:37:31 +00003428 // A^B == A^D -> B == D
3429 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
3430 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
3431 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
3432 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
3433 }
3434 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003435
Chris Lattner2188e402010-01-04 07:37:31 +00003436 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
3437 (A == Op0 || B == Op0)) {
3438 // A == (A^B) -> B == 0
3439 Value *OtherVal = A == Op0 ? B : A;
3440 return new ICmpInst(I.getPredicate(), OtherVal,
3441 Constant::getNullValue(A->getType()));
3442 }
3443
Chris Lattner2188e402010-01-04 07:37:31 +00003444 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00003445 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00003446 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Craig Topperf40110f2014-04-25 05:29:35 +00003447 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003448
Chris Lattner2188e402010-01-04 07:37:31 +00003449 if (A == C) {
3450 X = B; Y = D; Z = A;
3451 } else if (A == D) {
3452 X = B; Y = C; Z = A;
3453 } else if (B == C) {
3454 X = A; Y = D; Z = B;
3455 } else if (B == D) {
3456 X = A; Y = C; Z = B;
3457 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003458
Chris Lattner2188e402010-01-04 07:37:31 +00003459 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003460 Op1 = Builder->CreateXor(X, Y);
3461 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00003462 I.setOperand(0, Op1);
3463 I.setOperand(1, Constant::getNullValue(Op1->getType()));
3464 return &I;
3465 }
3466 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003467
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00003468 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00003469 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00003470 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00003471 if ((Op0->hasOneUse() &&
3472 match(Op0, m_ZExt(m_Value(A))) &&
3473 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
3474 (Op1->hasOneUse() &&
3475 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
3476 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00003477 APInt Pow2 = Cst1->getValue() + 1;
3478 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
3479 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
3480 return new ICmpInst(I.getPredicate(), A,
3481 Builder->CreateTrunc(B, A->getType()));
3482 }
3483
Benjamin Kramer03f3e242013-11-16 16:00:48 +00003484 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
3485 // For lshr and ashr pairs.
3486 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3487 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
3488 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3489 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
3490 unsigned TypeBits = Cst1->getBitWidth();
3491 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3492 if (ShAmt < TypeBits && ShAmt != 0) {
3493 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
3494 ? ICmpInst::ICMP_UGE
3495 : ICmpInst::ICMP_ULT;
3496 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
3497 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
3498 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
3499 }
3500 }
3501
Chris Lattner1b06c712011-04-26 20:18:20 +00003502 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
3503 // "icmp (and X, mask), cst"
3504 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00003505 if (Op0->hasOneUse() &&
3506 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
3507 m_ConstantInt(ShAmt))))) &&
3508 match(Op1, m_ConstantInt(Cst1)) &&
3509 // Only do this when A has multiple uses. This is most important to do
3510 // when it exposes other optimizations.
3511 !A->hasOneUse()) {
3512 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003513
Chris Lattner1b06c712011-04-26 20:18:20 +00003514 if (ShAmt < ASize) {
3515 APInt MaskV =
3516 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
3517 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003518
Chris Lattner1b06c712011-04-26 20:18:20 +00003519 APInt CmpV = Cst1->getValue().zext(ASize);
3520 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003521
Chris Lattner1b06c712011-04-26 20:18:20 +00003522 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
3523 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
3524 }
3525 }
Chris Lattner2188e402010-01-04 07:37:31 +00003526 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003527
Chris Lattner2188e402010-01-04 07:37:31 +00003528 {
3529 Value *X; ConstantInt *Cst;
3530 // icmp X+Cst, X
3531 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00003532 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00003533
3534 // icmp X, X+Cst
3535 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00003536 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00003537 }
Craig Topperf40110f2014-04-25 05:29:35 +00003538 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003539}
3540
Chris Lattner2188e402010-01-04 07:37:31 +00003541/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
3542///
3543Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
3544 Instruction *LHSI,
3545 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00003546 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003547 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003548
Chris Lattner2188e402010-01-04 07:37:31 +00003549 // Get the width of the mantissa. We don't want to hack on conversions that
3550 // might lose information from the integer, e.g. "i64 -> float"
3551 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00003552 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003553
Chris Lattner2188e402010-01-04 07:37:31 +00003554 // Check to see that the input is converted from an integer type that is small
3555 // enough that preserves all bits. TODO: check here for "known" sign bits.
3556 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
3557 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003558
Chris Lattner2188e402010-01-04 07:37:31 +00003559 // If this is a uitofp instruction, we need an extra bit to hold the sign.
3560 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
3561 if (LHSUnsigned)
3562 ++InputSize;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003563
Chris Lattner2188e402010-01-04 07:37:31 +00003564 // If the conversion would lose info, don't hack on this.
3565 if ((int)InputSize > MantissaWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00003566 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003567
Chris Lattner2188e402010-01-04 07:37:31 +00003568 // Otherwise, we can potentially simplify the comparison. We know that it
3569 // will always come through as an integer value and we know the constant is
3570 // not a NAN (it would have been previously simplified).
3571 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00003572
Chris Lattner2188e402010-01-04 07:37:31 +00003573 ICmpInst::Predicate Pred;
3574 switch (I.getPredicate()) {
3575 default: llvm_unreachable("Unexpected predicate!");
3576 case FCmpInst::FCMP_UEQ:
3577 case FCmpInst::FCMP_OEQ:
3578 Pred = ICmpInst::ICMP_EQ;
3579 break;
3580 case FCmpInst::FCMP_UGT:
3581 case FCmpInst::FCMP_OGT:
3582 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
3583 break;
3584 case FCmpInst::FCMP_UGE:
3585 case FCmpInst::FCMP_OGE:
3586 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
3587 break;
3588 case FCmpInst::FCMP_ULT:
3589 case FCmpInst::FCMP_OLT:
3590 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
3591 break;
3592 case FCmpInst::FCMP_ULE:
3593 case FCmpInst::FCMP_OLE:
3594 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
3595 break;
3596 case FCmpInst::FCMP_UNE:
3597 case FCmpInst::FCMP_ONE:
3598 Pred = ICmpInst::ICMP_NE;
3599 break;
3600 case FCmpInst::FCMP_ORD:
Jakub Staszakbddea112013-06-06 20:18:46 +00003601 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003602 case FCmpInst::FCMP_UNO:
Jakub Staszakbddea112013-06-06 20:18:46 +00003603 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003604 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003605
Chris Lattner229907c2011-07-18 04:54:35 +00003606 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00003607
Chris Lattner2188e402010-01-04 07:37:31 +00003608 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003609
Chris Lattner2188e402010-01-04 07:37:31 +00003610 // See if the FP constant is too large for the integer. For example,
3611 // comparing an i8 to 300.0.
3612 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003613
Chris Lattner2188e402010-01-04 07:37:31 +00003614 if (!LHSUnsigned) {
3615 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
3616 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00003617 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003618 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
3619 APFloat::rmNearestTiesToEven);
3620 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
3621 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
3622 Pred == ICmpInst::ICMP_SLE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003623 return ReplaceInstUsesWith(I, Builder->getTrue());
3624 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003625 }
3626 } else {
3627 // If the RHS value is > UnsignedMax, fold the comparison. This handles
3628 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00003629 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003630 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
3631 APFloat::rmNearestTiesToEven);
3632 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
3633 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
3634 Pred == ICmpInst::ICMP_ULE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003635 return ReplaceInstUsesWith(I, Builder->getTrue());
3636 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003637 }
3638 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003639
Chris Lattner2188e402010-01-04 07:37:31 +00003640 if (!LHSUnsigned) {
3641 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00003642 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003643 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
3644 APFloat::rmNearestTiesToEven);
3645 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
3646 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
3647 Pred == ICmpInst::ICMP_SGE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003648 return ReplaceInstUsesWith(I, Builder->getTrue());
3649 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003650 }
Devang Patel698452b2012-02-13 23:05:18 +00003651 } else {
3652 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00003653 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00003654 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
3655 APFloat::rmNearestTiesToEven);
3656 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
3657 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
3658 Pred == ICmpInst::ICMP_UGE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003659 return ReplaceInstUsesWith(I, Builder->getTrue());
3660 return ReplaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00003661 }
Chris Lattner2188e402010-01-04 07:37:31 +00003662 }
3663
3664 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
3665 // [0, UMAX], but it may still be fractional. See if it is fractional by
3666 // casting the FP value to the integer value and back, checking for equality.
3667 // Don't do this for zero, because -0.0 is not fractional.
3668 Constant *RHSInt = LHSUnsigned
3669 ? ConstantExpr::getFPToUI(RHSC, IntTy)
3670 : ConstantExpr::getFPToSI(RHSC, IntTy);
3671 if (!RHS.isZero()) {
3672 bool Equal = LHSUnsigned
3673 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
3674 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
3675 if (!Equal) {
3676 // If we had a comparison against a fractional value, we have to adjust
3677 // the compare predicate and sometimes the value. RHSC is rounded towards
3678 // zero at this point.
3679 switch (Pred) {
3680 default: llvm_unreachable("Unexpected integer comparison!");
3681 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Jakub Staszakbddea112013-06-06 20:18:46 +00003682 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003683 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Jakub Staszakbddea112013-06-06 20:18:46 +00003684 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003685 case ICmpInst::ICMP_ULE:
3686 // (float)int <= 4.4 --> int <= 4
3687 // (float)int <= -4.4 --> false
3688 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003689 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003690 break;
3691 case ICmpInst::ICMP_SLE:
3692 // (float)int <= 4.4 --> int <= 4
3693 // (float)int <= -4.4 --> int < -4
3694 if (RHS.isNegative())
3695 Pred = ICmpInst::ICMP_SLT;
3696 break;
3697 case ICmpInst::ICMP_ULT:
3698 // (float)int < -4.4 --> false
3699 // (float)int < 4.4 --> int <= 4
3700 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003701 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003702 Pred = ICmpInst::ICMP_ULE;
3703 break;
3704 case ICmpInst::ICMP_SLT:
3705 // (float)int < -4.4 --> int < -4
3706 // (float)int < 4.4 --> int <= 4
3707 if (!RHS.isNegative())
3708 Pred = ICmpInst::ICMP_SLE;
3709 break;
3710 case ICmpInst::ICMP_UGT:
3711 // (float)int > 4.4 --> int > 4
3712 // (float)int > -4.4 --> true
3713 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003714 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003715 break;
3716 case ICmpInst::ICMP_SGT:
3717 // (float)int > 4.4 --> int > 4
3718 // (float)int > -4.4 --> int >= -4
3719 if (RHS.isNegative())
3720 Pred = ICmpInst::ICMP_SGE;
3721 break;
3722 case ICmpInst::ICMP_UGE:
3723 // (float)int >= -4.4 --> true
3724 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00003725 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003726 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003727 Pred = ICmpInst::ICMP_UGT;
3728 break;
3729 case ICmpInst::ICMP_SGE:
3730 // (float)int >= -4.4 --> int >= -4
3731 // (float)int >= 4.4 --> int > 4
3732 if (!RHS.isNegative())
3733 Pred = ICmpInst::ICMP_SGT;
3734 break;
3735 }
3736 }
3737 }
3738
3739 // Lower this FP comparison into an appropriate integer version of the
3740 // comparison.
3741 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
3742}
3743
3744Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
3745 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003746
Chris Lattner2188e402010-01-04 07:37:31 +00003747 /// Orders the operands of the compare so that they are listed from most
3748 /// complex to least complex. This puts constants before unary operators,
3749 /// before binary operators.
3750 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
3751 I.swapOperands();
3752 Changed = true;
3753 }
3754
3755 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003756
Hal Finkel60db0582014-09-07 18:57:58 +00003757 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AT))
Chris Lattner2188e402010-01-04 07:37:31 +00003758 return ReplaceInstUsesWith(I, V);
3759
3760 // Simplify 'fcmp pred X, X'
3761 if (Op0 == Op1) {
3762 switch (I.getPredicate()) {
3763 default: llvm_unreachable("Unknown predicate!");
3764 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
3765 case FCmpInst::FCMP_ULT: // True if unordered or less than
3766 case FCmpInst::FCMP_UGT: // True if unordered or greater than
3767 case FCmpInst::FCMP_UNE: // True if unordered or not equal
3768 // Canonicalize these to be 'fcmp uno %X, 0.0'.
3769 I.setPredicate(FCmpInst::FCMP_UNO);
3770 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3771 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003772
Chris Lattner2188e402010-01-04 07:37:31 +00003773 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
3774 case FCmpInst::FCMP_OEQ: // True if ordered and equal
3775 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
3776 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
3777 // Canonicalize these to be 'fcmp ord %X, 0.0'.
3778 I.setPredicate(FCmpInst::FCMP_ORD);
3779 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3780 return &I;
3781 }
3782 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003783
Chris Lattner2188e402010-01-04 07:37:31 +00003784 // Handle fcmp with constant RHS
3785 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3786 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3787 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003788 case Instruction::FPExt: {
3789 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
3790 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
3791 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
3792 if (!RHSF)
3793 break;
3794
3795 const fltSemantics *Sem;
3796 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00003797 if (LHSExt->getSrcTy()->isHalfTy())
3798 Sem = &APFloat::IEEEhalf;
3799 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003800 Sem = &APFloat::IEEEsingle;
3801 else if (LHSExt->getSrcTy()->isDoubleTy())
3802 Sem = &APFloat::IEEEdouble;
3803 else if (LHSExt->getSrcTy()->isFP128Ty())
3804 Sem = &APFloat::IEEEquad;
3805 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
3806 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00003807 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
3808 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003809 else
3810 break;
3811
3812 bool Lossy;
3813 APFloat F = RHSF->getValueAPF();
3814 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
3815
Jim Grosbach24ff8342011-09-30 18:45:50 +00003816 // Avoid lossy conversions and denormals. Zero is a special case
3817 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00003818 APFloat Fabs = F;
3819 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003820 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00003821 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
3822 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00003823
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003824 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3825 ConstantFP::get(RHSC->getContext(), F));
3826 break;
3827 }
Chris Lattner2188e402010-01-04 07:37:31 +00003828 case Instruction::PHI:
3829 // Only fold fcmp into the PHI if the phi and fcmp are in the same
3830 // block. If in the same block, we're encouraging jump threading. If
3831 // not, we are just pessimizing the code by making an i1 phi.
3832 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003833 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003834 return NV;
3835 break;
3836 case Instruction::SIToFP:
3837 case Instruction::UIToFP:
3838 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
3839 return NV;
3840 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00003841 case Instruction::FSub: {
3842 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3843 Value *Op;
3844 if (match(LHSI, m_FNeg(m_Value(Op))))
3845 return new FCmpInst(I.getSwappedPredicate(), Op,
3846 ConstantExpr::getFNeg(RHSC));
3847 break;
3848 }
Dan Gohman94732022010-02-24 06:46:09 +00003849 case Instruction::Load:
3850 if (GetElementPtrInst *GEP =
3851 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3852 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3853 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3854 !cast<LoadInst>(LHSI)->isVolatile())
3855 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3856 return Res;
3857 }
3858 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00003859 case Instruction::Call: {
3860 CallInst *CI = cast<CallInst>(LHSI);
3861 LibFunc::Func Func;
3862 // Various optimization for fabs compared with zero.
Benjamin Kramer9d032422012-08-18 22:04:34 +00003863 if (RHSC->isNullValue() && CI->getCalledFunction() &&
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00003864 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3865 TLI->has(Func)) {
3866 if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3867 Func == LibFunc::fabsl) {
3868 switch (I.getPredicate()) {
3869 default: break;
3870 // fabs(x) < 0 --> false
3871 case FCmpInst::FCMP_OLT:
3872 return ReplaceInstUsesWith(I, Builder->getFalse());
3873 // fabs(x) > 0 --> x != 0
3874 case FCmpInst::FCMP_OGT:
3875 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3876 RHSC);
3877 // fabs(x) <= 0 --> x == 0
3878 case FCmpInst::FCMP_OLE:
3879 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3880 RHSC);
3881 // fabs(x) >= 0 --> !isnan(x)
3882 case FCmpInst::FCMP_OGE:
3883 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3884 RHSC);
3885 // fabs(x) == 0 --> x == 0
3886 // fabs(x) != 0 --> x != 0
3887 case FCmpInst::FCMP_OEQ:
3888 case FCmpInst::FCMP_UEQ:
3889 case FCmpInst::FCMP_ONE:
3890 case FCmpInst::FCMP_UNE:
3891 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3892 RHSC);
3893 }
3894 }
3895 }
3896 }
Chris Lattner2188e402010-01-04 07:37:31 +00003897 }
Chris Lattner2188e402010-01-04 07:37:31 +00003898 }
3899
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00003900 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00003901 Value *X, *Y;
3902 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00003903 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00003904
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00003905 // fcmp (fpext x), (fpext y) -> fcmp x, y
3906 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3907 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3908 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3909 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3910 RHSExt->getOperand(0));
3911
Craig Topperf40110f2014-04-25 05:29:35 +00003912 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003913}