blob: 80ae406604b34085f0fe79d9410897595f1936dc [file] [log] [blame]
Chris Lattner2188e402010-01-04 07:37:31 +00001//===- InstCombineCompares.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitICmp and visitFCmp functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Matt Arsenault55e73122015-01-06 15:50:59 +000015#include "llvm/ADT/APSInt.h"
Silviu Barangaf29dfd32016-01-15 15:52:05 +000016#include "llvm/ADT/SetVector.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000017#include "llvm/ADT/Statistic.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000018#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2188e402010-01-04 07:37:31 +000019#include "llvm/Analysis/InstructionSimplify.h"
20#include "llvm/Analysis/MemoryBuiltins.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/VectorUtils.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000023#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000025#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000027#include "llvm/IR/PatternMatch.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000028#include "llvm/Support/Debug.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000029
Chris Lattner2188e402010-01-04 07:37:31 +000030using namespace llvm;
31using namespace PatternMatch;
32
Chandler Carruth964daaa2014-04-22 02:55:47 +000033#define DEBUG_TYPE "instcombine"
34
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000035// How many times is a select replaced by one of its operands?
36STATISTIC(NumSel, "Number of select opts");
37
38// Initialization Routines
39
Chris Lattner98457102011-02-10 05:23:05 +000040static ConstantInt *getOne(Constant *C) {
41 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
42}
43
Chris Lattner2188e402010-01-04 07:37:31 +000044static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
45 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
46}
47
48static bool HasAddOverflow(ConstantInt *Result,
49 ConstantInt *In1, ConstantInt *In2,
50 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000051 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000052 return Result->getValue().ult(In1->getValue());
Chris Lattnerb1a15122011-07-15 06:08:15 +000053
54 if (In2->isNegative())
55 return Result->getValue().sgt(In1->getValue());
56 return Result->getValue().slt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000057}
58
59/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
60/// overflowed for this type.
61static bool AddWithOverflow(Constant *&Result, Constant *In1,
62 Constant *In2, bool IsSigned = false) {
63 Result = ConstantExpr::getAdd(In1, In2);
64
Chris Lattner229907c2011-07-18 04:54:35 +000065 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000066 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
67 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
68 if (HasAddOverflow(ExtractElement(Result, Idx),
69 ExtractElement(In1, Idx),
70 ExtractElement(In2, Idx),
71 IsSigned))
72 return true;
73 }
74 return false;
75 }
76
77 return HasAddOverflow(cast<ConstantInt>(Result),
78 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
79 IsSigned);
80}
81
82static bool HasSubOverflow(ConstantInt *Result,
83 ConstantInt *In1, ConstantInt *In2,
84 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000085 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000086 return Result->getValue().ugt(In1->getValue());
Jim Grosbach129c52a2011-09-30 18:09:53 +000087
Chris Lattnerb1a15122011-07-15 06:08:15 +000088 if (In2->isNegative())
89 return Result->getValue().slt(In1->getValue());
90
91 return Result->getValue().sgt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000092}
93
94/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
95/// overflowed for this type.
96static bool SubWithOverflow(Constant *&Result, Constant *In1,
97 Constant *In2, bool IsSigned = false) {
98 Result = ConstantExpr::getSub(In1, In2);
99
Chris Lattner229907c2011-07-18 04:54:35 +0000100 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +0000101 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
102 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
103 if (HasSubOverflow(ExtractElement(Result, Idx),
104 ExtractElement(In1, Idx),
105 ExtractElement(In2, Idx),
106 IsSigned))
107 return true;
108 }
109 return false;
110 }
111
112 return HasSubOverflow(cast<ConstantInt>(Result),
113 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
114 IsSigned);
115}
116
Balaram Makam569eaec2016-05-04 21:32:14 +0000117/// Given an icmp instruction, return true if any use of this comparison is a
118/// branch on sign bit comparison.
119static bool isBranchOnSignBitCheck(ICmpInst &I, bool isSignBit) {
120 for (auto *U : I.users())
121 if (isa<BranchInst>(U))
122 return isSignBit;
123 return false;
124}
125
Chris Lattner2188e402010-01-04 07:37:31 +0000126/// isSignBitCheck - Given an exploded icmp instruction, return true if the
127/// comparison only checks the sign bit. If it only checks the sign bit, set
128/// TrueIfSigned if the result of the comparison is true when the input value is
129/// signed.
130static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
131 bool &TrueIfSigned) {
132 switch (pred) {
133 case ICmpInst::ICMP_SLT: // True if LHS s< 0
134 TrueIfSigned = true;
135 return RHS->isZero();
136 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
137 TrueIfSigned = true;
138 return RHS->isAllOnesValue();
139 case ICmpInst::ICMP_SGT: // True if LHS s> -1
140 TrueIfSigned = false;
141 return RHS->isAllOnesValue();
142 case ICmpInst::ICMP_UGT:
143 // True if LHS u> RHS and RHS == high-bit-mask - 1
144 TrueIfSigned = true;
Chris Lattnerb1a15122011-07-15 06:08:15 +0000145 return RHS->isMaxValue(true);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000146 case ICmpInst::ICMP_UGE:
Chris Lattner2188e402010-01-04 07:37:31 +0000147 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
148 TrueIfSigned = true;
149 return RHS->getValue().isSignBit();
150 default:
151 return false;
152 }
153}
154
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000155/// Returns true if the exploded icmp can be expressed as a signed comparison
156/// to zero and updates the predicate accordingly.
157/// The signedness of the comparison is preserved.
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000158static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
159 if (!ICmpInst::isSigned(pred))
160 return false;
161
162 if (RHS->isZero())
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000163 return ICmpInst::isRelational(pred);
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000164
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000165 if (RHS->isOne()) {
166 if (pred == ICmpInst::ICMP_SLT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000167 pred = ICmpInst::ICMP_SLE;
168 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000169 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000170 } else if (RHS->isAllOnesValue()) {
171 if (pred == ICmpInst::ICMP_SGT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000172 pred = ICmpInst::ICMP_SGE;
173 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000174 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000175 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000176
177 return false;
178}
179
Chris Lattner2188e402010-01-04 07:37:31 +0000180// isHighOnes - Return true if the constant is of the form 1+0+.
181// This is the same as lowones(~X).
182static bool isHighOnes(const ConstantInt *CI) {
183 return (~CI->getValue() + 1).isPowerOf2();
184}
185
Jim Grosbach129c52a2011-09-30 18:09:53 +0000186/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
Chris Lattner2188e402010-01-04 07:37:31 +0000187/// set of known zero and one bits, compute the maximum and minimum values that
188/// could have the specified known zero and known one bits, returning them in
189/// min/max.
190static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
191 const APInt& KnownOne,
192 APInt& Min, APInt& Max) {
193 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
194 KnownZero.getBitWidth() == Min.getBitWidth() &&
195 KnownZero.getBitWidth() == Max.getBitWidth() &&
196 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
197 APInt UnknownBits = ~(KnownZero|KnownOne);
198
199 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
200 // bit if it is unknown.
201 Min = KnownOne;
202 Max = KnownOne|UnknownBits;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000203
Chris Lattner2188e402010-01-04 07:37:31 +0000204 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000205 Min.setBit(Min.getBitWidth()-1);
206 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000207 }
208}
209
210// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
211// a set of known zero and one bits, compute the maximum and minimum values that
212// could have the specified known zero and known one bits, returning them in
213// min/max.
214static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
215 const APInt &KnownOne,
216 APInt &Min, APInt &Max) {
217 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
218 KnownZero.getBitWidth() == Min.getBitWidth() &&
219 KnownZero.getBitWidth() == Max.getBitWidth() &&
220 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
221 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000222
Chris Lattner2188e402010-01-04 07:37:31 +0000223 // The minimum value is when the unknown bits are all zeros.
224 Min = KnownOne;
225 // The maximum value is when the unknown bits are all ones.
226 Max = KnownOne|UnknownBits;
227}
228
Chris Lattner2188e402010-01-04 07:37:31 +0000229/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
230/// cmp pred (load (gep GV, ...)), cmpcst
231/// where GV is a global variable with a constant initializer. Try to simplify
232/// this into some simple computation that does not need the load. For example
233/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
234///
235/// If AndCst is non-null, then the loaded value is masked with that constant
236/// before doing the comparison. This handles cases like "A[i]&4 == 0".
237Instruction *InstCombiner::
238FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
239 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattnerfe741762012-01-31 02:55:06 +0000240 Constant *Init = GV->getInitializer();
241 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
Craig Topperf40110f2014-04-25 05:29:35 +0000242 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000243
Chris Lattnerfe741762012-01-31 02:55:06 +0000244 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +0000245 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000246
Chris Lattner2188e402010-01-04 07:37:31 +0000247 // There are many forms of this optimization we can handle, for now, just do
248 // the simple index into a single-dimensional array.
249 //
250 // Require: GEP GV, 0, i {{, constant indices}}
251 if (GEP->getNumOperands() < 3 ||
252 !isa<ConstantInt>(GEP->getOperand(1)) ||
253 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
254 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000255 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000256
257 // Check that indices after the variable are constants and in-range for the
258 // type they index. Collect the indices. This is typically for arrays of
259 // structs.
260 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000261
Chris Lattnerfe741762012-01-31 02:55:06 +0000262 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000263 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
264 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000265 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000266
Chris Lattner2188e402010-01-04 07:37:31 +0000267 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000268 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000269
Chris Lattner229907c2011-07-18 04:54:35 +0000270 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000271 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000272 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000273 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000274 EltTy = ATy->getElementType();
275 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000276 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000277 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000278
Chris Lattner2188e402010-01-04 07:37:31 +0000279 LaterIndices.push_back(IdxVal);
280 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000281
Chris Lattner2188e402010-01-04 07:37:31 +0000282 enum { Overdefined = -3, Undefined = -2 };
283
284 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000285
Chris Lattner2188e402010-01-04 07:37:31 +0000286 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
287 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
288 // and 87 is the second (and last) index. FirstTrueElement is -2 when
289 // undefined, otherwise set to the first true element. SecondTrueElement is
290 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
291 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
292
293 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
294 // form "i != 47 & i != 87". Same state transitions as for true elements.
295 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000296
Chris Lattner2188e402010-01-04 07:37:31 +0000297 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
298 /// define a state machine that triggers for ranges of values that the index
299 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
300 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
301 /// index in the range (inclusive). We use -2 for undefined here because we
302 /// use relative comparisons and don't want 0-1 to match -1.
303 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000304
Chris Lattner2188e402010-01-04 07:37:31 +0000305 // MagicBitvector - This is a magic bitvector where we set a bit if the
306 // comparison is true for element 'i'. If there are 64 elements or less in
307 // the array, this will fully represent all the comparison results.
308 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000309
Chris Lattner2188e402010-01-04 07:37:31 +0000310 // Scan the array and see if one of our patterns matches.
311 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000312 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
313 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000314 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000315
Chris Lattner2188e402010-01-04 07:37:31 +0000316 // If this is indexing an array of structures, get the structure element.
317 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000318 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000319
Chris Lattner2188e402010-01-04 07:37:31 +0000320 // If the element is masked, handle it.
321 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000322
Chris Lattner2188e402010-01-04 07:37:31 +0000323 // Find out if the comparison would be true or false for the i'th element.
324 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000325 CompareRHS, DL, TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000326 // If the result is undef for this element, ignore it.
327 if (isa<UndefValue>(C)) {
328 // Extend range state machines to cover this element in case there is an
329 // undef in the middle of the range.
330 if (TrueRangeEnd == (int)i-1)
331 TrueRangeEnd = i;
332 if (FalseRangeEnd == (int)i-1)
333 FalseRangeEnd = i;
334 continue;
335 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000336
Chris Lattner2188e402010-01-04 07:37:31 +0000337 // If we can't compute the result for any of the elements, we have to give
338 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000339 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000340
Chris Lattner2188e402010-01-04 07:37:31 +0000341 // Otherwise, we know if the comparison is true or false for this element,
342 // update our state machines.
343 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000344
Chris Lattner2188e402010-01-04 07:37:31 +0000345 // State machine for single/double/range index comparison.
346 if (IsTrueForElt) {
347 // Update the TrueElement state machine.
348 if (FirstTrueElement == Undefined)
349 FirstTrueElement = TrueRangeEnd = i; // First true element.
350 else {
351 // Update double-compare state machine.
352 if (SecondTrueElement == Undefined)
353 SecondTrueElement = i;
354 else
355 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000356
Chris Lattner2188e402010-01-04 07:37:31 +0000357 // Update range state machine.
358 if (TrueRangeEnd == (int)i-1)
359 TrueRangeEnd = i;
360 else
361 TrueRangeEnd = Overdefined;
362 }
363 } else {
364 // Update the FalseElement state machine.
365 if (FirstFalseElement == Undefined)
366 FirstFalseElement = FalseRangeEnd = i; // First false element.
367 else {
368 // Update double-compare state machine.
369 if (SecondFalseElement == Undefined)
370 SecondFalseElement = i;
371 else
372 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000373
Chris Lattner2188e402010-01-04 07:37:31 +0000374 // Update range state machine.
375 if (FalseRangeEnd == (int)i-1)
376 FalseRangeEnd = i;
377 else
378 FalseRangeEnd = Overdefined;
379 }
380 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000381
Chris Lattner2188e402010-01-04 07:37:31 +0000382 // If this element is in range, update our magic bitvector.
383 if (i < 64 && IsTrueForElt)
384 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000385
Chris Lattner2188e402010-01-04 07:37:31 +0000386 // If all of our states become overdefined, bail out early. Since the
387 // predicate is expensive, only check it every 8 elements. This is only
388 // really useful for really huge arrays.
389 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
390 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
391 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000392 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000393 }
394
395 // Now that we've scanned the entire array, emit our new comparison(s). We
396 // order the state machines in complexity of the generated code.
397 Value *Idx = GEP->getOperand(2);
398
Matt Arsenault5aeae182013-08-19 21:40:31 +0000399 // If the index is larger than the pointer size of the target, truncate the
400 // index down like the GEP would do implicitly. We don't have to do this for
401 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000402 if (!GEP->isInBounds()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000403 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000404 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
405 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
406 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
407 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000408
Chris Lattner2188e402010-01-04 07:37:31 +0000409 // If the comparison is only true for one or two elements, emit direct
410 // comparisons.
411 if (SecondTrueElement != Overdefined) {
412 // None true -> false.
413 if (FirstTrueElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000414 return replaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000415
Chris Lattner2188e402010-01-04 07:37:31 +0000416 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000417
Chris Lattner2188e402010-01-04 07:37:31 +0000418 // True for one element -> 'i == 47'.
419 if (SecondTrueElement == Undefined)
420 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000421
Chris Lattner2188e402010-01-04 07:37:31 +0000422 // True for two elements -> 'i == 47 | i == 72'.
423 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
424 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
425 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
426 return BinaryOperator::CreateOr(C1, C2);
427 }
428
429 // If the comparison is only false for one or two elements, emit direct
430 // comparisons.
431 if (SecondFalseElement != Overdefined) {
432 // None false -> true.
433 if (FirstFalseElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000434 return replaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000435
Chris Lattner2188e402010-01-04 07:37:31 +0000436 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
437
438 // False for one element -> 'i != 47'.
439 if (SecondFalseElement == Undefined)
440 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000441
Chris Lattner2188e402010-01-04 07:37:31 +0000442 // False for two elements -> 'i != 47 & i != 72'.
443 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
444 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
445 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
446 return BinaryOperator::CreateAnd(C1, C2);
447 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000448
Chris Lattner2188e402010-01-04 07:37:31 +0000449 // If the comparison can be replaced with a range comparison for the elements
450 // where it is true, emit the range check.
451 if (TrueRangeEnd != Overdefined) {
452 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000453
Chris Lattner2188e402010-01-04 07:37:31 +0000454 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
455 if (FirstTrueElement) {
456 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
457 Idx = Builder->CreateAdd(Idx, Offs);
458 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000459
Chris Lattner2188e402010-01-04 07:37:31 +0000460 Value *End = ConstantInt::get(Idx->getType(),
461 TrueRangeEnd-FirstTrueElement+1);
462 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
463 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000464
Chris Lattner2188e402010-01-04 07:37:31 +0000465 // False range check.
466 if (FalseRangeEnd != Overdefined) {
467 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
468 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
469 if (FirstFalseElement) {
470 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
471 Idx = Builder->CreateAdd(Idx, Offs);
472 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000473
Chris Lattner2188e402010-01-04 07:37:31 +0000474 Value *End = ConstantInt::get(Idx->getType(),
475 FalseRangeEnd-FirstFalseElement);
476 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
477 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000478
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000479 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000480 // of this load, replace it with computation that does:
481 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000482 {
Craig Topperf40110f2014-04-25 05:29:35 +0000483 Type *Ty = nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000484
485 // Look for an appropriate type:
486 // - The type of Idx if the magic fits
487 // - The smallest fitting legal type if we have a DataLayout
488 // - Default to i32
489 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
490 Ty = Idx->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000491 else
492 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000493
Craig Topperf40110f2014-04-25 05:29:35 +0000494 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000495 Value *V = Builder->CreateIntCast(Idx, Ty, false);
496 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
497 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
498 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
499 }
Chris Lattner2188e402010-01-04 07:37:31 +0000500 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000501
Craig Topperf40110f2014-04-25 05:29:35 +0000502 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000503}
504
Chris Lattner2188e402010-01-04 07:37:31 +0000505/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
506/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
507/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
508/// be complex, and scales are involved. The above expression would also be
509/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
510/// This later form is less amenable to optimization though, and we are allowed
511/// to generate the first by knowing that pointer arithmetic doesn't overflow.
512///
513/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000514///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000515static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
516 const DataLayout &DL) {
Chris Lattner2188e402010-01-04 07:37:31 +0000517 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000518
Chris Lattner2188e402010-01-04 07:37:31 +0000519 // Check to see if this gep only has a single variable index. If so, and if
520 // any constant indices are a multiple of its scale, then we can compute this
521 // in terms of the scale of the variable index. For example, if the GEP
522 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
523 // because the expression will cross zero at the same point.
524 unsigned i, e = GEP->getNumOperands();
525 int64_t Offset = 0;
526 for (i = 1; i != e; ++i, ++GTI) {
527 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
528 // Compute the aggregate offset of constant indices.
529 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000530
Chris Lattner2188e402010-01-04 07:37:31 +0000531 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000532 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000533 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000534 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000535 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000536 Offset += Size*CI->getSExtValue();
537 }
538 } else {
539 // Found our variable index.
540 break;
541 }
542 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000543
Chris Lattner2188e402010-01-04 07:37:31 +0000544 // If there are no variable indices, we must have a constant offset, just
545 // evaluate it the general way.
Craig Topperf40110f2014-04-25 05:29:35 +0000546 if (i == e) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000547
Chris Lattner2188e402010-01-04 07:37:31 +0000548 Value *VariableIdx = GEP->getOperand(i);
549 // Determine the scale factor of the variable element. For example, this is
550 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000551 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000552
Chris Lattner2188e402010-01-04 07:37:31 +0000553 // Verify that there are no other variable indices. If so, emit the hard way.
554 for (++i, ++GTI; i != e; ++i, ++GTI) {
555 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000556 if (!CI) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000557
Chris Lattner2188e402010-01-04 07:37:31 +0000558 // Compute the aggregate offset of constant indices.
559 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000560
Chris Lattner2188e402010-01-04 07:37:31 +0000561 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000562 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000563 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000564 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000565 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000566 Offset += Size*CI->getSExtValue();
567 }
568 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000569
Chris Lattner2188e402010-01-04 07:37:31 +0000570 // Okay, we know we have a single variable index, which must be a
571 // pointer/array/vector index. If there is no offset, life is simple, return
572 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000573 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000574 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000575 if (Offset == 0) {
576 // Cast to intptrty in case a truncation occurs. If an extension is needed,
577 // we don't need to bother extending: the extension won't affect where the
578 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000579 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000580 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
581 }
Chris Lattner2188e402010-01-04 07:37:31 +0000582 return VariableIdx;
583 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000584
Chris Lattner2188e402010-01-04 07:37:31 +0000585 // Otherwise, there is an index. The computation we will do will be modulo
586 // the pointer size, so get it.
587 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000588
Chris Lattner2188e402010-01-04 07:37:31 +0000589 Offset &= PtrSizeMask;
590 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000591
Chris Lattner2188e402010-01-04 07:37:31 +0000592 // To do this transformation, any constant index must be a multiple of the
593 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
594 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
595 // multiple of the variable scale.
596 int64_t NewOffs = Offset / (int64_t)VariableScale;
597 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000598 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000599
Chris Lattner2188e402010-01-04 07:37:31 +0000600 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000601 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000602 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
603 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000604 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000605 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000606}
607
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000608/// Returns true if we can rewrite Start as a GEP with pointer Base
609/// and some integer offset. The nodes that need to be re-written
610/// for this transformation will be added to Explored.
611static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
612 const DataLayout &DL,
613 SetVector<Value *> &Explored) {
614 SmallVector<Value *, 16> WorkList(1, Start);
615 Explored.insert(Base);
616
617 // The following traversal gives us an order which can be used
618 // when doing the final transformation. Since in the final
619 // transformation we create the PHI replacement instructions first,
620 // we don't have to get them in any particular order.
621 //
622 // However, for other instructions we will have to traverse the
623 // operands of an instruction first, which means that we have to
624 // do a post-order traversal.
625 while (!WorkList.empty()) {
626 SetVector<PHINode *> PHIs;
627
628 while (!WorkList.empty()) {
629 if (Explored.size() >= 100)
630 return false;
631
632 Value *V = WorkList.back();
633
634 if (Explored.count(V) != 0) {
635 WorkList.pop_back();
636 continue;
637 }
638
639 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
640 !isa<GEPOperator>(V) && !isa<PHINode>(V))
641 // We've found some value that we can't explore which is different from
642 // the base. Therefore we can't do this transformation.
643 return false;
644
645 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
646 auto *CI = dyn_cast<CastInst>(V);
647 if (!CI->isNoopCast(DL))
648 return false;
649
650 if (Explored.count(CI->getOperand(0)) == 0)
651 WorkList.push_back(CI->getOperand(0));
652 }
653
654 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
655 // We're limiting the GEP to having one index. This will preserve
656 // the original pointer type. We could handle more cases in the
657 // future.
658 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
659 GEP->getType() != Start->getType())
660 return false;
661
662 if (Explored.count(GEP->getOperand(0)) == 0)
663 WorkList.push_back(GEP->getOperand(0));
664 }
665
666 if (WorkList.back() == V) {
667 WorkList.pop_back();
668 // We've finished visiting this node, mark it as such.
669 Explored.insert(V);
670 }
671
672 if (auto *PN = dyn_cast<PHINode>(V)) {
David Majnemercdf28732016-03-19 04:39:52 +0000673 // We cannot transform PHIs on unsplittable basic blocks.
674 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
675 return false;
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000676 Explored.insert(PN);
677 PHIs.insert(PN);
678 }
679 }
680
681 // Explore the PHI nodes further.
682 for (auto *PN : PHIs)
683 for (Value *Op : PN->incoming_values())
684 if (Explored.count(Op) == 0)
685 WorkList.push_back(Op);
686 }
687
688 // Make sure that we can do this. Since we can't insert GEPs in a basic
689 // block before a PHI node, we can't easily do this transformation if
690 // we have PHI node users of transformed instructions.
691 for (Value *Val : Explored) {
692 for (Value *Use : Val->uses()) {
693
694 auto *PHI = dyn_cast<PHINode>(Use);
695 auto *Inst = dyn_cast<Instruction>(Val);
696
697 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
698 Explored.count(PHI) == 0)
699 continue;
700
701 if (PHI->getParent() == Inst->getParent())
702 return false;
703 }
704 }
705 return true;
706}
707
708// Sets the appropriate insert point on Builder where we can add
709// a replacement Instruction for V (if that is possible).
710static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
711 bool Before = true) {
712 if (auto *PHI = dyn_cast<PHINode>(V)) {
713 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
714 return;
715 }
716 if (auto *I = dyn_cast<Instruction>(V)) {
717 if (!Before)
718 I = &*std::next(I->getIterator());
719 Builder.SetInsertPoint(I);
720 return;
721 }
722 if (auto *A = dyn_cast<Argument>(V)) {
723 // Set the insertion point in the entry block.
724 BasicBlock &Entry = A->getParent()->getEntryBlock();
725 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
726 return;
727 }
728 // Otherwise, this is a constant and we don't need to set a new
729 // insertion point.
730 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
731}
732
733/// Returns a re-written value of Start as an indexed GEP using Base as a
734/// pointer.
735static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
736 const DataLayout &DL,
737 SetVector<Value *> &Explored) {
738 // Perform all the substitutions. This is a bit tricky because we can
739 // have cycles in our use-def chains.
740 // 1. Create the PHI nodes without any incoming values.
741 // 2. Create all the other values.
742 // 3. Add the edges for the PHI nodes.
743 // 4. Emit GEPs to get the original pointers.
744 // 5. Remove the original instructions.
745 Type *IndexType = IntegerType::get(
746 Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType()));
747
748 DenseMap<Value *, Value *> NewInsts;
749 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
750
751 // Create the new PHI nodes, without adding any incoming values.
752 for (Value *Val : Explored) {
753 if (Val == Base)
754 continue;
755 // Create empty phi nodes. This avoids cyclic dependencies when creating
756 // the remaining instructions.
757 if (auto *PHI = dyn_cast<PHINode>(Val))
758 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
759 PHI->getName() + ".idx", PHI);
760 }
761 IRBuilder<> Builder(Base->getContext());
762
763 // Create all the other instructions.
764 for (Value *Val : Explored) {
765
766 if (NewInsts.find(Val) != NewInsts.end())
767 continue;
768
769 if (auto *CI = dyn_cast<CastInst>(Val)) {
770 NewInsts[CI] = NewInsts[CI->getOperand(0)];
771 continue;
772 }
773 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
774 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
775 : GEP->getOperand(1);
776 setInsertionPoint(Builder, GEP);
777 // Indices might need to be sign extended. GEPs will magically do
778 // this, but we need to do it ourselves here.
779 if (Index->getType()->getScalarSizeInBits() !=
780 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
781 Index = Builder.CreateSExtOrTrunc(
782 Index, NewInsts[GEP->getOperand(0)]->getType(),
783 GEP->getOperand(0)->getName() + ".sext");
784 }
785
786 auto *Op = NewInsts[GEP->getOperand(0)];
787 if (isa<ConstantInt>(Op) && dyn_cast<ConstantInt>(Op)->isZero())
788 NewInsts[GEP] = Index;
789 else
790 NewInsts[GEP] = Builder.CreateNSWAdd(
791 Op, Index, GEP->getOperand(0)->getName() + ".add");
792 continue;
793 }
794 if (isa<PHINode>(Val))
795 continue;
796
797 llvm_unreachable("Unexpected instruction type");
798 }
799
800 // Add the incoming values to the PHI nodes.
801 for (Value *Val : Explored) {
802 if (Val == Base)
803 continue;
804 // All the instructions have been created, we can now add edges to the
805 // phi nodes.
806 if (auto *PHI = dyn_cast<PHINode>(Val)) {
807 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
808 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
809 Value *NewIncoming = PHI->getIncomingValue(I);
810
811 if (NewInsts.find(NewIncoming) != NewInsts.end())
812 NewIncoming = NewInsts[NewIncoming];
813
814 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
815 }
816 }
817 }
818
819 for (Value *Val : Explored) {
820 if (Val == Base)
821 continue;
822
823 // Depending on the type, for external users we have to emit
824 // a GEP or a GEP + ptrtoint.
825 setInsertionPoint(Builder, Val, false);
826
827 // If required, create an inttoptr instruction for Base.
828 Value *NewBase = Base;
829 if (!Base->getType()->isPointerTy())
830 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
831 Start->getName() + "to.ptr");
832
833 Value *GEP = Builder.CreateInBoundsGEP(
834 Start->getType()->getPointerElementType(), NewBase,
835 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
836
837 if (!Val->getType()->isPointerTy()) {
838 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
839 Val->getName() + ".conv");
840 GEP = Cast;
841 }
842 Val->replaceAllUsesWith(GEP);
843 }
844
845 return NewInsts[Start];
846}
847
848/// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
849/// the input Value as a constant indexed GEP. Returns a pair containing
850/// the GEPs Pointer and Index.
851static std::pair<Value *, Value *>
852getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
853 Type *IndexType = IntegerType::get(V->getContext(),
854 DL.getPointerTypeSizeInBits(V->getType()));
855
856 Constant *Index = ConstantInt::getNullValue(IndexType);
857 while (true) {
858 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
859 // We accept only inbouds GEPs here to exclude the possibility of
860 // overflow.
861 if (!GEP->isInBounds())
862 break;
863 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
864 GEP->getType() == V->getType()) {
865 V = GEP->getOperand(0);
866 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
867 Index = ConstantExpr::getAdd(
868 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
869 continue;
870 }
871 break;
872 }
873 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
874 if (!CI->isNoopCast(DL))
875 break;
876 V = CI->getOperand(0);
877 continue;
878 }
879 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
880 if (!CI->isNoopCast(DL))
881 break;
882 V = CI->getOperand(0);
883 continue;
884 }
885 break;
886 }
887 return {V, Index};
888}
889
890// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
891// We can look through PHIs, GEPs and casts in order to determine a
892// common base between GEPLHS and RHS.
893static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
894 ICmpInst::Predicate Cond,
895 const DataLayout &DL) {
896 if (!GEPLHS->hasAllConstantIndices())
897 return nullptr;
898
899 Value *PtrBase, *Index;
900 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
901
902 // The set of nodes that will take part in this transformation.
903 SetVector<Value *> Nodes;
904
905 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
906 return nullptr;
907
908 // We know we can re-write this as
909 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
910 // Since we've only looked through inbouds GEPs we know that we
911 // can't have overflow on either side. We can therefore re-write
912 // this as:
913 // OFFSET1 cmp OFFSET2
914 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
915
916 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
917 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
918 // offset. Since Index is the offset of LHS to the base pointer, we will now
919 // compare the offsets instead of comparing the pointers.
920 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
921}
922
Chris Lattner2188e402010-01-04 07:37:31 +0000923/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
924/// else. At this point we know that the GEP is on the LHS of the comparison.
925Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
926 ICmpInst::Predicate Cond,
927 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000928 // Don't transform signed compares of GEPs into index compares. Even if the
929 // GEP is inbounds, the final add of the base pointer can have signed overflow
930 // and would change the result of the icmp.
931 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000932 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000933 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000934 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000935
Matt Arsenault44f60d02014-06-09 19:20:29 +0000936 // Look through bitcasts and addrspacecasts. We do not however want to remove
937 // 0 GEPs.
938 if (!isa<GetElementPtrInst>(RHS))
939 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000940
941 Value *PtrBase = GEPLHS->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000942 if (PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000943 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
944 // This transformation (ignoring the base and scales) is valid because we
945 // know pointers can't overflow since the gep is inbounds. See if we can
946 // output an optimized form.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000947 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this, DL);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000948
Chris Lattner2188e402010-01-04 07:37:31 +0000949 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000950 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000951 Offset = EmitGEPOffset(GEPLHS);
952 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
953 Constant::getNullValue(Offset->getType()));
954 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
955 // If the base pointers are different, but the indices are the same, just
956 // compare the base pointer.
957 if (PtrBase != GEPRHS->getOperand(0)) {
958 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
959 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
960 GEPRHS->getOperand(0)->getType();
961 if (IndicesTheSame)
962 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
963 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
964 IndicesTheSame = false;
965 break;
966 }
967
968 // If all indices are the same, just compare the base pointers.
969 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000970 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000971
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000972 // If we're comparing GEPs with two base pointers that only differ in type
973 // and both GEPs have only constant indices or just one use, then fold
974 // the compare with the adjusted indices.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000975 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000976 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
977 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
978 PtrBase->stripPointerCasts() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000979 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000980 Value *LOffset = EmitGEPOffset(GEPLHS);
981 Value *ROffset = EmitGEPOffset(GEPRHS);
982
983 // If we looked through an addrspacecast between different sized address
984 // spaces, the LHS and RHS pointers are different sized
985 // integers. Truncate to the smaller one.
986 Type *LHSIndexTy = LOffset->getType();
987 Type *RHSIndexTy = ROffset->getType();
988 if (LHSIndexTy != RHSIndexTy) {
989 if (LHSIndexTy->getPrimitiveSizeInBits() <
990 RHSIndexTy->getPrimitiveSizeInBits()) {
991 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
992 } else
993 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
994 }
995
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000996 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000997 LOffset, ROffset);
Sanjay Patel4b198802016-02-01 22:23:39 +0000998 return replaceInstUsesWith(I, Cmp);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000999 }
1000
Chris Lattner2188e402010-01-04 07:37:31 +00001001 // Otherwise, the base pointers are different and the indices are
Silviu Barangaf29dfd32016-01-15 15:52:05 +00001002 // different. Try convert this to an indexed compare by looking through
1003 // PHIs/casts.
1004 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +00001005 }
1006
1007 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001008 if (GEPLHS->hasAllZeroIndices())
Chris Lattner2188e402010-01-04 07:37:31 +00001009 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +00001010 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +00001011
1012 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001013 if (GEPRHS->hasAllZeroIndices())
Chris Lattner2188e402010-01-04 07:37:31 +00001014 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
1015
Stuart Hastings66a82b92011-05-14 05:55:10 +00001016 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +00001017 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
1018 // If the GEPs only differ by one index, compare it.
1019 unsigned NumDifferences = 0; // Keep track of # differences.
1020 unsigned DiffOperand = 0; // The operand that differs.
1021 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
1022 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
1023 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
1024 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
1025 // Irreconcilable differences.
1026 NumDifferences = 2;
1027 break;
1028 } else {
1029 if (NumDifferences++) break;
1030 DiffOperand = i;
1031 }
1032 }
1033
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +00001034 if (NumDifferences == 0) // SAME GEP?
Sanjay Patel4b198802016-02-01 22:23:39 +00001035 return replaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +00001036 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +00001037
Stuart Hastings66a82b92011-05-14 05:55:10 +00001038 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +00001039 Value *LHSV = GEPLHS->getOperand(DiffOperand);
1040 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1041 // Make sure we do a signed comparison here.
1042 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
1043 }
1044 }
1045
1046 // Only lower this if the icmp is the only user of the GEP or if we expect
1047 // the result to fold to a constant!
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001048 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner2188e402010-01-04 07:37:31 +00001049 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1050 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
1051 Value *L = EmitGEPOffset(GEPLHS);
1052 Value *R = EmitGEPOffset(GEPRHS);
1053 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1054 }
1055 }
Silviu Barangaf29dfd32016-01-15 15:52:05 +00001056
1057 // Try convert this to an indexed compare by looking through PHIs/casts as a
1058 // last resort.
1059 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +00001060}
1061
Hans Wennborgf1f36512015-10-07 00:20:07 +00001062Instruction *InstCombiner::FoldAllocaCmp(ICmpInst &ICI, AllocaInst *Alloca,
1063 Value *Other) {
1064 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1065
1066 // It would be tempting to fold away comparisons between allocas and any
1067 // pointer not based on that alloca (e.g. an argument). However, even
1068 // though such pointers cannot alias, they can still compare equal.
1069 //
1070 // But LLVM doesn't specify where allocas get their memory, so if the alloca
1071 // doesn't escape we can argue that it's impossible to guess its value, and we
1072 // can therefore act as if any such guesses are wrong.
1073 //
1074 // The code below checks that the alloca doesn't escape, and that it's only
1075 // used in a comparison once (the current instruction). The
1076 // single-comparison-use condition ensures that we're trivially folding all
1077 // comparisons against the alloca consistently, and avoids the risk of
1078 // erroneously folding a comparison of the pointer with itself.
1079
1080 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1081
1082 SmallVector<Use *, 32> Worklist;
1083 for (Use &U : Alloca->uses()) {
1084 if (Worklist.size() >= MaxIter)
1085 return nullptr;
1086 Worklist.push_back(&U);
1087 }
1088
1089 unsigned NumCmps = 0;
1090 while (!Worklist.empty()) {
1091 assert(Worklist.size() <= MaxIter);
1092 Use *U = Worklist.pop_back_val();
1093 Value *V = U->getUser();
1094 --MaxIter;
1095
1096 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1097 isa<SelectInst>(V)) {
1098 // Track the uses.
1099 } else if (isa<LoadInst>(V)) {
1100 // Loading from the pointer doesn't escape it.
1101 continue;
1102 } else if (auto *SI = dyn_cast<StoreInst>(V)) {
1103 // Storing *to* the pointer is fine, but storing the pointer escapes it.
1104 if (SI->getValueOperand() == U->get())
1105 return nullptr;
1106 continue;
1107 } else if (isa<ICmpInst>(V)) {
1108 if (NumCmps++)
1109 return nullptr; // Found more than one cmp.
1110 continue;
1111 } else if (auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
1112 switch (Intrin->getIntrinsicID()) {
1113 // These intrinsics don't escape or compare the pointer. Memset is safe
1114 // because we don't allow ptrtoint. Memcpy and memmove are safe because
1115 // we don't allow stores, so src cannot point to V.
1116 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1117 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
1118 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1119 continue;
1120 default:
1121 return nullptr;
1122 }
1123 } else {
1124 return nullptr;
1125 }
1126 for (Use &U : V->uses()) {
1127 if (Worklist.size() >= MaxIter)
1128 return nullptr;
1129 Worklist.push_back(&U);
1130 }
1131 }
1132
1133 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001134 return replaceInstUsesWith(
Hans Wennborgf1f36512015-10-07 00:20:07 +00001135 ICI,
1136 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1137}
1138
Chris Lattner2188e402010-01-04 07:37:31 +00001139/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00001140Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
Chris Lattner2188e402010-01-04 07:37:31 +00001141 Value *X, ConstantInt *CI,
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00001142 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +00001143 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001144 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +00001145 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +00001146
Chris Lattner8c92b572010-01-08 17:48:19 +00001147 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +00001148 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
1149 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
1150 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00001151 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +00001152 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +00001153 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1154 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001155
Chris Lattner2188e402010-01-04 07:37:31 +00001156 // (X+1) >u X --> X <u (0-1) --> X != 255
1157 // (X+2) >u X --> X <u (0-2) --> X <u 254
1158 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +00001159 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +00001160 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001161
Chris Lattner2188e402010-01-04 07:37:31 +00001162 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
1163 ConstantInt *SMax = ConstantInt::get(X->getContext(),
1164 APInt::getSignedMaxValue(BitWidth));
1165
1166 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1167 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1168 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1169 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1170 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1171 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +00001172 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +00001173 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001174
Chris Lattner2188e402010-01-04 07:37:31 +00001175 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1176 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1177 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1178 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1179 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1180 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +00001181
Chris Lattner2188e402010-01-04 07:37:31 +00001182 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +00001183 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +00001184 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
1185}
1186
1187/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
1188/// and CmpRHS are both known to be integer constants.
1189Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
1190 ConstantInt *DivRHS) {
1191 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
1192 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001193
1194 // FIXME: If the operand types don't match the type of the divide
Chris Lattner2188e402010-01-04 07:37:31 +00001195 // then don't attempt this transform. The code below doesn't have the
1196 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach129c52a2011-09-30 18:09:53 +00001197 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner2188e402010-01-04 07:37:31 +00001198 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach129c52a2011-09-30 18:09:53 +00001199 // (x /u C1) <u C2. Simply casting the operands and result won't
1200 // work. :( The if statement below tests that condition and bails
Chris Lattner98457102011-02-10 05:23:05 +00001201 // if it finds it.
Chris Lattner2188e402010-01-04 07:37:31 +00001202 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
1203 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Craig Topperf40110f2014-04-25 05:29:35 +00001204 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001205 if (DivRHS->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +00001206 return nullptr; // The ProdOV computation fails on divide by zero.
Chris Lattner2188e402010-01-04 07:37:31 +00001207 if (DivIsSigned && DivRHS->isAllOnesValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001208 return nullptr; // The overflow computation also screws up here
Chris Lattner43273af2011-02-13 08:07:21 +00001209 if (DivRHS->isOne()) {
1210 // This eliminates some funny cases with INT_MIN.
1211 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
1212 return &ICI;
1213 }
Chris Lattner2188e402010-01-04 07:37:31 +00001214
1215 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach129c52a2011-09-30 18:09:53 +00001216 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
1217 // C2 (CI). By solving for X we can turn this into a range check
1218 // instead of computing a divide.
Chris Lattner2188e402010-01-04 07:37:31 +00001219 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
1220
1221 // Determine if the product overflows by seeing if the product is
1222 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach129c52a2011-09-30 18:09:53 +00001223 // as in the LHS instruction that we're folding.
Chris Lattner2188e402010-01-04 07:37:31 +00001224 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
1225 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
1226
1227 // Get the ICmp opcode
1228 ICmpInst::Predicate Pred = ICI.getPredicate();
1229
Chris Lattner98457102011-02-10 05:23:05 +00001230 /// If the division is known to be exact, then there is no remainder from the
1231 /// divide, so the covered range size is unit, otherwise it is the divisor.
1232 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001233
Chris Lattner2188e402010-01-04 07:37:31 +00001234 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach129c52a2011-09-30 18:09:53 +00001235 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner2188e402010-01-04 07:37:31 +00001236 // Compute this interval based on the constants involved and the signedness of
1237 // the compare/divide. This computes a half-open interval, keeping track of
1238 // whether either value in the interval overflows. After analysis each
1239 // overflow variable is set to 0 if it's corresponding bound variable is valid
1240 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
1241 int LoOverflow = 0, HiOverflow = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001242 Constant *LoBound = nullptr, *HiBound = nullptr;
Chris Lattner98457102011-02-10 05:23:05 +00001243
Chris Lattner2188e402010-01-04 07:37:31 +00001244 if (!DivIsSigned) { // udiv
1245 // e.g. X/5 op 3 --> [15, 20)
1246 LoBound = Prod;
1247 HiOverflow = LoOverflow = ProdOV;
Chris Lattner98457102011-02-10 05:23:05 +00001248 if (!HiOverflow) {
1249 // If this is not an exact divide, then many values in the range collapse
1250 // to the same result value.
1251 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
1252 }
Chris Lattner2188e402010-01-04 07:37:31 +00001253 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
1254 if (CmpRHSV == 0) { // (X / pos) op 0
1255 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner98457102011-02-10 05:23:05 +00001256 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
1257 HiBound = RangeSize;
Chris Lattner2188e402010-01-04 07:37:31 +00001258 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
1259 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
1260 HiOverflow = LoOverflow = ProdOV;
1261 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001262 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +00001263 } else { // (X / pos) op neg
1264 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
1265 HiBound = AddOne(Prod);
1266 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
1267 if (!LoOverflow) {
Chris Lattner98457102011-02-10 05:23:05 +00001268 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001269 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattner98457102011-02-10 05:23:05 +00001270 }
Chris Lattner2188e402010-01-04 07:37:31 +00001271 }
Chris Lattnerb1a15122011-07-15 06:08:15 +00001272 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattner98457102011-02-10 05:23:05 +00001273 if (DivI->isExact())
1274 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001275 if (CmpRHSV == 0) { // (X / neg) op 0
1276 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner98457102011-02-10 05:23:05 +00001277 LoBound = AddOne(RangeSize);
1278 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001279 if (HiBound == DivRHS) { // -INTMIN = INTMIN
1280 HiOverflow = 1; // [INTMIN+1, overflow)
Craig Topperf40110f2014-04-25 05:29:35 +00001281 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
Chris Lattner2188e402010-01-04 07:37:31 +00001282 }
1283 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
1284 // e.g. X/-5 op 3 --> [-19, -14)
1285 HiBound = AddOne(Prod);
1286 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
1287 if (!LoOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001288 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner2188e402010-01-04 07:37:31 +00001289 } else { // (X / neg) op neg
1290 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
1291 LoOverflow = HiOverflow = ProdOV;
1292 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001293 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +00001294 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001295
Chris Lattner2188e402010-01-04 07:37:31 +00001296 // Dividing by a negative swaps the condition. LT <-> GT
1297 Pred = ICmpInst::getSwappedPredicate(Pred);
1298 }
1299
1300 Value *X = DivI->getOperand(0);
1301 switch (Pred) {
1302 default: llvm_unreachable("Unhandled icmp opcode!");
1303 case ICmpInst::ICMP_EQ:
1304 if (LoOverflow && HiOverflow)
Sanjay Patel4b198802016-02-01 22:23:39 +00001305 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner067459c2010-03-05 08:46:26 +00001306 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001307 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1308 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +00001309 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001310 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1311 ICmpInst::ICMP_ULT, X, HiBound);
Sanjay Patel4b198802016-02-01 22:23:39 +00001312 return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
Chris Lattner98457102011-02-10 05:23:05 +00001313 DivIsSigned, true));
Chris Lattner2188e402010-01-04 07:37:31 +00001314 case ICmpInst::ICMP_NE:
1315 if (LoOverflow && HiOverflow)
Sanjay Patel4b198802016-02-01 22:23:39 +00001316 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner067459c2010-03-05 08:46:26 +00001317 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001318 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1319 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +00001320 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001321 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1322 ICmpInst::ICMP_UGE, X, HiBound);
Sanjay Patel4b198802016-02-01 22:23:39 +00001323 return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
Chris Lattner067459c2010-03-05 08:46:26 +00001324 DivIsSigned, false));
Chris Lattner2188e402010-01-04 07:37:31 +00001325 case ICmpInst::ICMP_ULT:
1326 case ICmpInst::ICMP_SLT:
1327 if (LoOverflow == +1) // Low bound is greater than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001328 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001329 if (LoOverflow == -1) // Low bound is less than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001330 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001331 return new ICmpInst(Pred, X, LoBound);
1332 case ICmpInst::ICMP_UGT:
1333 case ICmpInst::ICMP_SGT:
1334 if (HiOverflow == +1) // High bound greater than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001335 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner98457102011-02-10 05:23:05 +00001336 if (HiOverflow == -1) // High bound less than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001337 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001338 if (Pred == ICmpInst::ICMP_UGT)
1339 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +00001340 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner2188e402010-01-04 07:37:31 +00001341 }
1342}
1343
Chris Lattnerd369f572011-02-13 07:43:07 +00001344/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
1345Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
1346 ConstantInt *ShAmt) {
Chris Lattnerd369f572011-02-13 07:43:07 +00001347 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001348
Chris Lattnerd369f572011-02-13 07:43:07 +00001349 // Check that the shift amount is in range. If not, don't perform
1350 // undefined shifts. When the shift is visited it will be
1351 // simplified.
1352 uint32_t TypeBits = CmpRHSV.getBitWidth();
1353 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner43273af2011-02-13 08:07:21 +00001354 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001355 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001356
Chris Lattner43273af2011-02-13 08:07:21 +00001357 if (!ICI.isEquality()) {
1358 // If we have an unsigned comparison and an ashr, we can't simplify this.
1359 // Similarly for signed comparisons with lshr.
1360 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
Craig Topperf40110f2014-04-25 05:29:35 +00001361 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001362
Eli Friedman865866e2011-05-25 23:26:20 +00001363 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
1364 // by a power of 2. Since we already have logic to simplify these,
1365 // transform to div and then simplify the resultant comparison.
Chris Lattner43273af2011-02-13 08:07:21 +00001366 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedman865866e2011-05-25 23:26:20 +00001367 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Craig Topperf40110f2014-04-25 05:29:35 +00001368 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001369
Chris Lattner43273af2011-02-13 08:07:21 +00001370 // Revisit the shift (to delete it).
1371 Worklist.Add(Shr);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001372
Chris Lattner43273af2011-02-13 08:07:21 +00001373 Constant *DivCst =
1374 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001375
Chris Lattner43273af2011-02-13 08:07:21 +00001376 Value *Tmp =
1377 Shr->getOpcode() == Instruction::AShr ?
1378 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
1379 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001380
Chris Lattner43273af2011-02-13 08:07:21 +00001381 ICI.setOperand(0, Tmp);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001382
Chris Lattner43273af2011-02-13 08:07:21 +00001383 // If the builder folded the binop, just return it.
1384 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
Craig Topperf40110f2014-04-25 05:29:35 +00001385 if (!TheDiv)
Chris Lattner43273af2011-02-13 08:07:21 +00001386 return &ICI;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001387
Chris Lattner43273af2011-02-13 08:07:21 +00001388 // Otherwise, fold this div/compare.
1389 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1390 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001391
Chris Lattner43273af2011-02-13 08:07:21 +00001392 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1393 assert(Res && "This div/cst should have folded!");
1394 return Res;
1395 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001396
Chris Lattnerd369f572011-02-13 07:43:07 +00001397 // If we are comparing against bits always shifted out, the
1398 // comparison cannot succeed.
1399 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszakbddea112013-06-06 20:18:46 +00001400 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattnerd369f572011-02-13 07:43:07 +00001401 if (Shr->getOpcode() == Instruction::LShr)
1402 Comp = Comp.lshr(ShAmtVal);
1403 else
1404 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001405
Chris Lattnerd369f572011-02-13 07:43:07 +00001406 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1407 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001408 Constant *Cst = Builder->getInt1(IsICMP_NE);
Sanjay Patel4b198802016-02-01 22:23:39 +00001409 return replaceInstUsesWith(ICI, Cst);
Chris Lattnerd369f572011-02-13 07:43:07 +00001410 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001411
Chris Lattnerd369f572011-02-13 07:43:07 +00001412 // Otherwise, check to see if the bits shifted out are known to be zero.
1413 // If so, we can compare against the unshifted value:
1414 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattner9bd7fdf2011-02-13 18:30:09 +00001415 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattnerd369f572011-02-13 07:43:07 +00001416 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001417
Chris Lattnerd369f572011-02-13 07:43:07 +00001418 if (Shr->hasOneUse()) {
1419 // Otherwise strength reduce the shift into an and.
1420 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszakbddea112013-06-06 20:18:46 +00001421 Constant *Mask = Builder->getInt(Val);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001422
Chris Lattnerd369f572011-02-13 07:43:07 +00001423 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1424 Mask, Shr->getName()+".mask");
1425 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1426 }
Craig Topperf40110f2014-04-25 05:29:35 +00001427 return nullptr;
Chris Lattnerd369f572011-02-13 07:43:07 +00001428}
1429
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001430/// FoldICmpCstShrCst - Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
1431/// (icmp eq/ne A, Log2(const2/const1)) ->
1432/// (icmp eq/ne A, Log2(const2) - Log2(const1)).
1433Instruction *InstCombiner::FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
1434 ConstantInt *CI1,
1435 ConstantInt *CI2) {
1436 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1437
1438 auto getConstant = [&I, this](bool IsTrue) {
1439 if (I.getPredicate() == I.ICMP_NE)
1440 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001441 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001442 };
1443
1444 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1445 if (I.getPredicate() == I.ICMP_NE)
1446 Pred = CmpInst::getInversePredicate(Pred);
1447 return new ICmpInst(Pred, LHS, RHS);
1448 };
1449
1450 APInt AP1 = CI1->getValue();
1451 APInt AP2 = CI2->getValue();
1452
David Majnemer2abb8182014-10-25 07:13:13 +00001453 // Don't bother doing any work for cases which InstSimplify handles.
1454 if (AP2 == 0)
1455 return nullptr;
1456 bool IsAShr = isa<AShrOperator>(Op);
1457 if (IsAShr) {
1458 if (AP2.isAllOnesValue())
1459 return nullptr;
1460 if (AP2.isNegative() != AP1.isNegative())
1461 return nullptr;
1462 if (AP2.sgt(AP1))
1463 return nullptr;
1464 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001465
David Majnemerd2056022014-10-21 19:51:55 +00001466 if (!AP1)
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001467 // 'A' must be large enough to shift out the highest set bit.
1468 return getICmp(I.ICMP_UGT, A,
1469 ConstantInt::get(A->getType(), AP2.logBase2()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001470
David Majnemerd2056022014-10-21 19:51:55 +00001471 if (AP1 == AP2)
1472 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001473
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001474 int Shift;
David Majnemerd2056022014-10-21 19:51:55 +00001475 if (IsAShr && AP1.isNegative())
David Majnemere5977eb2015-09-19 00:48:26 +00001476 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001477 else
David Majnemere5977eb2015-09-19 00:48:26 +00001478 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001479
David Majnemerd2056022014-10-21 19:51:55 +00001480 if (Shift > 0) {
David Majnemere5977eb2015-09-19 00:48:26 +00001481 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1482 // There are multiple solutions if we are comparing against -1 and the LHS
David Majnemer47ce0b82015-09-19 00:48:31 +00001483 // of the ashr is not a power of two.
David Majnemere5977eb2015-09-19 00:48:26 +00001484 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1485 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
David Majnemerd2056022014-10-21 19:51:55 +00001486 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
David Majnemere5977eb2015-09-19 00:48:26 +00001487 } else if (AP1 == AP2.lshr(Shift)) {
1488 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1489 }
David Majnemerd2056022014-10-21 19:51:55 +00001490 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001491 // Shifting const2 will never be equal to const1.
1492 return getConstant(false);
1493}
Chris Lattner2188e402010-01-04 07:37:31 +00001494
David Majnemer59939ac2014-10-19 08:23:08 +00001495/// FoldICmpCstShlCst - Handle "(icmp eq/ne (shl const2, A), const1)" ->
1496/// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)).
1497Instruction *InstCombiner::FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
1498 ConstantInt *CI1,
1499 ConstantInt *CI2) {
1500 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1501
1502 auto getConstant = [&I, this](bool IsTrue) {
1503 if (I.getPredicate() == I.ICMP_NE)
1504 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001505 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
David Majnemer59939ac2014-10-19 08:23:08 +00001506 };
1507
1508 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1509 if (I.getPredicate() == I.ICMP_NE)
1510 Pred = CmpInst::getInversePredicate(Pred);
1511 return new ICmpInst(Pred, LHS, RHS);
1512 };
1513
1514 APInt AP1 = CI1->getValue();
1515 APInt AP2 = CI2->getValue();
1516
David Majnemer2abb8182014-10-25 07:13:13 +00001517 // Don't bother doing any work for cases which InstSimplify handles.
1518 if (AP2 == 0)
1519 return nullptr;
David Majnemer59939ac2014-10-19 08:23:08 +00001520
1521 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1522
1523 if (!AP1 && AP2TrailingZeros != 0)
1524 return getICmp(I.ICMP_UGE, A,
1525 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1526
1527 if (AP1 == AP2)
1528 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1529
1530 // Get the distance between the lowest bits that are set.
1531 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1532
1533 if (Shift > 0 && AP2.shl(Shift) == AP1)
1534 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1535
1536 // Shifting const2 will never be equal to const1.
1537 return getConstant(false);
1538}
1539
Chris Lattner2188e402010-01-04 07:37:31 +00001540/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1541///
1542Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1543 Instruction *LHSI,
1544 ConstantInt *RHS) {
1545 const APInt &RHSV = RHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001546
Chris Lattner2188e402010-01-04 07:37:31 +00001547 switch (LHSI->getOpcode()) {
1548 case Instruction::Trunc:
Sanjoy Dase5f48892015-09-16 20:41:29 +00001549 if (RHS->isOne() && RHSV.getBitWidth() > 1) {
1550 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1551 Value *V = nullptr;
1552 if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1553 match(LHSI->getOperand(0), m_Signum(m_Value(V))))
1554 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1555 ConstantInt::get(V->getType(), 1));
1556 }
Chris Lattner2188e402010-01-04 07:37:31 +00001557 if (ICI.isEquality() && LHSI->hasOneUse()) {
1558 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1559 // of the high bits truncated out of x are known.
1560 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1561 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner2188e402010-01-04 07:37:31 +00001562 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001563 computeKnownBits(LHSI->getOperand(0), KnownZero, KnownOne, 0, &ICI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001564
Chris Lattner2188e402010-01-04 07:37:31 +00001565 // If all the high bits are known, we can do this xform.
1566 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1567 // Pull in the high bits from known-ones set.
Jay Foad583abbc2010-12-07 08:25:19 +00001568 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedmane0a64d82012-05-11 01:32:59 +00001569 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner2188e402010-01-04 07:37:31 +00001570 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001571 Builder->getInt(NewRHS));
Chris Lattner2188e402010-01-04 07:37:31 +00001572 }
1573 }
1574 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001575
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001576 case Instruction::Xor: // (icmp pred (xor X, XorCst), CI)
1577 if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001578 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1579 // fold the xor.
1580 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1581 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1582 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001583
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001584 // If the sign bit of the XorCst is not set, there is no change to
Chris Lattner2188e402010-01-04 07:37:31 +00001585 // the operation, just stop using the Xor.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001586 if (!XorCst->isNegative()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001587 ICI.setOperand(0, CompareVal);
1588 Worklist.Add(LHSI);
1589 return &ICI;
1590 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001591
Chris Lattner2188e402010-01-04 07:37:31 +00001592 // Was the old condition true if the operand is positive?
1593 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001594
Chris Lattner2188e402010-01-04 07:37:31 +00001595 // If so, the new one isn't.
1596 isTrueIfPositive ^= true;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001597
Chris Lattner2188e402010-01-04 07:37:31 +00001598 if (isTrueIfPositive)
1599 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1600 SubOne(RHS));
1601 else
1602 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1603 AddOne(RHS));
1604 }
1605
1606 if (LHSI->hasOneUse()) {
1607 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001608 if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1609 const APInt &SignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001610 ICmpInst::Predicate Pred = ICI.isSigned()
1611 ? ICI.getUnsignedPredicate()
1612 : ICI.getSignedPredicate();
1613 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001614 Builder->getInt(RHSV ^ SignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001615 }
1616
1617 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001618 if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1619 const APInt &NotSignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001620 ICmpInst::Predicate Pred = ICI.isSigned()
1621 ? ICI.getUnsignedPredicate()
1622 : ICI.getSignedPredicate();
1623 Pred = ICI.getSwappedPredicate(Pred);
1624 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001625 Builder->getInt(RHSV ^ NotSignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001626 }
1627 }
David Majnemer72d76272013-07-09 09:20:58 +00001628
1629 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1630 // iff -C is a power of 2
1631 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001632 XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1633 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
David Majnemer72d76272013-07-09 09:20:58 +00001634
1635 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1636 // iff -C is a power of 2
1637 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001638 XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1639 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001640 }
1641 break;
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001642 case Instruction::And: // (icmp pred (and X, AndCst), RHS)
Chris Lattner2188e402010-01-04 07:37:31 +00001643 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1644 LHSI->getOperand(0)->hasOneUse()) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001645 ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001646
Chris Lattner2188e402010-01-04 07:37:31 +00001647 // If the LHS is an AND of a truncating cast, we can widen the
1648 // and/compare to be the input width without changing the value
1649 // produced, eliminating a cast.
1650 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1651 // We can do this transformation if either the AND constant does not
Jim Grosbach129c52a2011-09-30 18:09:53 +00001652 // have its sign bit set or if it is an equality comparison.
Chris Lattner2188e402010-01-04 07:37:31 +00001653 // Extending a relational comparison when we're checking the sign
1654 // bit would not work.
Benjamin Kramer35159c12011-06-12 22:47:53 +00001655 if (ICI.isEquality() ||
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001656 (!AndCst->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer35159c12011-06-12 22:47:53 +00001657 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001658 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001659 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
Benjamin Kramer35159c12011-06-12 22:47:53 +00001660 NewAnd->takeName(LHSI);
Chris Lattner2188e402010-01-04 07:37:31 +00001661 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer35159c12011-06-12 22:47:53 +00001662 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner2188e402010-01-04 07:37:31 +00001663 }
1664 }
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001665
1666 // If the LHS is an AND of a zext, and we have an equality compare, we can
1667 // shrink the and/compare to the smaller type, eliminating the cast.
1668 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattner229907c2011-07-18 04:54:35 +00001669 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001670 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1671 // should fold the icmp to true/false in that case.
1672 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1673 Value *NewAnd =
1674 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001675 ConstantExpr::getTrunc(AndCst, Ty));
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001676 NewAnd->takeName(LHSI);
1677 return new ICmpInst(ICI.getPredicate(), NewAnd,
1678 ConstantExpr::getTrunc(RHS, Ty));
1679 }
1680 }
1681
Chris Lattner2188e402010-01-04 07:37:31 +00001682 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1683 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1684 // happens a LOT in code produced by the C front-end, for bitfield
1685 // access.
1686 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1687 if (Shift && !Shift->isShift())
Craig Topperf40110f2014-04-25 05:29:35 +00001688 Shift = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001689
Chris Lattner2188e402010-01-04 07:37:31 +00001690 ConstantInt *ShAmt;
Craig Topperf40110f2014-04-25 05:29:35 +00001691 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001692
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001693 // This seemingly simple opportunity to fold away a shift turns out to
1694 // be rather complicated. See PR17827
1695 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
Chris Lattner2188e402010-01-04 07:37:31 +00001696 if (ShAmt) {
Kay Tiong Khoo5389f742013-12-02 18:43:59 +00001697 bool CanFold = false;
1698 unsigned ShiftOpcode = Shift->getOpcode();
1699 if (ShiftOpcode == Instruction::AShr) {
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001700 // There may be some constraints that make this possible,
1701 // but nothing simple has been discovered yet.
1702 CanFold = false;
1703 } else if (ShiftOpcode == Instruction::Shl) {
1704 // For a left shift, we can fold if the comparison is not signed.
1705 // We can also fold a signed comparison if the mask value and
1706 // comparison value are not negative. These constraints may not be
1707 // obvious, but we can prove that they are correct using an SMT
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001708 // solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001709 if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
Chris Lattner2188e402010-01-04 07:37:31 +00001710 CanFold = true;
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001711 } else if (ShiftOpcode == Instruction::LShr) {
1712 // For a logical right shift, we can fold if the comparison is not
1713 // signed. We can also fold a signed comparison if the shifted mask
1714 // value and the shifted comparison value are not negative.
1715 // These constraints may not be obvious, but we can prove that they
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001716 // are correct using an SMT solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001717 if (!ICI.isSigned())
1718 CanFold = true;
1719 else {
1720 ConstantInt *ShiftedAndCst =
1721 cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1722 ConstantInt *ShiftedRHSCst =
1723 cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1724
1725 if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1726 CanFold = true;
1727 }
Chris Lattner2188e402010-01-04 07:37:31 +00001728 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001729
Chris Lattner2188e402010-01-04 07:37:31 +00001730 if (CanFold) {
1731 Constant *NewCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001732 if (ShiftOpcode == Instruction::Shl)
Chris Lattner2188e402010-01-04 07:37:31 +00001733 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1734 else
1735 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001736
Chris Lattner2188e402010-01-04 07:37:31 +00001737 // Check to see if we are shifting out any of the bits being
1738 // compared.
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001739 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001740 // If we shifted bits out, the fold is not going to work out.
1741 // As a special case, check to see if this means that the
1742 // result is always true or false now.
1743 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00001744 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001745 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Sanjay Patel4b198802016-02-01 22:23:39 +00001746 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001747 } else {
1748 ICI.setOperand(1, NewCst);
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001749 Constant *NewAndCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001750 if (ShiftOpcode == Instruction::Shl)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001751 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
Chris Lattner2188e402010-01-04 07:37:31 +00001752 else
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001753 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1754 LHSI->setOperand(1, NewAndCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001755 LHSI->setOperand(0, Shift->getOperand(0));
1756 Worklist.Add(Shift); // Shift is dead.
1757 return &ICI;
1758 }
1759 }
1760 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001761
Chris Lattner2188e402010-01-04 07:37:31 +00001762 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1763 // preferable because it allows the C<<Y expression to be hoisted out
1764 // of a loop if Y is invariant and X is not.
1765 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1766 ICI.isEquality() && !Shift->isArithmeticShift() &&
1767 !isa<Constant>(Shift->getOperand(0))) {
1768 // Compute C << Y.
1769 Value *NS;
1770 if (Shift->getOpcode() == Instruction::LShr) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001771 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001772 } else {
1773 // Insert a logical shift.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001774 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001775 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001776
Chris Lattner2188e402010-01-04 07:37:31 +00001777 // Compute X & (C << Y).
Jim Grosbach129c52a2011-09-30 18:09:53 +00001778 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001779 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001780
Chris Lattner2188e402010-01-04 07:37:31 +00001781 ICI.setOperand(0, NewAnd);
1782 return &ICI;
1783 }
Paul Redmond5917f4c2012-12-19 19:47:13 +00001784
David Majnemer0ffccf72014-08-24 09:10:57 +00001785 // (icmp pred (and (or (lshr X, Y), X), 1), 0) -->
1786 // (icmp pred (and X, (or (shl 1, Y), 1), 0))
1787 //
1788 // iff pred isn't signed
1789 {
1790 Value *X, *Y, *LShr;
1791 if (!ICI.isSigned() && RHSV == 0) {
1792 if (match(LHSI->getOperand(1), m_One())) {
1793 Constant *One = cast<Constant>(LHSI->getOperand(1));
1794 Value *Or = LHSI->getOperand(0);
1795 if (match(Or, m_Or(m_Value(LShr), m_Value(X))) &&
1796 match(LShr, m_LShr(m_Specific(X), m_Value(Y)))) {
1797 unsigned UsesRemoved = 0;
1798 if (LHSI->hasOneUse())
1799 ++UsesRemoved;
1800 if (Or->hasOneUse())
1801 ++UsesRemoved;
1802 if (LShr->hasOneUse())
1803 ++UsesRemoved;
1804 Value *NewOr = nullptr;
1805 // Compute X & ((1 << Y) | 1)
1806 if (auto *C = dyn_cast<Constant>(Y)) {
1807 if (UsesRemoved >= 1)
1808 NewOr =
1809 ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1810 } else {
1811 if (UsesRemoved >= 3)
1812 NewOr = Builder->CreateOr(Builder->CreateShl(One, Y,
1813 LShr->getName(),
1814 /*HasNUW=*/true),
1815 One, Or->getName());
1816 }
1817 if (NewOr) {
1818 Value *NewAnd = Builder->CreateAnd(X, NewOr, LHSI->getName());
1819 ICI.setOperand(0, NewAnd);
1820 return &ICI;
1821 }
1822 }
1823 }
1824 }
1825 }
1826
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001827 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1828 // bit set in (X & AndCst) will produce a result greater than RHSV.
Paul Redmond5917f4c2012-12-19 19:47:13 +00001829 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001830 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1831 if ((NTZ < AndCst->getBitWidth()) &&
1832 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
Paul Redmond5917f4c2012-12-19 19:47:13 +00001833 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1834 Constant::getNullValue(RHS->getType()));
1835 }
Chris Lattner2188e402010-01-04 07:37:31 +00001836 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001837
Chris Lattner2188e402010-01-04 07:37:31 +00001838 // Try to optimize things like "A[i]&42 == 0" to index computations.
1839 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1840 if (GetElementPtrInst *GEP =
1841 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1842 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1843 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1844 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1845 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1846 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1847 return Res;
1848 }
1849 }
David Majnemer414d4e52013-07-09 08:09:32 +00001850
1851 // X & -C == -C -> X > u ~C
1852 // X & -C != -C -> X <= u ~C
1853 // iff C is a power of 2
1854 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1855 return new ICmpInst(
1856 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1857 : ICmpInst::ICMP_ULE,
1858 LHSI->getOperand(0), SubOne(RHS));
David Majnemerdfa3b092015-08-16 07:09:17 +00001859
1860 // (icmp eq (and %A, C), 0) -> (icmp sgt (trunc %A), -1)
1861 // iff C is a power of 2
1862 if (ICI.isEquality() && LHSI->hasOneUse() && match(RHS, m_Zero())) {
1863 if (auto *CI = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1864 const APInt &AI = CI->getValue();
1865 int32_t ExactLogBase2 = AI.exactLogBase2();
1866 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1867 Type *NTy = IntegerType::get(ICI.getContext(), ExactLogBase2 + 1);
1868 Value *Trunc = Builder->CreateTrunc(LHSI->getOperand(0), NTy);
1869 return new ICmpInst(ICI.getPredicate() == ICmpInst::ICMP_EQ
1870 ? ICmpInst::ICMP_SGE
1871 : ICmpInst::ICMP_SLT,
1872 Trunc, Constant::getNullValue(NTy));
1873 }
1874 }
1875 }
Chris Lattner2188e402010-01-04 07:37:31 +00001876 break;
1877
1878 case Instruction::Or: {
Sanjoy Dase5f48892015-09-16 20:41:29 +00001879 if (RHS->isOne()) {
1880 // icmp slt signum(V) 1 --> icmp slt V, 1
1881 Value *V = nullptr;
1882 if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1883 match(LHSI, m_Signum(m_Value(V))))
1884 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1885 ConstantInt::get(V->getType(), 1));
1886 }
1887
Chris Lattner2188e402010-01-04 07:37:31 +00001888 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1889 break;
1890 Value *P, *Q;
1891 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1892 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1893 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner2188e402010-01-04 07:37:31 +00001894 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1895 Constant::getNullValue(P->getType()));
1896 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1897 Constant::getNullValue(Q->getType()));
1898 Instruction *Op;
1899 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1900 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1901 else
1902 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1903 return Op;
1904 }
1905 break;
1906 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001907
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001908 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1909 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1910 if (!Val) break;
1911
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001912 // If this is a signed comparison to 0 and the mul is sign preserving,
1913 // use the mul LHS operand instead.
1914 ICmpInst::Predicate pred = ICI.getPredicate();
1915 if (isSignTest(pred, RHS) && !Val->isZero() &&
1916 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1917 return new ICmpInst(Val->isNegative() ?
1918 ICmpInst::getSwappedPredicate(pred) : pred,
1919 LHSI->getOperand(0),
1920 Constant::getNullValue(RHS->getType()));
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001921
1922 break;
1923 }
1924
Chris Lattner2188e402010-01-04 07:37:31 +00001925 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
Chris Lattner2188e402010-01-04 07:37:31 +00001926 uint32_t TypeBits = RHSV.getBitWidth();
David Majnemerb889e402013-06-28 23:42:03 +00001927 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1928 if (!ShAmt) {
1929 Value *X;
1930 // (1 << X) pred P2 -> X pred Log2(P2)
1931 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1932 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1933 ICmpInst::Predicate Pred = ICI.getPredicate();
1934 if (ICI.isUnsigned()) {
1935 if (!RHSVIsPowerOf2) {
1936 // (1 << X) < 30 -> X <= 4
1937 // (1 << X) <= 30 -> X <= 4
1938 // (1 << X) >= 30 -> X > 4
1939 // (1 << X) > 30 -> X > 4
1940 if (Pred == ICmpInst::ICMP_ULT)
1941 Pred = ICmpInst::ICMP_ULE;
1942 else if (Pred == ICmpInst::ICMP_UGE)
1943 Pred = ICmpInst::ICMP_UGT;
1944 }
1945 unsigned RHSLog2 = RHSV.logBase2();
1946
1947 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
David Majnemerb889e402013-06-28 23:42:03 +00001948 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1949 if (RHSLog2 == TypeBits-1) {
1950 if (Pred == ICmpInst::ICMP_UGE)
1951 Pred = ICmpInst::ICMP_EQ;
David Majnemerb889e402013-06-28 23:42:03 +00001952 else if (Pred == ICmpInst::ICMP_ULT)
1953 Pred = ICmpInst::ICMP_NE;
1954 }
1955
1956 return new ICmpInst(Pred, X,
1957 ConstantInt::get(RHS->getType(), RHSLog2));
1958 } else if (ICI.isSigned()) {
1959 if (RHSV.isAllOnesValue()) {
1960 // (1 << X) <= -1 -> X == 31
1961 if (Pred == ICmpInst::ICMP_SLE)
1962 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1963 ConstantInt::get(RHS->getType(), TypeBits-1));
1964
1965 // (1 << X) > -1 -> X != 31
1966 if (Pred == ICmpInst::ICMP_SGT)
1967 return new ICmpInst(ICmpInst::ICMP_NE, X,
1968 ConstantInt::get(RHS->getType(), TypeBits-1));
1969 } else if (!RHSV) {
1970 // (1 << X) < 0 -> X == 31
1971 // (1 << X) <= 0 -> X == 31
1972 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1973 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1974 ConstantInt::get(RHS->getType(), TypeBits-1));
1975
1976 // (1 << X) >= 0 -> X != 31
1977 // (1 << X) > 0 -> X != 31
1978 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1979 return new ICmpInst(ICmpInst::ICMP_NE, X,
1980 ConstantInt::get(RHS->getType(), TypeBits-1));
1981 }
1982 } else if (ICI.isEquality()) {
1983 if (RHSVIsPowerOf2)
1984 return new ICmpInst(
1985 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
David Majnemerb889e402013-06-28 23:42:03 +00001986 }
1987 }
1988 break;
1989 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001990
Chris Lattner2188e402010-01-04 07:37:31 +00001991 // Check that the shift amount is in range. If not, don't perform
1992 // undefined shifts. When the shift is visited it will be
1993 // simplified.
1994 if (ShAmt->uge(TypeBits))
1995 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001996
Chris Lattner2188e402010-01-04 07:37:31 +00001997 if (ICI.isEquality()) {
1998 // If we are comparing against bits always shifted out, the
1999 // comparison cannot succeed.
2000 Constant *Comp =
2001 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
2002 ShAmt);
2003 if (Comp != RHS) {// Comparing against a bit that we know is zero.
2004 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00002005 Constant *Cst = Builder->getInt1(IsICMP_NE);
Sanjay Patel4b198802016-02-01 22:23:39 +00002006 return replaceInstUsesWith(ICI, Cst);
Chris Lattner2188e402010-01-04 07:37:31 +00002007 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002008
Chris Lattner98457102011-02-10 05:23:05 +00002009 // If the shift is NUW, then it is just shifting out zeros, no need for an
2010 // AND.
2011 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
2012 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2013 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002014
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002015 // If the shift is NSW and we compare to 0, then it is just shifting out
2016 // sign bits, no need for an AND either.
2017 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
2018 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2019 ConstantExpr::getLShr(RHS, ShAmt));
2020
Chris Lattner2188e402010-01-04 07:37:31 +00002021 if (LHSI->hasOneUse()) {
2022 // Otherwise strength reduce the shift into an and.
2023 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Jakub Staszakbddea112013-06-06 20:18:46 +00002024 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
2025 TypeBits - ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002026
Chris Lattner2188e402010-01-04 07:37:31 +00002027 Value *And =
2028 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
2029 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner98457102011-02-10 05:23:05 +00002030 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner2188e402010-01-04 07:37:31 +00002031 }
2032 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002033
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002034 // If this is a signed comparison to 0 and the shift is sign preserving,
2035 // use the shift LHS operand instead.
2036 ICmpInst::Predicate pred = ICI.getPredicate();
2037 if (isSignTest(pred, RHS) &&
2038 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
2039 return new ICmpInst(pred,
2040 LHSI->getOperand(0),
2041 Constant::getNullValue(RHS->getType()));
2042
Chris Lattner2188e402010-01-04 07:37:31 +00002043 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2044 bool TrueIfSigned = false;
2045 if (LHSI->hasOneUse() &&
2046 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
2047 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattner43273af2011-02-13 08:07:21 +00002048 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach129c52a2011-09-30 18:09:53 +00002049 APInt::getOneBitSet(TypeBits,
Chris Lattner43273af2011-02-13 08:07:21 +00002050 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002051 Value *And =
2052 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
2053 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2054 And, Constant::getNullValue(And->getType()));
2055 }
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002056
2057 // Transform (icmp pred iM (shl iM %v, N), CI)
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00002058 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
2059 // 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 +00002060 // This enables to get rid of the shift in favor of a trunc which can be
2061 // free on the target. It has the additional benefit of comparing to a
2062 // smaller constant, which will be target friendly.
2063 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00002064 if (LHSI->hasOneUse() &&
2065 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002066 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
2067 Constant *NCI = ConstantExpr::getTrunc(
2068 ConstantExpr::getAShr(RHS,
2069 ConstantInt::get(RHS->getType(), Amt)),
2070 NTy);
2071 return new ICmpInst(ICI.getPredicate(),
2072 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaison1fd843e2013-02-15 15:18:17 +00002073 NCI);
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002074 }
2075
Chris Lattner2188e402010-01-04 07:37:31 +00002076 break;
2077 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002078
Chris Lattner2188e402010-01-04 07:37:31 +00002079 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewycky174a7052011-02-28 08:31:40 +00002080 case Instruction::AShr: {
2081 // Handle equality comparisons of shift-by-constant.
2082 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
2083 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2084 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattnerd369f572011-02-13 07:43:07 +00002085 return Res;
Nick Lewycky174a7052011-02-28 08:31:40 +00002086 }
2087
2088 // Handle exact shr's.
2089 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
2090 if (RHSV.isMinValue())
2091 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
2092 }
Chris Lattner2188e402010-01-04 07:37:31 +00002093 break;
Nick Lewycky174a7052011-02-28 08:31:40 +00002094 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002095
Chris Lattner2188e402010-01-04 07:37:31 +00002096 case Instruction::SDiv:
2097 case Instruction::UDiv:
2098 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach129c52a2011-09-30 18:09:53 +00002099 // Fold this div into the comparison, producing a range check.
2100 // Determine, based on the divide type, what the range is being
2101 // checked. If there is an overflow on the low or high side, remember
Chris Lattner2188e402010-01-04 07:37:31 +00002102 // it, otherwise compute the range [low, hi) bounding the new value.
2103 // See: InsertRangeTest above for the kinds of replacements possible.
2104 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
2105 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
2106 DivRHS))
2107 return R;
2108 break;
2109
David Majnemerf2a9a512013-07-09 07:50:59 +00002110 case Instruction::Sub: {
2111 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
2112 if (!LHSC) break;
2113 const APInt &LHSV = LHSC->getValue();
2114
2115 // C1-X <u C2 -> (X|(C2-1)) == C1
2116 // iff C1 & (C2-1) == C2-1
2117 // C2 is a power of 2
2118 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
2119 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
2120 return new ICmpInst(ICmpInst::ICMP_EQ,
2121 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
2122 LHSC);
2123
David Majnemereeed73b2013-07-09 09:24:35 +00002124 // C1-X >u C2 -> (X|C2) != C1
David Majnemerf2a9a512013-07-09 07:50:59 +00002125 // iff C1 & C2 == C2
2126 // C2+1 is a power of 2
2127 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
2128 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
2129 return new ICmpInst(ICmpInst::ICMP_NE,
2130 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
2131 break;
2132 }
2133
Chris Lattner2188e402010-01-04 07:37:31 +00002134 case Instruction::Add:
2135 // Fold: icmp pred (add X, C1), C2
2136 if (!ICI.isEquality()) {
2137 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
2138 if (!LHSC) break;
2139 const APInt &LHSV = LHSC->getValue();
2140
2141 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
2142 .subtract(LHSV);
2143
2144 if (ICI.isSigned()) {
2145 if (CR.getLower().isSignBit()) {
2146 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002147 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00002148 } else if (CR.getUpper().isSignBit()) {
2149 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002150 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00002151 }
2152 } else {
2153 if (CR.getLower().isMinValue()) {
2154 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002155 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00002156 } else if (CR.getUpper().isMinValue()) {
2157 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002158 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00002159 }
2160 }
David Majnemerfa90a0b2013-07-08 11:53:08 +00002161
David Majnemerbafa5372013-07-09 07:58:32 +00002162 // X-C1 <u C2 -> (X & -C2) == C1
2163 // iff C1 & (C2-1) == 0
2164 // C2 is a power of 2
David Majnemerfa90a0b2013-07-08 11:53:08 +00002165 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
David Majnemerbafa5372013-07-09 07:58:32 +00002166 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
David Majnemerfa90a0b2013-07-08 11:53:08 +00002167 return new ICmpInst(ICmpInst::ICMP_EQ,
2168 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
2169 ConstantExpr::getNeg(LHSC));
David Majnemerbafa5372013-07-09 07:58:32 +00002170
David Majnemereeed73b2013-07-09 09:24:35 +00002171 // X-C1 >u C2 -> (X & ~C2) != C1
David Majnemerbafa5372013-07-09 07:58:32 +00002172 // iff C1 & C2 == 0
2173 // C2+1 is a power of 2
2174 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
2175 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
2176 return new ICmpInst(ICmpInst::ICMP_NE,
2177 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
2178 ConstantExpr::getNeg(LHSC));
Chris Lattner2188e402010-01-04 07:37:31 +00002179 }
2180 break;
2181 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002182
Chris Lattner2188e402010-01-04 07:37:31 +00002183 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
2184 if (ICI.isEquality()) {
2185 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002186
2187 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner2188e402010-01-04 07:37:31 +00002188 // the second operand is a constant, simplify a bit.
2189 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
2190 switch (BO->getOpcode()) {
2191 case Instruction::SRem:
2192 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2193 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
2194 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohman4ce1fb12010-04-08 23:03:40 +00002195 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner2188e402010-01-04 07:37:31 +00002196 Value *NewRem =
2197 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
2198 BO->getName());
2199 return new ICmpInst(ICI.getPredicate(), NewRem,
2200 Constant::getNullValue(BO->getType()));
2201 }
2202 }
2203 break;
2204 case Instruction::Add:
2205 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2206 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2207 if (BO->hasOneUse())
2208 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2209 ConstantExpr::getSub(RHS, BOp1C));
2210 } else if (RHSV == 0) {
2211 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2212 // efficiently invertible, or if the add has just this one use.
2213 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002214
Chris Lattner2188e402010-01-04 07:37:31 +00002215 if (Value *NegVal = dyn_castNegVal(BOp1))
2216 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner31b106d2011-04-26 20:02:45 +00002217 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner2188e402010-01-04 07:37:31 +00002218 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner31b106d2011-04-26 20:02:45 +00002219 if (BO->hasOneUse()) {
Chris Lattner2188e402010-01-04 07:37:31 +00002220 Value *Neg = Builder->CreateNeg(BOp1);
2221 Neg->takeName(BO);
2222 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
2223 }
2224 }
2225 break;
2226 case Instruction::Xor:
David Majnemer0f0abc72016-02-12 18:12:38 +00002227 if (BO->hasOneUse()) {
2228 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
2229 // For the xor case, we can xor two constants together, eliminating
2230 // the explicit xor.
2231 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2232 ConstantExpr::getXor(RHS, BOC));
2233 } else if (RHSV == 0) {
2234 // Replace ((xor A, B) != 0) with (A != B)
2235 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2236 BO->getOperand(1));
2237 }
Benjamin Kramerc9708492011-06-13 15:24:24 +00002238 }
Chris Lattner2188e402010-01-04 07:37:31 +00002239 break;
Benjamin Kramerc9708492011-06-13 15:24:24 +00002240 case Instruction::Sub:
David Majnemer0f0abc72016-02-12 18:12:38 +00002241 if (BO->hasOneUse()) {
2242 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
2243 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
Benjamin Kramerc9708492011-06-13 15:24:24 +00002244 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
David Majnemer0f0abc72016-02-12 18:12:38 +00002245 ConstantExpr::getSub(BOp0C, RHS));
2246 } else if (RHSV == 0) {
2247 // Replace ((sub A, B) != 0) with (A != B)
2248 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2249 BO->getOperand(1));
2250 }
Benjamin Kramerc9708492011-06-13 15:24:24 +00002251 }
2252 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002253 case Instruction::Or:
2254 // If bits are being or'd in that are not present in the constant we
2255 // are comparing against, then the comparison could never succeed!
Eli Friedman0428a612010-07-29 18:03:33 +00002256 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002257 Constant *NotCI = ConstantExpr::getNot(RHS);
2258 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00002259 return replaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Sanjay Patele998b912016-04-14 20:17:40 +00002260
2261 // Comparing if all bits outside of a constant mask are set?
2262 // Replace (X | C) == -1 with (X & ~C) == ~C.
2263 // This removes the -1 constant.
2264 if (BO->hasOneUse() && RHS->isAllOnesValue()) {
2265 Constant *NotBOC = ConstantExpr::getNot(BOC);
2266 Value *And = Builder->CreateAnd(BO->getOperand(0), NotBOC);
2267 return new ICmpInst(ICI.getPredicate(), And, NotBOC);
2268 }
Chris Lattner2188e402010-01-04 07:37:31 +00002269 }
2270 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002271
Chris Lattner2188e402010-01-04 07:37:31 +00002272 case Instruction::And:
2273 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2274 // If bits are being compared against that are and'd out, then the
2275 // comparison can never succeed!
2276 if ((RHSV & ~BOC->getValue()) != 0)
Sanjay Patel4b198802016-02-01 22:23:39 +00002277 return replaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002278
Chris Lattner2188e402010-01-04 07:37:31 +00002279 // If we have ((X & C) == C), turn it into ((X & C) != 0).
2280 if (RHS == BOC && RHSV.isPowerOf2())
2281 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
2282 ICmpInst::ICMP_NE, LHSI,
2283 Constant::getNullValue(RHS->getType()));
Benjamin Kramer9eca5fe2011-07-04 20:16:36 +00002284
2285 // Don't perform the following transforms if the AND has multiple uses
2286 if (!BO->hasOneUse())
2287 break;
2288
Chris Lattner2188e402010-01-04 07:37:31 +00002289 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
2290 if (BOC->getValue().isSignBit()) {
2291 Value *X = BO->getOperand(0);
2292 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002293 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00002294 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
2295 return new ICmpInst(pred, X, Zero);
2296 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002297
Chris Lattner2188e402010-01-04 07:37:31 +00002298 // ((X & ~7) == 0) --> X < 8
2299 if (RHSV == 0 && isHighOnes(BOC)) {
2300 Value *X = BO->getOperand(0);
2301 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002302 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00002303 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
2304 return new ICmpInst(pred, X, NegX);
2305 }
2306 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002307 break;
2308 case Instruction::Mul:
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00002309 if (RHSV == 0 && BO->hasNoSignedWrap()) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002310 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2311 // The trivial case (mul X, 0) is handled by InstSimplify
2312 // General case : (mul X, C) != 0 iff X != 0
2313 // (mul X, C) == 0 iff X == 0
2314 if (!BOC->isZero())
2315 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2316 Constant::getNullValue(RHS->getType()));
2317 }
2318 }
2319 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002320 default: break;
2321 }
2322 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
2323 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner54f4e392010-01-05 18:09:56 +00002324 switch (II->getIntrinsicID()) {
2325 case Intrinsic::bswap:
Chris Lattner2188e402010-01-04 07:37:31 +00002326 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00002327 ICI.setOperand(0, II->getArgOperand(0));
Jakub Staszakbddea112013-06-06 20:18:46 +00002328 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
Chris Lattner2188e402010-01-04 07:37:31 +00002329 return &ICI;
Chris Lattner54f4e392010-01-05 18:09:56 +00002330 case Intrinsic::ctlz:
2331 case Intrinsic::cttz:
2332 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
2333 if (RHSV == RHS->getType()->getBitWidth()) {
2334 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00002335 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00002336 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
2337 return &ICI;
2338 }
2339 break;
2340 case Intrinsic::ctpop:
2341 // popcount(A) == 0 -> A == 0 and likewise for !=
2342 if (RHS->isZero()) {
2343 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00002344 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00002345 ICI.setOperand(1, RHS);
2346 return &ICI;
2347 }
2348 break;
2349 default:
Duncan Sands41b4a6b2010-07-12 08:16:59 +00002350 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002351 }
2352 }
2353 }
Craig Topperf40110f2014-04-25 05:29:35 +00002354 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002355}
2356
2357/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
2358/// We only handle extending casts so far.
2359///
2360Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
2361 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
2362 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002363 Type *SrcTy = LHSCIOp->getType();
2364 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002365 Value *RHSCIOp;
2366
Jim Grosbach129c52a2011-09-30 18:09:53 +00002367 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00002368 // integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002369 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
2370 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002371 Value *RHSOp = nullptr;
Michael Liaod266b922015-02-13 04:51:26 +00002372 if (PtrToIntOperator *RHSC = dyn_cast<PtrToIntOperator>(ICI.getOperand(1))) {
2373 Value *RHSCIOp = RHSC->getOperand(0);
2374 if (RHSCIOp->getType()->getPointerAddressSpace() ==
2375 LHSCIOp->getType()->getPointerAddressSpace()) {
2376 RHSOp = RHSC->getOperand(0);
2377 // If the pointer types don't match, insert a bitcast.
2378 if (LHSCIOp->getType() != RHSOp->getType())
2379 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
2380 }
2381 } else if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1)))
Chris Lattner2188e402010-01-04 07:37:31 +00002382 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner2188e402010-01-04 07:37:31 +00002383
2384 if (RHSOp)
2385 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
2386 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002387
Chris Lattner2188e402010-01-04 07:37:31 +00002388 // The code below only handles extension cast instructions, so far.
2389 // Enforce this.
2390 if (LHSCI->getOpcode() != Instruction::ZExt &&
2391 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002392 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002393
2394 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
2395 bool isSignedCmp = ICI.isSigned();
2396
2397 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
2398 // Not an extension from the same type?
2399 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002400 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00002401 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002402
Chris Lattner2188e402010-01-04 07:37:31 +00002403 // If the signedness of the two casts doesn't agree (i.e. one is a sext
2404 // and the other is a zext), then we can't handle this.
2405 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00002406 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002407
2408 // Deal with equality cases early.
2409 if (ICI.isEquality())
2410 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
2411
2412 // A signed comparison of sign extended values simplifies into a
2413 // signed comparison.
2414 if (isSignedCmp && isSignedExt)
2415 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
2416
2417 // The other three cases all fold into an unsigned comparison.
2418 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
2419 }
2420
2421 // If we aren't dealing with a constant on the RHS, exit early
2422 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
2423 if (!CI)
Craig Topperf40110f2014-04-25 05:29:35 +00002424 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002425
2426 // Compute the constant that would happen if we truncated to SrcTy then
2427 // reextended to DestTy.
2428 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
2429 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
2430 Res1, DestTy);
2431
2432 // If the re-extended constant didn't change...
2433 if (Res2 == CI) {
2434 // Deal with equality cases early.
2435 if (ICI.isEquality())
2436 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
2437
2438 // A signed comparison of sign extended values simplifies into a
2439 // signed comparison.
2440 if (isSignedExt && isSignedCmp)
2441 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
2442
2443 // The other three cases all fold into an unsigned comparison.
2444 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
2445 }
2446
Jim Grosbach129c52a2011-09-30 18:09:53 +00002447 // The re-extended constant changed so the constant cannot be represented
Chris Lattner2188e402010-01-04 07:37:31 +00002448 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002449 // All the cases that fold to true or false will have already been handled
2450 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00002451
Duncan Sands8fb2c382011-01-20 13:21:55 +00002452 if (isSignedCmp || !isSignedExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002453 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002454
2455 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
2456 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002457
2458 // We're performing an unsigned comp with a sign extended value.
2459 // This is true if the input is >= 0. [aka >s -1]
2460 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
2461 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00002462
2463 // Finally, return the value computed.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002464 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Sanjay Patel4b198802016-02-01 22:23:39 +00002465 return replaceInstUsesWith(ICI, Result);
Chris Lattner2188e402010-01-04 07:37:31 +00002466
Duncan Sands8fb2c382011-01-20 13:21:55 +00002467 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00002468 return BinaryOperator::CreateNot(Result);
2469}
2470
Chris Lattneree61c1d2010-12-19 17:52:50 +00002471/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
2472/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00002473/// If this is of the form:
2474/// sum = a + b
2475/// if (sum+128 >u 255)
2476/// Then replace it with llvm.sadd.with.overflow.i8.
2477///
Chris Lattneree61c1d2010-12-19 17:52:50 +00002478static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2479 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00002480 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00002481 // The transformation we're trying to do here is to transform this into an
2482 // llvm.sadd.with.overflow. To do this, we have to replace the original add
2483 // with a narrower add, and discard the add-with-constant that is part of the
2484 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00002485
Chris Lattnerf29562d2010-12-19 17:59:02 +00002486 // In order to eliminate the add-with-constant, the compare can be its only
2487 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00002488 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00002489 if (!AddWithCst->hasOneUse()) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002490
Chris Lattnerc56c8452010-12-19 18:22:06 +00002491 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
Craig Topperf40110f2014-04-25 05:29:35 +00002492 if (!CI2->getValue().isPowerOf2()) return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002493 unsigned NewWidth = CI2->getValue().countTrailingZeros();
Craig Topperf40110f2014-04-25 05:29:35 +00002494 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002495
Chris Lattnerc56c8452010-12-19 18:22:06 +00002496 // The width of the new add formed is 1 more than the bias.
2497 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002498
Chris Lattnerc56c8452010-12-19 18:22:06 +00002499 // Check to see that CI1 is an all-ones value with NewWidth bits.
2500 if (CI1->getBitWidth() == NewWidth ||
2501 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
Craig Topperf40110f2014-04-25 05:29:35 +00002502 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002503
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002504 // This is only really a signed overflow check if the inputs have been
2505 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2506 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2507 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
Hal Finkel60db0582014-09-07 18:57:58 +00002508 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2509 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
Craig Topperf40110f2014-04-25 05:29:35 +00002510 return nullptr;
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002511
Jim Grosbach129c52a2011-09-30 18:09:53 +00002512 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00002513 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2514 // and truncates that discard the high bits of the add. Verify that this is
2515 // the case.
2516 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00002517 for (User *U : OrigAdd->users()) {
2518 if (U == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002519
Chris Lattnerc56c8452010-12-19 18:22:06 +00002520 // Only accept truncates for now. We would really like a nice recursive
2521 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2522 // chain to see which bits of a value are actually demanded. If the
2523 // original add had another add which was then immediately truncated, we
2524 // could still do the transformation.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002525 TruncInst *TI = dyn_cast<TruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00002526 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2527 return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002528 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002529
Chris Lattneree61c1d2010-12-19 17:52:50 +00002530 // If the pattern matches, truncate the inputs to the narrower type and
2531 // use the sadd_with_overflow intrinsic to efficiently compute both the
2532 // result and the overflow bit.
Jay Foadb804a2b2011-07-12 14:06:48 +00002533 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002534 Value *F = Intrinsic::getDeclaration(I.getModule(),
2535 Intrinsic::sadd_with_overflow, NewType);
Chris Lattner79874562010-12-19 18:35:09 +00002536
Chris Lattnerce2995a2010-12-19 18:38:44 +00002537 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002538
Chris Lattner79874562010-12-19 18:35:09 +00002539 // Put the new code above the original add, in case there are any uses of the
2540 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002541 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002542
Chris Lattner79874562010-12-19 18:35:09 +00002543 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2544 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
David Blaikieff6409d2015-05-18 22:13:54 +00002545 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
Chris Lattner79874562010-12-19 18:35:09 +00002546 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2547 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002548
Chris Lattneree61c1d2010-12-19 17:52:50 +00002549 // The inner add was the result of the narrow add, zero extended to the
2550 // wider type. Replace it with the result computed by the intrinsic.
Sanjay Patel4b198802016-02-01 22:23:39 +00002551 IC.replaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002552
Chris Lattner79874562010-12-19 18:35:09 +00002553 // The original icmp gets replaced with the overflow value.
2554 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00002555}
Chris Lattner2188e402010-01-04 07:37:31 +00002556
Sanjoy Dasb0984472015-04-08 04:27:22 +00002557bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
2558 Value *RHS, Instruction &OrigI,
2559 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00002560 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
2561 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002562
2563 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
2564 Result = OpResult;
2565 Overflow = OverflowVal;
2566 if (ReuseName)
2567 Result->takeName(&OrigI);
2568 return true;
2569 };
2570
Sanjoy Das6f5dca72015-08-28 19:09:31 +00002571 // If the overflow check was an add followed by a compare, the insertion point
2572 // may be pointing to the compare. We want to insert the new instructions
2573 // before the add in case there are uses of the add between the add and the
2574 // compare.
2575 Builder->SetInsertPoint(&OrigI);
2576
Sanjoy Dasb0984472015-04-08 04:27:22 +00002577 switch (OCF) {
2578 case OCF_INVALID:
2579 llvm_unreachable("bad overflow check kind!");
2580
2581 case OCF_UNSIGNED_ADD: {
2582 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
2583 if (OR == OverflowResult::NeverOverflows)
2584 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
2585 true);
2586
2587 if (OR == OverflowResult::AlwaysOverflows)
2588 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
2589 }
2590 // FALL THROUGH uadd into sadd
2591 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002592 // X + 0 -> {X, false}
2593 if (match(RHS, m_Zero()))
2594 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002595
2596 // We can strength reduce this signed add into a regular add if we can prove
2597 // that it will never overflow.
2598 if (OCF == OCF_SIGNED_ADD)
2599 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
2600 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
2601 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00002602 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002603 }
2604
2605 case OCF_UNSIGNED_SUB:
2606 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002607 // X - 0 -> {X, false}
2608 if (match(RHS, m_Zero()))
2609 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002610
2611 if (OCF == OCF_SIGNED_SUB) {
2612 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
2613 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
2614 true);
2615 } else {
2616 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
2617 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
2618 true);
2619 }
2620 break;
2621 }
2622
2623 case OCF_UNSIGNED_MUL: {
2624 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
2625 if (OR == OverflowResult::NeverOverflows)
2626 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
2627 true);
2628 if (OR == OverflowResult::AlwaysOverflows)
2629 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
2630 } // FALL THROUGH
2631 case OCF_SIGNED_MUL:
2632 // X * undef -> undef
2633 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00002634 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002635
David Majnemer27e89ba2015-05-21 23:04:21 +00002636 // X * 0 -> {0, false}
2637 if (match(RHS, m_Zero()))
2638 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002639
David Majnemer27e89ba2015-05-21 23:04:21 +00002640 // X * 1 -> {X, false}
2641 if (match(RHS, m_One()))
2642 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002643
2644 if (OCF == OCF_SIGNED_MUL)
2645 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
2646 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
2647 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00002648 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002649 }
2650
2651 return false;
2652}
2653
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002654/// \brief Recognize and process idiom involving test for multiplication
2655/// overflow.
2656///
2657/// The caller has matched a pattern of the form:
2658/// I = cmp u (mul(zext A, zext B), V
2659/// The function checks if this is a test for overflow and if so replaces
2660/// multiplication with call to 'mul.with.overflow' intrinsic.
2661///
2662/// \param I Compare instruction.
2663/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2664/// the compare instruction. Must be of integer type.
2665/// \param OtherVal The other argument of compare instruction.
2666/// \returns Instruction which must replace the compare instruction, NULL if no
2667/// replacement required.
2668static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2669 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00002670 // Don't bother doing this transformation for pointers, don't do it for
2671 // vectors.
2672 if (!isa<IntegerType>(MulVal->getType()))
2673 return nullptr;
2674
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002675 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2676 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00002677 auto *MulInstr = dyn_cast<Instruction>(MulVal);
2678 if (!MulInstr)
2679 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002680 assert(MulInstr->getOpcode() == Instruction::Mul);
2681
David Majnemer634ca232014-11-01 23:46:05 +00002682 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
2683 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002684 assert(LHS->getOpcode() == Instruction::ZExt);
2685 assert(RHS->getOpcode() == Instruction::ZExt);
2686 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2687
2688 // Calculate type and width of the result produced by mul.with.overflow.
2689 Type *TyA = A->getType(), *TyB = B->getType();
2690 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2691 WidthB = TyB->getPrimitiveSizeInBits();
2692 unsigned MulWidth;
2693 Type *MulType;
2694 if (WidthB > WidthA) {
2695 MulWidth = WidthB;
2696 MulType = TyB;
2697 } else {
2698 MulWidth = WidthA;
2699 MulType = TyA;
2700 }
2701
2702 // In order to replace the original mul with a narrower mul.with.overflow,
2703 // all uses must ignore upper bits of the product. The number of used low
2704 // bits must be not greater than the width of mul.with.overflow.
2705 if (MulVal->hasNUsesOrMore(2))
2706 for (User *U : MulVal->users()) {
2707 if (U == &I)
2708 continue;
2709 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2710 // Check if truncation ignores bits above MulWidth.
2711 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2712 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002713 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002714 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2715 // Check if AND ignores bits above MulWidth.
2716 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00002717 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002718 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2719 const APInt &CVal = CI->getValue();
2720 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002721 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002722 }
2723 } else {
2724 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00002725 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002726 }
2727 }
2728
2729 // Recognize patterns
2730 switch (I.getPredicate()) {
2731 case ICmpInst::ICMP_EQ:
2732 case ICmpInst::ICMP_NE:
2733 // Recognize pattern:
2734 // mulval = mul(zext A, zext B)
2735 // cmp eq/neq mulval, zext trunc mulval
2736 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2737 if (Zext->hasOneUse()) {
2738 Value *ZextArg = Zext->getOperand(0);
2739 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2740 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2741 break; //Recognized
2742 }
2743
2744 // Recognize pattern:
2745 // mulval = mul(zext A, zext B)
2746 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2747 ConstantInt *CI;
2748 Value *ValToMask;
2749 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2750 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00002751 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002752 const APInt &CVal = CI->getValue() + 1;
2753 if (CVal.isPowerOf2()) {
2754 unsigned MaskWidth = CVal.logBase2();
2755 if (MaskWidth == MulWidth)
2756 break; // Recognized
2757 }
2758 }
Craig Topperf40110f2014-04-25 05:29:35 +00002759 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002760
2761 case ICmpInst::ICMP_UGT:
2762 // Recognize pattern:
2763 // mulval = mul(zext A, zext B)
2764 // cmp ugt mulval, max
2765 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2766 APInt MaxVal = APInt::getMaxValue(MulWidth);
2767 MaxVal = MaxVal.zext(CI->getBitWidth());
2768 if (MaxVal.eq(CI->getValue()))
2769 break; // Recognized
2770 }
Craig Topperf40110f2014-04-25 05:29:35 +00002771 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002772
2773 case ICmpInst::ICMP_UGE:
2774 // Recognize pattern:
2775 // mulval = mul(zext A, zext B)
2776 // cmp uge mulval, max+1
2777 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2778 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2779 if (MaxVal.eq(CI->getValue()))
2780 break; // Recognized
2781 }
Craig Topperf40110f2014-04-25 05:29:35 +00002782 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002783
2784 case ICmpInst::ICMP_ULE:
2785 // Recognize pattern:
2786 // mulval = mul(zext A, zext B)
2787 // cmp ule mulval, max
2788 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2789 APInt MaxVal = APInt::getMaxValue(MulWidth);
2790 MaxVal = MaxVal.zext(CI->getBitWidth());
2791 if (MaxVal.eq(CI->getValue()))
2792 break; // Recognized
2793 }
Craig Topperf40110f2014-04-25 05:29:35 +00002794 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002795
2796 case ICmpInst::ICMP_ULT:
2797 // Recognize pattern:
2798 // mulval = mul(zext A, zext B)
2799 // cmp ule mulval, max + 1
2800 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002801 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002802 if (MaxVal.eq(CI->getValue()))
2803 break; // Recognized
2804 }
Craig Topperf40110f2014-04-25 05:29:35 +00002805 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002806
2807 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002808 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002809 }
2810
2811 InstCombiner::BuilderTy *Builder = IC.Builder;
2812 Builder->SetInsertPoint(MulInstr);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002813
2814 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2815 Value *MulA = A, *MulB = B;
2816 if (WidthA < MulWidth)
2817 MulA = Builder->CreateZExt(A, MulType);
2818 if (WidthB < MulWidth)
2819 MulB = Builder->CreateZExt(B, MulType);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002820 Value *F = Intrinsic::getDeclaration(I.getModule(),
2821 Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00002822 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002823 IC.Worklist.Add(MulInstr);
2824
2825 // If there are uses of mul result other than the comparison, we know that
2826 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002827 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002828 if (MulVal->hasNUsesOrMore(2)) {
2829 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2830 for (User *U : MulVal->users()) {
2831 if (U == &I || U == OtherVal)
2832 continue;
2833 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2834 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
Sanjay Patel4b198802016-02-01 22:23:39 +00002835 IC.replaceInstUsesWith(*TI, Mul);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002836 else
2837 TI->setOperand(0, Mul);
2838 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2839 assert(BO->getOpcode() == Instruction::And);
2840 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2841 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2842 APInt ShortMask = CI->getValue().trunc(MulWidth);
2843 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2844 Instruction *Zext =
2845 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2846 IC.Worklist.Add(Zext);
Sanjay Patel4b198802016-02-01 22:23:39 +00002847 IC.replaceInstUsesWith(*BO, Zext);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002848 } else {
2849 llvm_unreachable("Unexpected Binary operation");
2850 }
2851 IC.Worklist.Add(cast<Instruction>(U));
2852 }
2853 }
2854 if (isa<Instruction>(OtherVal))
2855 IC.Worklist.Add(cast<Instruction>(OtherVal));
2856
2857 // The original icmp gets replaced with the overflow value, maybe inverted
2858 // depending on predicate.
2859 bool Inverse = false;
2860 switch (I.getPredicate()) {
2861 case ICmpInst::ICMP_NE:
2862 break;
2863 case ICmpInst::ICMP_EQ:
2864 Inverse = true;
2865 break;
2866 case ICmpInst::ICMP_UGT:
2867 case ICmpInst::ICMP_UGE:
2868 if (I.getOperand(0) == MulVal)
2869 break;
2870 Inverse = true;
2871 break;
2872 case ICmpInst::ICMP_ULT:
2873 case ICmpInst::ICMP_ULE:
2874 if (I.getOperand(1) == MulVal)
2875 break;
2876 Inverse = true;
2877 break;
2878 default:
2879 llvm_unreachable("Unexpected predicate");
2880 }
2881 if (Inverse) {
2882 Value *Res = Builder->CreateExtractValue(Call, 1);
2883 return BinaryOperator::CreateNot(Res);
2884 }
2885
2886 return ExtractValueInst::Create(Call, 1);
2887}
2888
Owen Andersond490c2d2011-01-11 00:36:45 +00002889// DemandedBitsLHSMask - When performing a comparison against a constant,
2890// it is possible that not all the bits in the LHS are demanded. This helper
2891// method computes the mask that IS demanded.
2892static APInt DemandedBitsLHSMask(ICmpInst &I,
2893 unsigned BitWidth, bool isSignCheck) {
2894 if (isSignCheck)
2895 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002896
Owen Andersond490c2d2011-01-11 00:36:45 +00002897 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2898 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00002899 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002900
Owen Andersond490c2d2011-01-11 00:36:45 +00002901 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002902 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00002903 // correspond to the trailing ones of the comparand. The value of these
2904 // bits doesn't impact the outcome of the comparison, because any value
2905 // greater than the RHS must differ in a bit higher than these due to carry.
2906 case ICmpInst::ICMP_UGT: {
2907 unsigned trailingOnes = RHS.countTrailingOnes();
2908 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2909 return ~lowBitsSet;
2910 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002911
Owen Andersond490c2d2011-01-11 00:36:45 +00002912 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2913 // Any value less than the RHS must differ in a higher bit because of carries.
2914 case ICmpInst::ICMP_ULT: {
2915 unsigned trailingZeros = RHS.countTrailingZeros();
2916 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2917 return ~lowBitsSet;
2918 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002919
Owen Andersond490c2d2011-01-11 00:36:45 +00002920 default:
2921 return APInt::getAllOnesValue(BitWidth);
2922 }
Owen Andersond490c2d2011-01-11 00:36:45 +00002923}
Chris Lattner2188e402010-01-04 07:37:31 +00002924
Quentin Colombet5ab55552013-09-09 20:56:48 +00002925/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2926/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00002927/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00002928/// as subtract operands and their positions in those instructions.
2929/// The rational is that several architectures use the same instruction for
2930/// both subtract and cmp, thus it is better if the order of those operands
2931/// match.
2932/// \return true if Op0 and Op1 should be swapped.
2933static bool swapMayExposeCSEOpportunities(const Value * Op0,
2934 const Value * Op1) {
2935 // Filter out pointer value as those cannot appears directly in subtract.
2936 // FIXME: we may want to go through inttoptrs or bitcasts.
2937 if (Op0->getType()->isPointerTy())
2938 return false;
2939 // Count every uses of both Op0 and Op1 in a subtract.
2940 // Each time Op0 is the first operand, count -1: swapping is bad, the
2941 // subtract has already the same layout as the compare.
2942 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00002943 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002944 // At the end, if the benefit is greater than 0, Op0 should come second to
2945 // expose more CSE opportunities.
2946 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002947 for (const User *U : Op0->users()) {
2948 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002949 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2950 continue;
2951 // If Op0 is the first argument, this is not beneficial to swap the
2952 // arguments.
2953 int LocalSwapBenefits = -1;
2954 unsigned Op1Idx = 1;
2955 if (BinOp->getOperand(Op1Idx) == Op0) {
2956 Op1Idx = 0;
2957 LocalSwapBenefits = 1;
2958 }
2959 if (BinOp->getOperand(Op1Idx) != Op1)
2960 continue;
2961 GlobalSwapBenefits += LocalSwapBenefits;
2962 }
2963 return GlobalSwapBenefits > 0;
2964}
2965
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00002966/// \brief Check that one use is in the same block as the definition and all
2967/// other uses are in blocks dominated by a given block
2968///
2969/// \param DI Definition
2970/// \param UI Use
2971/// \param DB Block that must dominate all uses of \p DI outside
2972/// the parent block
2973/// \return true when \p UI is the only use of \p DI in the parent block
2974/// and all other uses of \p DI are in blocks dominated by \p DB.
2975///
2976bool InstCombiner::dominatesAllUses(const Instruction *DI,
2977 const Instruction *UI,
2978 const BasicBlock *DB) const {
2979 assert(DI && UI && "Instruction not defined\n");
2980 // ignore incomplete definitions
2981 if (!DI->getParent())
2982 return false;
2983 // DI and UI must be in the same block
2984 if (DI->getParent() != UI->getParent())
2985 return false;
2986 // Protect from self-referencing blocks
2987 if (DI->getParent() == DB)
2988 return false;
2989 // DominatorTree available?
2990 if (!DT)
2991 return false;
2992 for (const User *U : DI->users()) {
2993 auto *Usr = cast<Instruction>(U);
2994 if (Usr != UI && !DT->dominates(DB, Usr->getParent()))
2995 return false;
2996 }
2997 return true;
2998}
2999
3000///
3001/// true when the instruction sequence within a block is select-cmp-br.
3002///
3003static bool isChainSelectCmpBranch(const SelectInst *SI) {
3004 const BasicBlock *BB = SI->getParent();
3005 if (!BB)
3006 return false;
3007 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
3008 if (!BI || BI->getNumSuccessors() != 2)
3009 return false;
3010 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
3011 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
3012 return false;
3013 return true;
3014}
3015
3016///
3017/// \brief True when a select result is replaced by one of its operands
3018/// in select-icmp sequence. This will eventually result in the elimination
3019/// of the select.
3020///
3021/// \param SI Select instruction
3022/// \param Icmp Compare instruction
3023/// \param SIOpd Operand that replaces the select
3024///
3025/// Notes:
3026/// - The replacement is global and requires dominator information
3027/// - The caller is responsible for the actual replacement
3028///
3029/// Example:
3030///
3031/// entry:
3032/// %4 = select i1 %3, %C* %0, %C* null
3033/// %5 = icmp eq %C* %4, null
3034/// br i1 %5, label %9, label %7
3035/// ...
3036/// ; <label>:7 ; preds = %entry
3037/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
3038/// ...
3039///
3040/// can be transformed to
3041///
3042/// %5 = icmp eq %C* %0, null
3043/// %6 = select i1 %3, i1 %5, i1 true
3044/// br i1 %6, label %9, label %7
3045/// ...
3046/// ; <label>:7 ; preds = %entry
3047/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
3048///
3049/// Similar when the first operand of the select is a constant or/and
3050/// the compare is for not equal rather than equal.
3051///
3052/// NOTE: The function is only called when the select and compare constants
3053/// are equal, the optimization can work only for EQ predicates. This is not a
3054/// major restriction since a NE compare should be 'normalized' to an equal
3055/// compare, which usually happens in the combiner and test case
3056/// select-cmp-br.ll
3057/// checks for it.
3058bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
3059 const ICmpInst *Icmp,
3060 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00003061 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003062 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
3063 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
3064 // The check for the unique predecessor is not the best that can be
3065 // done. But it protects efficiently against cases like when SI's
3066 // home block has two successors, Succ and Succ1, and Succ1 predecessor
3067 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
3068 // replaced can be reached on either path. So the uniqueness check
3069 // guarantees that the path all uses of SI (outside SI's parent) are on
3070 // is disjoint from all other paths out of SI. But that information
3071 // is more expensive to compute, and the trade-off here is in favor
3072 // of compile-time.
3073 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
3074 NumSel++;
3075 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
3076 return true;
3077 }
3078 }
3079 return false;
3080}
3081
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003082/// If we have an icmp le or icmp ge instruction with a constant operand, turn
3083/// it into the appropriate icmp lt or icmp gt instruction. This transform
3084/// allows them to be folded in visitICmpInst.
3085static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I,
3086 InstCombiner::BuilderTy &Builder) {
3087 Value *Op0 = I.getOperand(0);
3088 Value *Op1 = I.getOperand(1);
3089
3090 if (auto *Op1C = dyn_cast<ConstantInt>(Op1)) {
3091 // For scalars, SimplifyICmpInst has already handled the edge cases for us,
3092 // so we just assert on them.
3093 APInt Op1Val = Op1C->getValue();
3094 switch (I.getPredicate()) {
3095 case ICmpInst::ICMP_ULE:
3096 assert(!Op1C->isMaxValue(false)); // A <=u MAX -> TRUE
3097 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, Builder.getInt(Op1Val + 1));
3098 case ICmpInst::ICMP_SLE:
3099 assert(!Op1C->isMaxValue(true)); // A <=s MAX -> TRUE
3100 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Builder.getInt(Op1Val + 1));
3101 case ICmpInst::ICMP_UGE:
3102 assert(!Op1C->isMinValue(false)); // A >=u MIN -> TRUE
3103 return new ICmpInst(ICmpInst::ICMP_UGT, Op0, Builder.getInt(Op1Val - 1));
3104 case ICmpInst::ICMP_SGE:
3105 assert(!Op1C->isMinValue(true)); // A >=s MIN -> TRUE
3106 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, Builder.getInt(Op1Val - 1));
3107 default:
3108 break;
3109 }
3110 }
3111
3112 // TODO: Handle vectors.
3113
3114 return nullptr;
3115}
3116
Chris Lattner2188e402010-01-04 07:37:31 +00003117Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
3118 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00003119 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003120 unsigned Op0Cplxity = getComplexity(Op0);
3121 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003122
Chris Lattner2188e402010-01-04 07:37:31 +00003123 /// Orders the operands of the compare so that they are listed from most
3124 /// complex to least complex. This puts constants before unary operators,
3125 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003126 if (Op0Cplxity < Op1Cplxity ||
3127 (Op0Cplxity == Op1Cplxity &&
3128 swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003129 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00003130 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003131 Changed = true;
3132 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003133
Jingyue Wu5e34ce32015-06-25 20:14:47 +00003134 if (Value *V =
3135 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00003136 return replaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003137
Pete Cooperbc5c5242011-12-01 03:58:40 +00003138 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00003139 // ie, abs(val) != 0 -> val != 0
Pete Cooperbc5c5242011-12-01 03:58:40 +00003140 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
3141 {
Pete Cooperfdddc272011-12-01 19:13:26 +00003142 Value *Cond, *SelectTrue, *SelectFalse;
3143 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00003144 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003145 if (Value *V = dyn_castNegVal(SelectTrue)) {
3146 if (V == SelectFalse)
3147 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
3148 }
3149 else if (Value *V = dyn_castNegVal(SelectFalse)) {
3150 if (V == SelectTrue)
3151 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00003152 }
3153 }
3154 }
3155
Chris Lattner229907c2011-07-18 04:54:35 +00003156 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00003157
3158 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sands9dff9be2010-02-15 16:12:20 +00003159 if (Ty->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00003160 switch (I.getPredicate()) {
3161 default: llvm_unreachable("Invalid icmp instruction!");
3162 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
3163 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
3164 return BinaryOperator::CreateNot(Xor);
3165 }
3166 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
3167 return BinaryOperator::CreateXor(Op0, Op1);
3168
3169 case ICmpInst::ICMP_UGT:
3170 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
3171 // FALL THROUGH
3172 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
3173 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
3174 return BinaryOperator::CreateAnd(Not, Op1);
3175 }
3176 case ICmpInst::ICMP_SGT:
3177 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
3178 // FALL THROUGH
3179 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
3180 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
3181 return BinaryOperator::CreateAnd(Not, Op0);
3182 }
3183 case ICmpInst::ICMP_UGE:
3184 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
3185 // FALL THROUGH
3186 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
3187 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
3188 return BinaryOperator::CreateOr(Not, Op1);
3189 }
3190 case ICmpInst::ICMP_SGE:
3191 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
3192 // FALL THROUGH
3193 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
3194 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
3195 return BinaryOperator::CreateOr(Not, Op0);
3196 }
3197 }
3198 }
3199
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003200 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I, *Builder))
3201 return NewICmp;
3202
Chris Lattner2188e402010-01-04 07:37:31 +00003203 unsigned BitWidth = 0;
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003204 if (Ty->isIntOrIntVectorTy())
Chris Lattner2188e402010-01-04 07:37:31 +00003205 BitWidth = Ty->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003206 else // Get pointer size.
3207 BitWidth = DL.getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00003208
Chris Lattner2188e402010-01-04 07:37:31 +00003209 bool isSignBit = false;
3210
3211 // See if we are doing a comparison with a constant.
3212 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00003213 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003214
Owen Anderson1294ea72010-12-17 18:08:00 +00003215 // Match the following pattern, which is a common idiom when writing
3216 // overflow-safe integer arithmetic function. The source performs an
3217 // addition in wider type, and explicitly checks for overflow using
3218 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
3219 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00003220 //
3221 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00003222 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00003223 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003224 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00003225 // sum = a + b
3226 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00003227 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00003228 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00003229 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00003230 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00003231 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00003232 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00003233 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003234
Philip Reamesec8a8b52016-03-09 21:05:07 +00003235 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
3236 if (CI->isZero() && I.getPredicate() == ICmpInst::ICMP_SGT)
3237 if (auto *SI = dyn_cast<SelectInst>(Op0)) {
3238 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
3239 if (SPR.Flavor == SPF_SMIN) {
Philip Reames8f12eba2016-03-09 21:31:47 +00003240 if (isKnownPositive(A, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003241 return new ICmpInst(I.getPredicate(), B, CI);
Philip Reames8f12eba2016-03-09 21:31:47 +00003242 if (isKnownPositive(B, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003243 return new ICmpInst(I.getPredicate(), A, CI);
3244 }
3245 }
3246
3247
David Majnemera0afb552015-01-14 19:26:56 +00003248 // The following transforms are only 'worth it' if the only user of the
3249 // subtraction is the icmp.
3250 if (Op0->hasOneUse()) {
3251 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
3252 if (I.isEquality() && CI->isZero() &&
3253 match(Op0, m_Sub(m_Value(A), m_Value(B))))
3254 return new ICmpInst(I.getPredicate(), A, B);
3255
3256 // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
3257 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
3258 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3259 return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
3260
3261 // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
3262 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
3263 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3264 return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
3265
3266 // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
3267 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
3268 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3269 return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
3270
3271 // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
3272 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
3273 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3274 return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
Chris Lattner2188e402010-01-04 07:37:31 +00003275 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003276
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003277 if (I.isEquality()) {
3278 ConstantInt *CI2;
3279 if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
3280 match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
David Majnemer59939ac2014-10-19 08:23:08 +00003281 // (icmp eq/ne (ashr/lshr const2, A), const1)
David Majnemer2abb8182014-10-25 07:13:13 +00003282 if (Instruction *Inst = FoldICmpCstShrCst(I, Op0, A, CI, CI2))
3283 return Inst;
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003284 }
David Majnemer59939ac2014-10-19 08:23:08 +00003285 if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
3286 // (icmp eq/ne (shl const2, A), const1)
David Majnemer2abb8182014-10-25 07:13:13 +00003287 if (Instruction *Inst = FoldICmpCstShlCst(I, Op0, A, CI, CI2))
3288 return Inst;
David Majnemer59939ac2014-10-19 08:23:08 +00003289 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003290 }
3291
Chris Lattner2188e402010-01-04 07:37:31 +00003292 // If this comparison is a normal comparison, it demands all
3293 // bits, if it is a sign bit comparison, it only demands the sign bit.
3294 bool UnusedBit;
3295 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
Balaram Makam569eaec2016-05-04 21:32:14 +00003296
3297 // Canonicalize icmp instructions based on dominating conditions.
3298 BasicBlock *Parent = I.getParent();
3299 BasicBlock *Dom = Parent->getSinglePredecessor();
3300 auto *BI = Dom ? dyn_cast<BranchInst>(Dom->getTerminator()) : nullptr;
3301 ICmpInst::Predicate Pred;
3302 BasicBlock *TrueBB, *FalseBB;
3303 ConstantInt *CI2;
3304 if (BI && match(BI, m_Br(m_ICmp(Pred, m_Specific(Op0), m_ConstantInt(CI2)),
3305 TrueBB, FalseBB)) &&
3306 TrueBB != FalseBB) {
3307 ConstantRange CR = ConstantRange::makeAllowedICmpRegion(I.getPredicate(),
3308 CI->getValue());
3309 ConstantRange DominatingCR =
3310 (Parent == TrueBB)
3311 ? ConstantRange::makeExactICmpRegion(Pred, CI2->getValue())
3312 : ConstantRange::makeExactICmpRegion(
3313 CmpInst::getInversePredicate(Pred), CI2->getValue());
3314 ConstantRange Intersection = DominatingCR.intersectWith(CR);
3315 ConstantRange Difference = DominatingCR.difference(CR);
3316 if (Intersection.isEmptySet())
3317 return replaceInstUsesWith(I, Builder->getFalse());
3318 if (Difference.isEmptySet())
3319 return replaceInstUsesWith(I, Builder->getTrue());
3320 // Canonicalizing a sign bit comparison that gets used in a branch,
3321 // pessimizes codegen by generating branch on zero instruction instead
3322 // of a test and branch. So we avoid canonicalizing in such situations
3323 // because test and branch instruction has better branch displacement
3324 // than compare and branch instruction.
3325 if (!isBranchOnSignBitCheck(I, isSignBit) && !I.isEquality()) {
3326 if (auto *AI = Intersection.getSingleElement())
3327 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Builder->getInt(*AI));
3328 if (auto *AD = Difference.getSingleElement())
3329 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Builder->getInt(*AD));
3330 }
3331 }
Chris Lattner2188e402010-01-04 07:37:31 +00003332 }
3333
3334 // See if we can fold the comparison based on range information we can get
3335 // by checking whether bits are known to be zero or one in the input.
3336 if (BitWidth != 0) {
3337 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
3338 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
3339
3340 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersond490c2d2011-01-11 00:36:45 +00003341 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner2188e402010-01-04 07:37:31 +00003342 Op0KnownZero, Op0KnownOne, 0))
3343 return &I;
3344 if (SimplifyDemandedBits(I.getOperandUse(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003345 APInt::getAllOnesValue(BitWidth), Op1KnownZero,
3346 Op1KnownOne, 0))
Chris Lattner2188e402010-01-04 07:37:31 +00003347 return &I;
3348
3349 // Given the known and unknown bits, compute a range that the LHS could be
3350 // in. Compute the Min, Max and RHS values based on the known bits. For the
3351 // EQ and NE we use unsigned values.
3352 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
3353 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
3354 if (I.isSigned()) {
3355 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3356 Op0Min, Op0Max);
3357 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3358 Op1Min, Op1Max);
3359 } else {
3360 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3361 Op0Min, Op0Max);
3362 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3363 Op1Min, Op1Max);
3364 }
3365
3366 // If Min and Max are known to be the same, then SimplifyDemandedBits
3367 // figured out that the LHS is a constant. Just constant fold this now so
3368 // that code below can assume that Min != Max.
3369 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
3370 return new ICmpInst(I.getPredicate(),
Nick Lewycky92db8e82011-03-06 03:36:19 +00003371 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003372 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
3373 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewycky92db8e82011-03-06 03:36:19 +00003374 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner2188e402010-01-04 07:37:31 +00003375
3376 // Based on the range information we know about the LHS, see if we can
Nick Lewycky6b4454192011-02-28 06:20:05 +00003377 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner2188e402010-01-04 07:37:31 +00003378 switch (I.getPredicate()) {
3379 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattnerf7e89612010-11-21 06:44:42 +00003380 case ICmpInst::ICMP_EQ: {
Chris Lattner2188e402010-01-04 07:37:31 +00003381 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003382 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003383
Chris Lattnerf7e89612010-11-21 06:44:42 +00003384 // If all bits are known zero except for one, then we know at most one
3385 // bit is set. If the comparison is against zero, then this is a check
3386 // to see if *that* bit is set.
3387 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003388 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003389 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003390 Value *LHS = nullptr;
3391 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003392 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3393 LHSC->getValue() != Op0KnownZeroInverted)
3394 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003395
Chris Lattnerf7e89612010-11-21 06:44:42 +00003396 // 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 +00003397 // then turn "((1 << x)&8) == 0" into "x != 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003398 // or turn "((1 << x)&7) == 0" into "x > 2".
Craig Topperf40110f2014-04-25 05:29:35 +00003399 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003400 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003401 APInt ValToCheck = Op0KnownZeroInverted;
3402 if (ValToCheck.isPowerOf2()) {
3403 unsigned CmpVal = ValToCheck.countTrailingZeros();
3404 return new ICmpInst(ICmpInst::ICMP_NE, X,
3405 ConstantInt::get(X->getType(), CmpVal));
3406 } else if ((++ValToCheck).isPowerOf2()) {
3407 unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
3408 return new ICmpInst(ICmpInst::ICMP_UGT, X,
3409 ConstantInt::get(X->getType(), CmpVal));
3410 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003411 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003412
Chris Lattnerf7e89612010-11-21 06:44:42 +00003413 // 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 +00003414 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattner98457102011-02-10 05:23:05 +00003415 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003416 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003417 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003418 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner98457102011-02-10 05:23:05 +00003419 ConstantInt::get(X->getType(),
3420 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003421 }
Chris Lattner2188e402010-01-04 07:37:31 +00003422 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003423 }
3424 case ICmpInst::ICMP_NE: {
Chris Lattner2188e402010-01-04 07:37:31 +00003425 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003426 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003427
Chris Lattnerf7e89612010-11-21 06:44:42 +00003428 // If all bits are known zero except for one, then we know at most one
3429 // bit is set. If the comparison is against zero, then this is a check
3430 // to see if *that* bit is set.
3431 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003432 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003433 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003434 Value *LHS = nullptr;
3435 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003436 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3437 LHSC->getValue() != Op0KnownZeroInverted)
3438 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003439
Chris Lattnerf7e89612010-11-21 06:44:42 +00003440 // 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 +00003441 // then turn "((1 << x)&8) != 0" into "x == 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003442 // or turn "((1 << x)&7) != 0" into "x < 3".
Craig Topperf40110f2014-04-25 05:29:35 +00003443 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003444 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003445 APInt ValToCheck = Op0KnownZeroInverted;
3446 if (ValToCheck.isPowerOf2()) {
3447 unsigned CmpVal = ValToCheck.countTrailingZeros();
3448 return new ICmpInst(ICmpInst::ICMP_EQ, X,
3449 ConstantInt::get(X->getType(), CmpVal));
3450 } else if ((++ValToCheck).isPowerOf2()) {
3451 unsigned CmpVal = ValToCheck.countTrailingZeros();
3452 return new ICmpInst(ICmpInst::ICMP_ULT, X,
3453 ConstantInt::get(X->getType(), CmpVal));
3454 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003455 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003456
Chris Lattnerf7e89612010-11-21 06:44:42 +00003457 // 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 +00003458 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattner98457102011-02-10 05:23:05 +00003459 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003460 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003461 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003462 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner98457102011-02-10 05:23:05 +00003463 ConstantInt::get(X->getType(),
3464 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003465 }
Chris Lattner2188e402010-01-04 07:37:31 +00003466 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003467 }
Chris Lattner2188e402010-01-04 07:37:31 +00003468 case ICmpInst::ICMP_ULT:
3469 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003470 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003471 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003472 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003473 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
3474 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3475 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3476 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
3477 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003478 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003479
3480 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
3481 if (CI->isMinValue(true))
3482 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
3483 Constant::getAllOnesValue(Op0->getType()));
3484 }
3485 break;
3486 case ICmpInst::ICMP_UGT:
3487 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003488 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003489 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003490 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003491
3492 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
3493 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3494 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3495 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
3496 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003497 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003498
3499 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
3500 if (CI->isMaxValue(true))
3501 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
3502 Constant::getNullValue(Op0->getType()));
3503 }
3504 break;
3505 case ICmpInst::ICMP_SLT:
3506 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003507 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003508 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003509 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003510 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
3511 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3512 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3513 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
3514 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003515 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003516 }
3517 break;
3518 case ICmpInst::ICMP_SGT:
3519 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003520 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003521 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003522 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003523
3524 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
3525 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3526 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3527 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
3528 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003529 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003530 }
3531 break;
3532 case ICmpInst::ICMP_SGE:
3533 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
3534 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003535 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003536 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003537 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003538 break;
3539 case ICmpInst::ICMP_SLE:
3540 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
3541 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003542 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003543 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003544 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003545 break;
3546 case ICmpInst::ICMP_UGE:
3547 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
3548 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003549 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003550 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003551 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003552 break;
3553 case ICmpInst::ICMP_ULE:
3554 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
3555 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003556 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003557 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003558 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003559 break;
3560 }
3561
3562 // Turn a signed comparison into an unsigned one if both operands
3563 // are known to have the same sign.
3564 if (I.isSigned() &&
3565 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
3566 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
3567 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
3568 }
3569
3570 // Test if the ICmpInst instruction is used exclusively by a select as
3571 // part of a minimum or maximum operation. If so, refrain from doing
3572 // any other folding. This helps out other analyses which understand
3573 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
3574 // and CodeGen. And in this case, at least one of the comparison
3575 // operands has at least one user besides the compare (the select),
3576 // which would often largely negate the benefit of folding anyway.
3577 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00003578 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00003579 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
3580 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00003581 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003582
3583 // See if we are doing a comparison between a constant and an instruction that
3584 // can be folded into the comparison.
3585 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003586 // Since the RHS is a ConstantInt (CI), if the left hand side is an
3587 // instruction, see if that instruction also has constants so that the
3588 // instruction can be folded into the icmp
Chris Lattner2188e402010-01-04 07:37:31 +00003589 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3590 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
3591 return Res;
3592 }
3593
3594 // Handle icmp with constant (but not simple integer constant) RHS
3595 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3596 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3597 switch (LHSI->getOpcode()) {
3598 case Instruction::GetElementPtr:
3599 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3600 if (RHSC->isNullValue() &&
3601 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3602 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3603 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3604 break;
3605 case Instruction::PHI:
3606 // Only fold icmp into the PHI if the phi and icmp are in the same
3607 // block. If in the same block, we're encouraging jump threading. If
3608 // not, we are just pessimizing the code by making an i1 phi.
3609 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003610 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003611 return NV;
3612 break;
3613 case Instruction::Select: {
3614 // If either operand of the select is a constant, we can fold the
3615 // comparison into the select arms, which will cause one to be
3616 // constant folded and the select turned into a bitwise or.
Craig Topperf40110f2014-04-25 05:29:35 +00003617 Value *Op1 = nullptr, *Op2 = nullptr;
Hans Wennborg083ca9b2015-10-06 23:24:35 +00003618 ConstantInt *CI = nullptr;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003619 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003620 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003621 CI = dyn_cast<ConstantInt>(Op1);
3622 }
3623 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003624 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003625 CI = dyn_cast<ConstantInt>(Op2);
3626 }
Chris Lattner2188e402010-01-04 07:37:31 +00003627
3628 // We only want to perform this transformation if it will not lead to
3629 // additional code. This is true if either both sides of the select
3630 // fold to a constant (in which case the icmp is replaced with a select
3631 // which will usually simplify) or this is the only user of the
3632 // select (in which case we are trading a select+icmp for a simpler
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003633 // select+icmp) or all uses of the select can be replaced based on
3634 // dominance information ("Global cases").
3635 bool Transform = false;
3636 if (Op1 && Op2)
3637 Transform = true;
3638 else if (Op1 || Op2) {
3639 // Local case
3640 if (LHSI->hasOneUse())
3641 Transform = true;
3642 // Global cases
3643 else if (CI && !CI->isZero())
3644 // When Op1 is constant try replacing select with second operand.
3645 // Otherwise Op2 is constant and try replacing select with first
3646 // operand.
3647 Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
3648 Op1 ? 2 : 1);
3649 }
3650 if (Transform) {
Chris Lattner2188e402010-01-04 07:37:31 +00003651 if (!Op1)
3652 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3653 RHSC, I.getName());
3654 if (!Op2)
3655 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3656 RHSC, I.getName());
3657 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3658 }
3659 break;
3660 }
Chris Lattner2188e402010-01-04 07:37:31 +00003661 case Instruction::IntToPtr:
3662 // icmp pred inttoptr(X), null -> icmp pred X, 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003663 if (RHSC->isNullValue() &&
3664 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
Chris Lattner2188e402010-01-04 07:37:31 +00003665 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3666 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3667 break;
3668
3669 case Instruction::Load:
3670 // Try to optimize things like "A[i] > 4" to index computations.
3671 if (GetElementPtrInst *GEP =
3672 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3673 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3674 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3675 !cast<LoadInst>(LHSI)->isVolatile())
3676 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3677 return Res;
3678 }
3679 break;
3680 }
3681 }
3682
3683 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3684 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
3685 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
3686 return NI;
3687 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
3688 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
3689 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3690 return NI;
3691
Hans Wennborgf1f36512015-10-07 00:20:07 +00003692 // Try to optimize equality comparisons against alloca-based pointers.
3693 if (Op0->getType()->isPointerTy() && I.isEquality()) {
3694 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
3695 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
3696 if (Instruction *New = FoldAllocaCmp(I, Alloca, Op1))
3697 return New;
3698 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
3699 if (Instruction *New = FoldAllocaCmp(I, Alloca, Op0))
3700 return New;
3701 }
3702
Chris Lattner2188e402010-01-04 07:37:31 +00003703 // Test to see if the operands of the icmp are casted versions of other
3704 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3705 // now.
3706 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003707 if (Op0->getType()->isPointerTy() &&
3708 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003709 // We keep moving the cast from the left operand over to the right
3710 // operand, where it can often be eliminated completely.
3711 Op0 = CI->getOperand(0);
3712
3713 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3714 // so eliminate it as well.
3715 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3716 Op1 = CI2->getOperand(0);
3717
3718 // If Op1 is a constant, we can fold the cast into the constant.
3719 if (Op0->getType() != Op1->getType()) {
3720 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3721 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3722 } else {
3723 // Otherwise, cast the RHS right before the icmp
3724 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3725 }
3726 }
3727 return new ICmpInst(I.getPredicate(), Op0, Op1);
3728 }
3729 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003730
Chris Lattner2188e402010-01-04 07:37:31 +00003731 if (isa<CastInst>(Op0)) {
3732 // Handle the special case of: icmp (cast bool to X), <cst>
3733 // This comes up when you have code like
3734 // int X = A < B;
3735 // if (X) ...
3736 // For generality, we handle any zero-extension of any operand comparison
3737 // with a constant or another cast from the same type.
3738 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
3739 if (Instruction *R = visitICmpInstWithCastAndCast(I))
3740 return R;
3741 }
Chris Lattner2188e402010-01-04 07:37:31 +00003742
Duncan Sandse5220012011-02-17 07:46:37 +00003743 // Special logic for binary operators.
3744 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3745 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3746 if (BO0 || BO1) {
3747 CmpInst::Predicate Pred = I.getPredicate();
3748 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3749 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3750 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3751 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3752 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3753 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3754 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3755 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3756 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3757
3758 // Analyze the case when either Op0 or Op1 is an add instruction.
3759 // 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 +00003760 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +00003761 if (BO0 && BO0->getOpcode() == Instruction::Add) {
3762 A = BO0->getOperand(0);
3763 B = BO0->getOperand(1);
3764 }
3765 if (BO1 && BO1->getOpcode() == Instruction::Add) {
3766 C = BO1->getOperand(0);
3767 D = BO1->getOperand(1);
3768 }
Duncan Sandse5220012011-02-17 07:46:37 +00003769
David Majnemer549f4f22014-11-01 09:09:51 +00003770 // icmp (X+cst) < 0 --> X < -cst
3771 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
3772 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
3773 if (!RHSC->isMinValue(/*isSigned=*/true))
3774 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
3775
Duncan Sandse5220012011-02-17 07:46:37 +00003776 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3777 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3778 return new ICmpInst(Pred, A == Op1 ? B : A,
3779 Constant::getNullValue(Op1->getType()));
3780
3781 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3782 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3783 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3784 C == Op0 ? D : C);
3785
Duncan Sands84653b32011-02-18 16:25:37 +00003786 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003787 if (A && C && (A == C || A == D || B == C || B == D) &&
3788 NoOp0WrapProblem && NoOp1WrapProblem &&
3789 // Try not to increase register pressure.
3790 BO0->hasOneUse() && BO1->hasOneUse()) {
3791 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003792 Value *Y, *Z;
3793 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003794 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003795 Y = B;
3796 Z = D;
3797 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003798 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003799 Y = B;
3800 Z = C;
3801 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003802 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003803 Y = A;
3804 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003805 } else {
3806 assert(B == D);
3807 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003808 Y = A;
3809 Z = C;
3810 }
Duncan Sandse5220012011-02-17 07:46:37 +00003811 return new ICmpInst(Pred, Y, Z);
3812 }
3813
David Majnemerb81cd632013-04-11 20:05:46 +00003814 // icmp slt (X + -1), Y -> icmp sle X, Y
3815 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3816 match(B, m_AllOnes()))
3817 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3818
3819 // icmp sge (X + -1), Y -> icmp sgt X, Y
3820 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3821 match(B, m_AllOnes()))
3822 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3823
3824 // icmp sle (X + 1), Y -> icmp slt X, Y
3825 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3826 match(B, m_One()))
3827 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3828
3829 // icmp sgt (X + 1), Y -> icmp sge X, Y
3830 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3831 match(B, m_One()))
3832 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3833
Michael Liaoc65d3862015-10-19 22:08:14 +00003834 // icmp sgt X, (Y + -1) -> icmp sge X, Y
3835 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3836 match(D, m_AllOnes()))
3837 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3838
3839 // icmp sle X, (Y + -1) -> icmp slt X, Y
3840 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3841 match(D, m_AllOnes()))
3842 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3843
3844 // icmp sge X, (Y + 1) -> icmp sgt X, Y
3845 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE &&
3846 match(D, m_One()))
3847 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3848
3849 // icmp slt X, (Y + 1) -> icmp sle X, Y
3850 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT &&
3851 match(D, m_One()))
3852 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3853
David Majnemerb81cd632013-04-11 20:05:46 +00003854 // if C1 has greater magnitude than C2:
3855 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3856 // s.t. C3 = C1 - C2
3857 //
3858 // if C2 has greater magnitude than C1:
3859 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3860 // s.t. C3 = C2 - C1
3861 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3862 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3863 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3864 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3865 const APInt &AP1 = C1->getValue();
3866 const APInt &AP2 = C2->getValue();
3867 if (AP1.isNegative() == AP2.isNegative()) {
3868 APInt AP1Abs = C1->getValue().abs();
3869 APInt AP2Abs = C2->getValue().abs();
3870 if (AP1Abs.uge(AP2Abs)) {
3871 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
3872 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
3873 return new ICmpInst(Pred, NewAdd, C);
3874 } else {
3875 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
3876 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
3877 return new ICmpInst(Pred, A, NewAdd);
3878 }
3879 }
3880 }
3881
3882
Duncan Sandse5220012011-02-17 07:46:37 +00003883 // Analyze the case when either Op0 or Op1 is a sub instruction.
3884 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
Richard Trieu7a083812016-02-18 22:09:30 +00003885 A = nullptr;
3886 B = nullptr;
3887 C = nullptr;
3888 D = nullptr;
3889 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
3890 A = BO0->getOperand(0);
3891 B = BO0->getOperand(1);
3892 }
3893 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3894 C = BO1->getOperand(0);
3895 D = BO1->getOperand(1);
3896 }
Duncan Sandse5220012011-02-17 07:46:37 +00003897
Duncan Sands84653b32011-02-18 16:25:37 +00003898 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3899 if (A == Op1 && NoOp0WrapProblem)
3900 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3901
3902 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
3903 if (C == Op0 && NoOp1WrapProblem)
3904 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3905
3906 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003907 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
3908 // Try not to increase register pressure.
3909 BO0->hasOneUse() && BO1->hasOneUse())
3910 return new ICmpInst(Pred, A, C);
3911
Duncan Sands84653b32011-02-18 16:25:37 +00003912 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
3913 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3914 // Try not to increase register pressure.
3915 BO0->hasOneUse() && BO1->hasOneUse())
3916 return new ICmpInst(Pred, D, B);
3917
David Majnemer186c9422014-05-15 00:02:20 +00003918 // icmp (0-X) < cst --> x > -cst
3919 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3920 Value *X;
3921 if (match(BO0, m_Neg(m_Value(X))))
3922 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
3923 if (!RHSC->isMinValue(/*isSigned=*/true))
3924 return new ICmpInst(I.getSwappedPredicate(), X,
3925 ConstantExpr::getNeg(RHSC));
3926 }
3927
Craig Topperf40110f2014-04-25 05:29:35 +00003928 BinaryOperator *SRem = nullptr;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003929 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00003930 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
3931 Op1 == BO0->getOperand(1))
3932 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003933 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00003934 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3935 Op0 == BO1->getOperand(1))
3936 SRem = BO1;
3937 if (SRem) {
3938 // We don't check hasOneUse to avoid increasing register pressure because
3939 // the value we use is the same value this instruction was already using.
3940 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
3941 default: break;
3942 case ICmpInst::ICMP_EQ:
Sanjay Patel4b198802016-02-01 22:23:39 +00003943 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003944 case ICmpInst::ICMP_NE:
Sanjay Patel4b198802016-02-01 22:23:39 +00003945 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003946 case ICmpInst::ICMP_SGT:
3947 case ICmpInst::ICMP_SGE:
3948 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
3949 Constant::getAllOnesValue(SRem->getType()));
3950 case ICmpInst::ICMP_SLT:
3951 case ICmpInst::ICMP_SLE:
3952 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
3953 Constant::getNullValue(SRem->getType()));
3954 }
3955 }
3956
Duncan Sandse5220012011-02-17 07:46:37 +00003957 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
3958 BO0->hasOneUse() && BO1->hasOneUse() &&
3959 BO0->getOperand(1) == BO1->getOperand(1)) {
3960 switch (BO0->getOpcode()) {
3961 default: break;
3962 case Instruction::Add:
3963 case Instruction::Sub:
3964 case Instruction::Xor:
3965 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
3966 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3967 BO1->getOperand(0));
3968 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
3969 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3970 if (CI->getValue().isSignBit()) {
3971 ICmpInst::Predicate Pred = I.isSigned()
3972 ? I.getUnsignedPredicate()
3973 : I.getSignedPredicate();
3974 return new ICmpInst(Pred, BO0->getOperand(0),
3975 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00003976 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003977
David Majnemerf8853ae2016-02-01 17:37:56 +00003978 if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00003979 ICmpInst::Predicate Pred = I.isSigned()
3980 ? I.getUnsignedPredicate()
3981 : I.getSignedPredicate();
3982 Pred = I.getSwappedPredicate(Pred);
3983 return new ICmpInst(Pred, BO0->getOperand(0),
3984 BO1->getOperand(0));
3985 }
Chris Lattner2188e402010-01-04 07:37:31 +00003986 }
Duncan Sandse5220012011-02-17 07:46:37 +00003987 break;
3988 case Instruction::Mul:
3989 if (!I.isEquality())
3990 break;
3991
3992 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3993 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
3994 // Mask = -1 >> count-trailing-zeros(Cst).
3995 if (!CI->isZero() && !CI->isOne()) {
3996 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003997 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00003998 APInt::getLowBitsSet(AP.getBitWidth(),
3999 AP.getBitWidth() -
4000 AP.countTrailingZeros()));
4001 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
4002 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
4003 return new ICmpInst(I.getPredicate(), And1, And2);
4004 }
4005 }
4006 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00004007 case Instruction::UDiv:
4008 case Instruction::LShr:
4009 if (I.isSigned())
4010 break;
4011 // fall-through
4012 case Instruction::SDiv:
4013 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00004014 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00004015 break;
4016 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4017 BO1->getOperand(0));
4018 case Instruction::Shl: {
4019 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
4020 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
4021 if (!NUW && !NSW)
4022 break;
4023 if (!NSW && I.isSigned())
4024 break;
4025 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4026 BO1->getOperand(0));
4027 }
Chris Lattner2188e402010-01-04 07:37:31 +00004028 }
4029 }
Sanjoy Dasc86c1622015-08-21 22:22:37 +00004030
4031 if (BO0) {
4032 // Transform A & (L - 1) `ult` L --> L != 0
4033 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
4034 auto BitwiseAnd =
4035 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
4036
4037 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
4038 auto *Zero = Constant::getNullValue(BO0->getType());
4039 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
4040 }
4041 }
Chris Lattner2188e402010-01-04 07:37:31 +00004042 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004043
Chris Lattner2188e402010-01-04 07:37:31 +00004044 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00004045 // Transform (A & ~B) == 0 --> (A & B) != 0
4046 // and (A & ~B) != 0 --> (A & B) == 0
4047 // if A is a power of 2.
4048 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00004049 match(Op1, m_Zero()) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004050 isKnownToBeAPowerOfTwo(A, DL, false, 0, AC, &I, DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00004051 return new ICmpInst(I.getInversePredicate(),
4052 Builder->CreateAnd(A, B),
4053 Op1);
4054
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004055 // ~x < ~y --> y < x
4056 // ~x < cst --> ~cst < x
4057 if (match(Op0, m_Not(m_Value(A)))) {
4058 if (match(Op1, m_Not(m_Value(B))))
4059 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00004060 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004061 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
4062 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00004063
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004064 Instruction *AddI = nullptr;
4065 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
4066 m_Instruction(AddI))) &&
4067 isa<IntegerType>(A->getType())) {
4068 Value *Result;
4069 Constant *Overflow;
4070 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
4071 Overflow)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004072 replaceInstUsesWith(*AddI, Result);
4073 return replaceInstUsesWith(I, Overflow);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004074 }
4075 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004076
4077 // (zext a) * (zext b) --> llvm.umul.with.overflow.
4078 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4079 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
4080 return R;
4081 }
4082 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4083 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
4084 return R;
4085 }
Chris Lattner2188e402010-01-04 07:37:31 +00004086 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004087
Chris Lattner2188e402010-01-04 07:37:31 +00004088 if (I.isEquality()) {
4089 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00004090
Chris Lattner2188e402010-01-04 07:37:31 +00004091 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4092 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4093 Value *OtherVal = A == Op1 ? B : A;
4094 return new ICmpInst(I.getPredicate(), OtherVal,
4095 Constant::getNullValue(A->getType()));
4096 }
4097
4098 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4099 // A^c1 == C^c2 --> A == C^(c1^c2)
4100 ConstantInt *C1, *C2;
4101 if (match(B, m_ConstantInt(C1)) &&
4102 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00004103 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004104 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00004105 return new ICmpInst(I.getPredicate(), A, Xor);
4106 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004107
Chris Lattner2188e402010-01-04 07:37:31 +00004108 // A^B == A^D -> B == D
4109 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4110 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4111 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4112 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4113 }
4114 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004115
Chris Lattner2188e402010-01-04 07:37:31 +00004116 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4117 (A == Op0 || B == Op0)) {
4118 // A == (A^B) -> B == 0
4119 Value *OtherVal = A == Op0 ? B : A;
4120 return new ICmpInst(I.getPredicate(), OtherVal,
4121 Constant::getNullValue(A->getType()));
4122 }
4123
Chris Lattner2188e402010-01-04 07:37:31 +00004124 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00004125 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00004126 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Craig Topperf40110f2014-04-25 05:29:35 +00004127 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004128
Chris Lattner2188e402010-01-04 07:37:31 +00004129 if (A == C) {
4130 X = B; Y = D; Z = A;
4131 } else if (A == D) {
4132 X = B; Y = C; Z = A;
4133 } else if (B == C) {
4134 X = A; Y = D; Z = B;
4135 } else if (B == D) {
4136 X = A; Y = C; Z = B;
4137 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004138
Chris Lattner2188e402010-01-04 07:37:31 +00004139 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004140 Op1 = Builder->CreateXor(X, Y);
4141 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00004142 I.setOperand(0, Op1);
4143 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4144 return &I;
4145 }
4146 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004147
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004148 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00004149 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004150 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00004151 if ((Op0->hasOneUse() &&
4152 match(Op0, m_ZExt(m_Value(A))) &&
4153 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
4154 (Op1->hasOneUse() &&
4155 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
4156 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004157 APInt Pow2 = Cst1->getValue() + 1;
4158 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
4159 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
4160 return new ICmpInst(I.getPredicate(), A,
4161 Builder->CreateTrunc(B, A->getType()));
4162 }
4163
Benjamin Kramer03f3e242013-11-16 16:00:48 +00004164 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
4165 // For lshr and ashr pairs.
4166 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4167 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
4168 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4169 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
4170 unsigned TypeBits = Cst1->getBitWidth();
4171 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4172 if (ShAmt < TypeBits && ShAmt != 0) {
4173 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
4174 ? ICmpInst::ICMP_UGE
4175 : ICmpInst::ICMP_ULT;
4176 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4177 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
4178 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
4179 }
4180 }
4181
Benjamin Kramer7fa8c432015-03-26 17:12:06 +00004182 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
4183 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
4184 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
4185 unsigned TypeBits = Cst1->getBitWidth();
4186 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4187 if (ShAmt < TypeBits && ShAmt != 0) {
4188 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4189 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
4190 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
4191 I.getName() + ".mask");
4192 return new ICmpInst(I.getPredicate(), And,
4193 Constant::getNullValue(Cst1->getType()));
4194 }
4195 }
4196
Chris Lattner1b06c712011-04-26 20:18:20 +00004197 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
4198 // "icmp (and X, mask), cst"
4199 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00004200 if (Op0->hasOneUse() &&
4201 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
4202 m_ConstantInt(ShAmt))))) &&
4203 match(Op1, m_ConstantInt(Cst1)) &&
4204 // Only do this when A has multiple uses. This is most important to do
4205 // when it exposes other optimizations.
4206 !A->hasOneUse()) {
4207 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004208
Chris Lattner1b06c712011-04-26 20:18:20 +00004209 if (ShAmt < ASize) {
4210 APInt MaskV =
4211 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
4212 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004213
Chris Lattner1b06c712011-04-26 20:18:20 +00004214 APInt CmpV = Cst1->getValue().zext(ASize);
4215 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004216
Chris Lattner1b06c712011-04-26 20:18:20 +00004217 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
4218 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
4219 }
4220 }
Chris Lattner2188e402010-01-04 07:37:31 +00004221 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004222
David Majnemerc1eca5a2014-11-06 23:23:30 +00004223 // The 'cmpxchg' instruction returns an aggregate containing the old value and
4224 // an i1 which indicates whether or not we successfully did the swap.
4225 //
4226 // Replace comparisons between the old value and the expected value with the
4227 // indicator that 'cmpxchg' returns.
4228 //
4229 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
4230 // spuriously fail. In those cases, the old value may equal the expected
4231 // value but it is possible for the swap to not occur.
4232 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4233 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4234 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4235 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4236 !ACXI->isWeak())
4237 return ExtractValueInst::Create(ACXI, 1);
4238
Chris Lattner2188e402010-01-04 07:37:31 +00004239 {
4240 Value *X; ConstantInt *Cst;
4241 // icmp X+Cst, X
4242 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00004243 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004244
4245 // icmp X, X+Cst
4246 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00004247 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004248 }
Craig Topperf40110f2014-04-25 05:29:35 +00004249 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004250}
4251
Chris Lattner2188e402010-01-04 07:37:31 +00004252/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
Chris Lattner2188e402010-01-04 07:37:31 +00004253Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4254 Instruction *LHSI,
4255 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00004256 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004257 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004258
Chris Lattner2188e402010-01-04 07:37:31 +00004259 // Get the width of the mantissa. We don't want to hack on conversions that
4260 // might lose information from the integer, e.g. "i64 -> float"
4261 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00004262 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004263
Matt Arsenault55e73122015-01-06 15:50:59 +00004264 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4265
Chris Lattner2188e402010-01-04 07:37:31 +00004266 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004267
Matt Arsenault55e73122015-01-06 15:50:59 +00004268 if (I.isEquality()) {
4269 FCmpInst::Predicate P = I.getPredicate();
4270 bool IsExact = false;
4271 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
4272 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
4273
4274 // If the floating point constant isn't an integer value, we know if we will
4275 // ever compare equal / not equal to it.
4276 if (!IsExact) {
4277 // TODO: Can never be -0.0 and other non-representable values
4278 APFloat RHSRoundInt(RHS);
4279 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
4280 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
4281 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00004282 return replaceInstUsesWith(I, Builder->getFalse());
Matt Arsenault55e73122015-01-06 15:50:59 +00004283
4284 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
Sanjay Patel4b198802016-02-01 22:23:39 +00004285 return replaceInstUsesWith(I, Builder->getTrue());
Matt Arsenault55e73122015-01-06 15:50:59 +00004286 }
4287 }
4288
4289 // TODO: If the constant is exactly representable, is it always OK to do
4290 // equality compares as integer?
4291 }
4292
Arch D. Robison8ed08542015-09-15 17:51:59 +00004293 // Check to see that the input is converted from an integer type that is small
4294 // enough that preserves all bits. TODO: check here for "known" sign bits.
4295 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4296 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00004297
Arch D. Robison8ed08542015-09-15 17:51:59 +00004298 // Following test does NOT adjust InputSize downwards for signed inputs,
4299 // because the most negative value still requires all the mantissa bits
4300 // to distinguish it from one less than that value.
4301 if ((int)InputSize > MantissaWidth) {
4302 // Conversion would lose accuracy. Check if loss can impact comparison.
4303 int Exp = ilogb(RHS);
4304 if (Exp == APFloat::IEK_Inf) {
4305 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
4306 if (MaxExponent < (int)InputSize - !LHSUnsigned)
4307 // Conversion could create infinity.
4308 return nullptr;
4309 } else {
4310 // Note that if RHS is zero or NaN, then Exp is negative
4311 // and first condition is trivially false.
4312 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
4313 // Conversion could affect comparison.
4314 return nullptr;
4315 }
4316 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004317
Chris Lattner2188e402010-01-04 07:37:31 +00004318 // Otherwise, we can potentially simplify the comparison. We know that it
4319 // will always come through as an integer value and we know the constant is
4320 // not a NAN (it would have been previously simplified).
4321 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00004322
Chris Lattner2188e402010-01-04 07:37:31 +00004323 ICmpInst::Predicate Pred;
4324 switch (I.getPredicate()) {
4325 default: llvm_unreachable("Unexpected predicate!");
4326 case FCmpInst::FCMP_UEQ:
4327 case FCmpInst::FCMP_OEQ:
4328 Pred = ICmpInst::ICMP_EQ;
4329 break;
4330 case FCmpInst::FCMP_UGT:
4331 case FCmpInst::FCMP_OGT:
4332 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4333 break;
4334 case FCmpInst::FCMP_UGE:
4335 case FCmpInst::FCMP_OGE:
4336 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4337 break;
4338 case FCmpInst::FCMP_ULT:
4339 case FCmpInst::FCMP_OLT:
4340 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4341 break;
4342 case FCmpInst::FCMP_ULE:
4343 case FCmpInst::FCMP_OLE:
4344 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4345 break;
4346 case FCmpInst::FCMP_UNE:
4347 case FCmpInst::FCMP_ONE:
4348 Pred = ICmpInst::ICMP_NE;
4349 break;
4350 case FCmpInst::FCMP_ORD:
Sanjay Patel4b198802016-02-01 22:23:39 +00004351 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004352 case FCmpInst::FCMP_UNO:
Sanjay Patel4b198802016-02-01 22:23:39 +00004353 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004354 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004355
Chris Lattner2188e402010-01-04 07:37:31 +00004356 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004357
Chris Lattner2188e402010-01-04 07:37:31 +00004358 // See if the FP constant is too large for the integer. For example,
4359 // comparing an i8 to 300.0.
4360 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004361
Chris Lattner2188e402010-01-04 07:37:31 +00004362 if (!LHSUnsigned) {
4363 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4364 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004365 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004366 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4367 APFloat::rmNearestTiesToEven);
4368 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4369 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4370 Pred == ICmpInst::ICMP_SLE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004371 return replaceInstUsesWith(I, Builder->getTrue());
4372 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004373 }
4374 } else {
4375 // If the RHS value is > UnsignedMax, fold the comparison. This handles
4376 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004377 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004378 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4379 APFloat::rmNearestTiesToEven);
4380 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
4381 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
4382 Pred == ICmpInst::ICMP_ULE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004383 return replaceInstUsesWith(I, Builder->getTrue());
4384 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004385 }
4386 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004387
Chris Lattner2188e402010-01-04 07:37:31 +00004388 if (!LHSUnsigned) {
4389 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004390 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004391 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4392 APFloat::rmNearestTiesToEven);
4393 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4394 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4395 Pred == ICmpInst::ICMP_SGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004396 return replaceInstUsesWith(I, Builder->getTrue());
4397 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004398 }
Devang Patel698452b2012-02-13 23:05:18 +00004399 } else {
4400 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004401 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00004402 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
4403 APFloat::rmNearestTiesToEven);
4404 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
4405 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
4406 Pred == ICmpInst::ICMP_UGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004407 return replaceInstUsesWith(I, Builder->getTrue());
4408 return replaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00004409 }
Chris Lattner2188e402010-01-04 07:37:31 +00004410 }
4411
4412 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4413 // [0, UMAX], but it may still be fractional. See if it is fractional by
4414 // casting the FP value to the integer value and back, checking for equality.
4415 // Don't do this for zero, because -0.0 is not fractional.
4416 Constant *RHSInt = LHSUnsigned
4417 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4418 : ConstantExpr::getFPToSI(RHSC, IntTy);
4419 if (!RHS.isZero()) {
4420 bool Equal = LHSUnsigned
4421 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4422 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4423 if (!Equal) {
4424 // If we had a comparison against a fractional value, we have to adjust
4425 // the compare predicate and sometimes the value. RHSC is rounded towards
4426 // zero at this point.
4427 switch (Pred) {
4428 default: llvm_unreachable("Unexpected integer comparison!");
4429 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Sanjay Patel4b198802016-02-01 22:23:39 +00004430 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004431 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Sanjay Patel4b198802016-02-01 22:23:39 +00004432 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004433 case ICmpInst::ICMP_ULE:
4434 // (float)int <= 4.4 --> int <= 4
4435 // (float)int <= -4.4 --> false
4436 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004437 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004438 break;
4439 case ICmpInst::ICMP_SLE:
4440 // (float)int <= 4.4 --> int <= 4
4441 // (float)int <= -4.4 --> int < -4
4442 if (RHS.isNegative())
4443 Pred = ICmpInst::ICMP_SLT;
4444 break;
4445 case ICmpInst::ICMP_ULT:
4446 // (float)int < -4.4 --> false
4447 // (float)int < 4.4 --> int <= 4
4448 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004449 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004450 Pred = ICmpInst::ICMP_ULE;
4451 break;
4452 case ICmpInst::ICMP_SLT:
4453 // (float)int < -4.4 --> int < -4
4454 // (float)int < 4.4 --> int <= 4
4455 if (!RHS.isNegative())
4456 Pred = ICmpInst::ICMP_SLE;
4457 break;
4458 case ICmpInst::ICMP_UGT:
4459 // (float)int > 4.4 --> int > 4
4460 // (float)int > -4.4 --> true
4461 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004462 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004463 break;
4464 case ICmpInst::ICMP_SGT:
4465 // (float)int > 4.4 --> int > 4
4466 // (float)int > -4.4 --> int >= -4
4467 if (RHS.isNegative())
4468 Pred = ICmpInst::ICMP_SGE;
4469 break;
4470 case ICmpInst::ICMP_UGE:
4471 // (float)int >= -4.4 --> true
4472 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00004473 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004474 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004475 Pred = ICmpInst::ICMP_UGT;
4476 break;
4477 case ICmpInst::ICMP_SGE:
4478 // (float)int >= -4.4 --> int >= -4
4479 // (float)int >= 4.4 --> int > 4
4480 if (!RHS.isNegative())
4481 Pred = ICmpInst::ICMP_SGT;
4482 break;
4483 }
4484 }
4485 }
4486
4487 // Lower this FP comparison into an appropriate integer version of the
4488 // comparison.
4489 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4490}
4491
4492Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4493 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004494
Chris Lattner2188e402010-01-04 07:37:31 +00004495 /// Orders the operands of the compare so that they are listed from most
4496 /// complex to least complex. This puts constants before unary operators,
4497 /// before binary operators.
4498 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4499 I.swapOperands();
4500 Changed = true;
4501 }
4502
4503 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004504
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004505 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
4506 I.getFastMathFlags(), DL, TLI, DT, AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004507 return replaceInstUsesWith(I, V);
Chris Lattner2188e402010-01-04 07:37:31 +00004508
4509 // Simplify 'fcmp pred X, X'
4510 if (Op0 == Op1) {
4511 switch (I.getPredicate()) {
4512 default: llvm_unreachable("Unknown predicate!");
4513 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4514 case FCmpInst::FCMP_ULT: // True if unordered or less than
4515 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4516 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4517 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4518 I.setPredicate(FCmpInst::FCMP_UNO);
4519 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4520 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004521
Chris Lattner2188e402010-01-04 07:37:31 +00004522 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4523 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4524 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4525 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4526 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4527 I.setPredicate(FCmpInst::FCMP_ORD);
4528 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4529 return &I;
4530 }
4531 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004532
James Molloy2b21a7c2015-05-20 18:41:25 +00004533 // Test if the FCmpInst instruction is used exclusively by a select as
4534 // part of a minimum or maximum operation. If so, refrain from doing
4535 // any other folding. This helps out other analyses which understand
4536 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4537 // and CodeGen. And in this case, at least one of the comparison
4538 // operands has at least one user besides the compare (the select),
4539 // which would often largely negate the benefit of folding anyway.
4540 if (I.hasOneUse())
4541 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4542 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4543 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4544 return nullptr;
4545
Chris Lattner2188e402010-01-04 07:37:31 +00004546 // Handle fcmp with constant RHS
4547 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4548 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4549 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004550 case Instruction::FPExt: {
4551 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4552 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4553 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4554 if (!RHSF)
4555 break;
4556
4557 const fltSemantics *Sem;
4558 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004559 if (LHSExt->getSrcTy()->isHalfTy())
4560 Sem = &APFloat::IEEEhalf;
4561 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004562 Sem = &APFloat::IEEEsingle;
4563 else if (LHSExt->getSrcTy()->isDoubleTy())
4564 Sem = &APFloat::IEEEdouble;
4565 else if (LHSExt->getSrcTy()->isFP128Ty())
4566 Sem = &APFloat::IEEEquad;
4567 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
4568 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004569 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
4570 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004571 else
4572 break;
4573
4574 bool Lossy;
4575 APFloat F = RHSF->getValueAPF();
4576 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4577
Jim Grosbach24ff8342011-09-30 18:45:50 +00004578 // Avoid lossy conversions and denormals. Zero is a special case
4579 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004580 APFloat Fabs = F;
4581 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004582 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004583 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4584 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004585
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004586 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4587 ConstantFP::get(RHSC->getContext(), F));
4588 break;
4589 }
Chris Lattner2188e402010-01-04 07:37:31 +00004590 case Instruction::PHI:
4591 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4592 // block. If in the same block, we're encouraging jump threading. If
4593 // not, we are just pessimizing the code by making an i1 phi.
4594 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004595 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004596 return NV;
4597 break;
4598 case Instruction::SIToFP:
4599 case Instruction::UIToFP:
4600 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
4601 return NV;
4602 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004603 case Instruction::FSub: {
4604 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4605 Value *Op;
4606 if (match(LHSI, m_FNeg(m_Value(Op))))
4607 return new FCmpInst(I.getSwappedPredicate(), Op,
4608 ConstantExpr::getFNeg(RHSC));
4609 break;
4610 }
Dan Gohman94732022010-02-24 06:46:09 +00004611 case Instruction::Load:
4612 if (GetElementPtrInst *GEP =
4613 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4614 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4615 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4616 !cast<LoadInst>(LHSI)->isVolatile())
4617 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
4618 return Res;
4619 }
4620 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004621 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004622 if (!RHSC->isNullValue())
4623 break;
4624
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004625 CallInst *CI = cast<CallInst>(LHSI);
David Majnemerb4b27232016-04-19 19:10:21 +00004626 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer2e02ba72016-04-15 17:21:03 +00004627 if (IID != Intrinsic::fabs)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004628 break;
4629
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004630 // Various optimization for fabs compared with zero.
David Majnemer2e02ba72016-04-15 17:21:03 +00004631 switch (I.getPredicate()) {
4632 default:
4633 break;
4634 // fabs(x) < 0 --> false
4635 case FCmpInst::FCMP_OLT:
4636 llvm_unreachable("handled by SimplifyFCmpInst");
4637 // fabs(x) > 0 --> x != 0
4638 case FCmpInst::FCMP_OGT:
4639 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
4640 // fabs(x) <= 0 --> x == 0
4641 case FCmpInst::FCMP_OLE:
4642 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
4643 // fabs(x) >= 0 --> !isnan(x)
4644 case FCmpInst::FCMP_OGE:
4645 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
4646 // fabs(x) == 0 --> x == 0
4647 // fabs(x) != 0 --> x != 0
4648 case FCmpInst::FCMP_OEQ:
4649 case FCmpInst::FCMP_UEQ:
4650 case FCmpInst::FCMP_ONE:
4651 case FCmpInst::FCMP_UNE:
4652 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004653 }
4654 }
Chris Lattner2188e402010-01-04 07:37:31 +00004655 }
Chris Lattner2188e402010-01-04 07:37:31 +00004656 }
4657
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004658 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004659 Value *X, *Y;
4660 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004661 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004662
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004663 // fcmp (fpext x), (fpext y) -> fcmp x, y
4664 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4665 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4666 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4667 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4668 RHSExt->getOperand(0));
4669
Craig Topperf40110f2014-04-25 05:29:35 +00004670 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004671}