blob: 1ef8428aa70302faf992a664fceacf256e52bf31 [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
Sanjay Patel5f0217f2016-06-05 16:46:18 +000059/// Compute Result = In1+In2, returning true if the result overflowed for this
60/// type.
Chris Lattner2188e402010-01-04 07:37:31 +000061static 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
Sanjay Patel5f0217f2016-06-05 16:46:18 +000094/// Compute Result = In1-In2, returning true if the result overflowed for this
95/// type.
Chris Lattner2188e402010-01-04 07:37:31 +000096static 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
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000126/// Given an exploded icmp instruction, return true if the comparison only
127/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if the
128/// result of the comparison is true when the input value is signed.
129static bool isSignBitCheck(ICmpInst::Predicate Pred, ConstantInt *RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000130 bool &TrueIfSigned) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000131 switch (Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +0000132 case ICmpInst::ICMP_SLT: // True if LHS s< 0
133 TrueIfSigned = true;
134 return RHS->isZero();
135 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
136 TrueIfSigned = true;
137 return RHS->isAllOnesValue();
138 case ICmpInst::ICMP_SGT: // True if LHS s> -1
139 TrueIfSigned = false;
140 return RHS->isAllOnesValue();
141 case ICmpInst::ICMP_UGT:
142 // True if LHS u> RHS and RHS == high-bit-mask - 1
143 TrueIfSigned = true;
Chris Lattnerb1a15122011-07-15 06:08:15 +0000144 return RHS->isMaxValue(true);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000145 case ICmpInst::ICMP_UGE:
Chris Lattner2188e402010-01-04 07:37:31 +0000146 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
147 TrueIfSigned = true;
148 return RHS->getValue().isSignBit();
149 default:
150 return false;
151 }
152}
153
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000154/// Returns true if the exploded icmp can be expressed as a signed comparison
155/// to zero and updates the predicate accordingly.
156/// The signedness of the comparison is preserved.
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000157static bool isSignTest(ICmpInst::Predicate &Pred, const ConstantInt *RHS) {
158 if (!ICmpInst::isSigned(Pred))
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000159 return false;
160
161 if (RHS->isZero())
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000162 return ICmpInst::isRelational(Pred);
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000163
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000164 if (RHS->isOne()) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000165 if (Pred == ICmpInst::ICMP_SLT) {
166 Pred = ICmpInst::ICMP_SLE;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000167 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000168 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000169 } else if (RHS->isAllOnesValue()) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000170 if (Pred == ICmpInst::ICMP_SGT) {
171 Pred = ICmpInst::ICMP_SGE;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000172 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000173 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000174 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000175
176 return false;
177}
178
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000179/// Given a signed integer type and a set of known zero and one bits, compute
180/// the maximum and minimum values that could have the specified known zero and
181/// known one bits, returning them in Min/Max.
182static void ComputeSignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
183 const APInt &KnownOne,
184 APInt &Min, APInt &Max) {
Chris Lattner2188e402010-01-04 07:37:31 +0000185 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
186 KnownZero.getBitWidth() == Min.getBitWidth() &&
187 KnownZero.getBitWidth() == Max.getBitWidth() &&
188 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
189 APInt UnknownBits = ~(KnownZero|KnownOne);
190
191 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
192 // bit if it is unknown.
193 Min = KnownOne;
194 Max = KnownOne|UnknownBits;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000195
Chris Lattner2188e402010-01-04 07:37:31 +0000196 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000197 Min.setBit(Min.getBitWidth()-1);
198 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000199 }
200}
201
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000202/// Given an unsigned integer type and a set of known zero and one bits, compute
203/// the maximum and minimum values that could have the specified known zero and
204/// known one bits, returning them in Min/Max.
Chris Lattner2188e402010-01-04 07:37:31 +0000205static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
206 const APInt &KnownOne,
207 APInt &Min, APInt &Max) {
208 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
209 KnownZero.getBitWidth() == Min.getBitWidth() &&
210 KnownZero.getBitWidth() == Max.getBitWidth() &&
211 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
212 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000213
Chris Lattner2188e402010-01-04 07:37:31 +0000214 // The minimum value is when the unknown bits are all zeros.
215 Min = KnownOne;
216 // The maximum value is when the unknown bits are all ones.
217 Max = KnownOne|UnknownBits;
218}
219
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000220/// This is called when we see this pattern:
Chris Lattner2188e402010-01-04 07:37:31 +0000221/// cmp pred (load (gep GV, ...)), cmpcst
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000222/// where GV is a global variable with a constant initializer. Try to simplify
223/// this into some simple computation that does not need the load. For example
Chris Lattner2188e402010-01-04 07:37:31 +0000224/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
225///
226/// If AndCst is non-null, then the loaded value is masked with that constant
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000227/// before doing the comparison. This handles cases like "A[i]&4 == 0".
Sanjay Patel43395062016-07-21 18:07:40 +0000228Instruction *InstCombiner::foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
229 GlobalVariable *GV,
230 CmpInst &ICI,
231 ConstantInt *AndCst) {
Chris Lattnerfe741762012-01-31 02:55:06 +0000232 Constant *Init = GV->getInitializer();
233 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
Craig Topperf40110f2014-04-25 05:29:35 +0000234 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000235
Chris Lattnerfe741762012-01-31 02:55:06 +0000236 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +0000237 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000238
Chris Lattner2188e402010-01-04 07:37:31 +0000239 // There are many forms of this optimization we can handle, for now, just do
240 // the simple index into a single-dimensional array.
241 //
242 // Require: GEP GV, 0, i {{, constant indices}}
243 if (GEP->getNumOperands() < 3 ||
244 !isa<ConstantInt>(GEP->getOperand(1)) ||
245 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
246 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000247 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000248
249 // Check that indices after the variable are constants and in-range for the
250 // type they index. Collect the indices. This is typically for arrays of
251 // structs.
252 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000253
Chris Lattnerfe741762012-01-31 02:55:06 +0000254 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000255 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
256 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000257 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000258
Chris Lattner2188e402010-01-04 07:37:31 +0000259 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000260 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000261
Chris Lattner229907c2011-07-18 04:54:35 +0000262 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000263 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000264 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000265 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000266 EltTy = ATy->getElementType();
267 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000268 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000269 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000270
Chris Lattner2188e402010-01-04 07:37:31 +0000271 LaterIndices.push_back(IdxVal);
272 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000273
Chris Lattner2188e402010-01-04 07:37:31 +0000274 enum { Overdefined = -3, Undefined = -2 };
275
276 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000277
Chris Lattner2188e402010-01-04 07:37:31 +0000278 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
279 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
280 // and 87 is the second (and last) index. FirstTrueElement is -2 when
281 // undefined, otherwise set to the first true element. SecondTrueElement is
282 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
283 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
284
285 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
286 // form "i != 47 & i != 87". Same state transitions as for true elements.
287 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000288
Chris Lattner2188e402010-01-04 07:37:31 +0000289 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
290 /// define a state machine that triggers for ranges of values that the index
291 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
292 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
293 /// index in the range (inclusive). We use -2 for undefined here because we
294 /// use relative comparisons and don't want 0-1 to match -1.
295 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000296
Chris Lattner2188e402010-01-04 07:37:31 +0000297 // MagicBitvector - This is a magic bitvector where we set a bit if the
298 // comparison is true for element 'i'. If there are 64 elements or less in
299 // the array, this will fully represent all the comparison results.
300 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000301
Chris Lattner2188e402010-01-04 07:37:31 +0000302 // Scan the array and see if one of our patterns matches.
303 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000304 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
305 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000306 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000307
Chris Lattner2188e402010-01-04 07:37:31 +0000308 // If this is indexing an array of structures, get the structure element.
309 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000310 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000311
Chris Lattner2188e402010-01-04 07:37:31 +0000312 // If the element is masked, handle it.
313 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000314
Chris Lattner2188e402010-01-04 07:37:31 +0000315 // Find out if the comparison would be true or false for the i'th element.
316 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Justin Bogner99798402016-08-05 01:06:44 +0000317 CompareRHS, DL, &TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000318 // If the result is undef for this element, ignore it.
319 if (isa<UndefValue>(C)) {
320 // Extend range state machines to cover this element in case there is an
321 // undef in the middle of the range.
322 if (TrueRangeEnd == (int)i-1)
323 TrueRangeEnd = i;
324 if (FalseRangeEnd == (int)i-1)
325 FalseRangeEnd = i;
326 continue;
327 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000328
Chris Lattner2188e402010-01-04 07:37:31 +0000329 // If we can't compute the result for any of the elements, we have to give
330 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000331 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000332
Chris Lattner2188e402010-01-04 07:37:31 +0000333 // Otherwise, we know if the comparison is true or false for this element,
334 // update our state machines.
335 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000336
Chris Lattner2188e402010-01-04 07:37:31 +0000337 // State machine for single/double/range index comparison.
338 if (IsTrueForElt) {
339 // Update the TrueElement state machine.
340 if (FirstTrueElement == Undefined)
341 FirstTrueElement = TrueRangeEnd = i; // First true element.
342 else {
343 // Update double-compare state machine.
344 if (SecondTrueElement == Undefined)
345 SecondTrueElement = i;
346 else
347 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000348
Chris Lattner2188e402010-01-04 07:37:31 +0000349 // Update range state machine.
350 if (TrueRangeEnd == (int)i-1)
351 TrueRangeEnd = i;
352 else
353 TrueRangeEnd = Overdefined;
354 }
355 } else {
356 // Update the FalseElement state machine.
357 if (FirstFalseElement == Undefined)
358 FirstFalseElement = FalseRangeEnd = i; // First false element.
359 else {
360 // Update double-compare state machine.
361 if (SecondFalseElement == Undefined)
362 SecondFalseElement = i;
363 else
364 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000365
Chris Lattner2188e402010-01-04 07:37:31 +0000366 // Update range state machine.
367 if (FalseRangeEnd == (int)i-1)
368 FalseRangeEnd = i;
369 else
370 FalseRangeEnd = Overdefined;
371 }
372 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000373
Chris Lattner2188e402010-01-04 07:37:31 +0000374 // If this element is in range, update our magic bitvector.
375 if (i < 64 && IsTrueForElt)
376 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000377
Chris Lattner2188e402010-01-04 07:37:31 +0000378 // If all of our states become overdefined, bail out early. Since the
379 // predicate is expensive, only check it every 8 elements. This is only
380 // really useful for really huge arrays.
381 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
382 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
383 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000384 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000385 }
386
387 // Now that we've scanned the entire array, emit our new comparison(s). We
388 // order the state machines in complexity of the generated code.
389 Value *Idx = GEP->getOperand(2);
390
Matt Arsenault5aeae182013-08-19 21:40:31 +0000391 // If the index is larger than the pointer size of the target, truncate the
392 // index down like the GEP would do implicitly. We don't have to do this for
393 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000394 if (!GEP->isInBounds()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000395 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000396 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
397 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
398 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
399 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000400
Chris Lattner2188e402010-01-04 07:37:31 +0000401 // If the comparison is only true for one or two elements, emit direct
402 // comparisons.
403 if (SecondTrueElement != Overdefined) {
404 // None true -> false.
405 if (FirstTrueElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000406 return replaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000407
Chris Lattner2188e402010-01-04 07:37:31 +0000408 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000409
Chris Lattner2188e402010-01-04 07:37:31 +0000410 // True for one element -> 'i == 47'.
411 if (SecondTrueElement == Undefined)
412 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000413
Chris Lattner2188e402010-01-04 07:37:31 +0000414 // True for two elements -> 'i == 47 | i == 72'.
415 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
416 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
417 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
418 return BinaryOperator::CreateOr(C1, C2);
419 }
420
421 // If the comparison is only false for one or two elements, emit direct
422 // comparisons.
423 if (SecondFalseElement != Overdefined) {
424 // None false -> true.
425 if (FirstFalseElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000426 return replaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000427
Chris Lattner2188e402010-01-04 07:37:31 +0000428 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
429
430 // False for one element -> 'i != 47'.
431 if (SecondFalseElement == Undefined)
432 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000433
Chris Lattner2188e402010-01-04 07:37:31 +0000434 // False for two elements -> 'i != 47 & i != 72'.
435 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
436 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
437 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
438 return BinaryOperator::CreateAnd(C1, C2);
439 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000440
Chris Lattner2188e402010-01-04 07:37:31 +0000441 // If the comparison can be replaced with a range comparison for the elements
442 // where it is true, emit the range check.
443 if (TrueRangeEnd != Overdefined) {
444 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000445
Chris Lattner2188e402010-01-04 07:37:31 +0000446 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
447 if (FirstTrueElement) {
448 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
449 Idx = Builder->CreateAdd(Idx, Offs);
450 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000451
Chris Lattner2188e402010-01-04 07:37:31 +0000452 Value *End = ConstantInt::get(Idx->getType(),
453 TrueRangeEnd-FirstTrueElement+1);
454 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
455 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000456
Chris Lattner2188e402010-01-04 07:37:31 +0000457 // False range check.
458 if (FalseRangeEnd != Overdefined) {
459 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
460 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
461 if (FirstFalseElement) {
462 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
463 Idx = Builder->CreateAdd(Idx, Offs);
464 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000465
Chris Lattner2188e402010-01-04 07:37:31 +0000466 Value *End = ConstantInt::get(Idx->getType(),
467 FalseRangeEnd-FirstFalseElement);
468 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
469 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000470
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000471 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000472 // of this load, replace it with computation that does:
473 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000474 {
Craig Topperf40110f2014-04-25 05:29:35 +0000475 Type *Ty = nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000476
477 // Look for an appropriate type:
478 // - The type of Idx if the magic fits
479 // - The smallest fitting legal type if we have a DataLayout
480 // - Default to i32
481 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
482 Ty = Idx->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000483 else
484 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000485
Craig Topperf40110f2014-04-25 05:29:35 +0000486 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000487 Value *V = Builder->CreateIntCast(Idx, Ty, false);
488 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
489 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
490 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
491 }
Chris Lattner2188e402010-01-04 07:37:31 +0000492 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000493
Craig Topperf40110f2014-04-25 05:29:35 +0000494 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000495}
496
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000497/// Return a value that can be used to compare the *offset* implied by a GEP to
498/// zero. For example, if we have &A[i], we want to return 'i' for
499/// "icmp ne i, 0". Note that, in general, indices can be complex, and scales
500/// are involved. The above expression would also be legal to codegen as
501/// "icmp ne (i*4), 0" (assuming A is a pointer to i32).
502/// This latter form is less amenable to optimization though, and we are allowed
Chris Lattner2188e402010-01-04 07:37:31 +0000503/// to generate the first by knowing that pointer arithmetic doesn't overflow.
504///
505/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000506///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000507static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
508 const DataLayout &DL) {
Chris Lattner2188e402010-01-04 07:37:31 +0000509 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000510
Chris Lattner2188e402010-01-04 07:37:31 +0000511 // Check to see if this gep only has a single variable index. If so, and if
512 // any constant indices are a multiple of its scale, then we can compute this
513 // in terms of the scale of the variable index. For example, if the GEP
514 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
515 // because the expression will cross zero at the same point.
516 unsigned i, e = GEP->getNumOperands();
517 int64_t Offset = 0;
518 for (i = 1; i != e; ++i, ++GTI) {
519 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
520 // Compute the aggregate offset of constant indices.
521 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000522
Chris Lattner2188e402010-01-04 07:37:31 +0000523 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000524 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000525 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000526 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000527 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000528 Offset += Size*CI->getSExtValue();
529 }
530 } else {
531 // Found our variable index.
532 break;
533 }
534 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000535
Chris Lattner2188e402010-01-04 07:37:31 +0000536 // If there are no variable indices, we must have a constant offset, just
537 // evaluate it the general way.
Craig Topperf40110f2014-04-25 05:29:35 +0000538 if (i == e) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000539
Chris Lattner2188e402010-01-04 07:37:31 +0000540 Value *VariableIdx = GEP->getOperand(i);
541 // Determine the scale factor of the variable element. For example, this is
542 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000543 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000544
Chris Lattner2188e402010-01-04 07:37:31 +0000545 // Verify that there are no other variable indices. If so, emit the hard way.
546 for (++i, ++GTI; i != e; ++i, ++GTI) {
547 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000548 if (!CI) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000549
Chris Lattner2188e402010-01-04 07:37:31 +0000550 // Compute the aggregate offset of constant indices.
551 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000552
Chris Lattner2188e402010-01-04 07:37:31 +0000553 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000554 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000555 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000556 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000557 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000558 Offset += Size*CI->getSExtValue();
559 }
560 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000561
Chris Lattner2188e402010-01-04 07:37:31 +0000562 // Okay, we know we have a single variable index, which must be a
563 // pointer/array/vector index. If there is no offset, life is simple, return
564 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000565 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000566 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000567 if (Offset == 0) {
568 // Cast to intptrty in case a truncation occurs. If an extension is needed,
569 // we don't need to bother extending: the extension won't affect where the
570 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000571 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000572 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
573 }
Chris Lattner2188e402010-01-04 07:37:31 +0000574 return VariableIdx;
575 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000576
Chris Lattner2188e402010-01-04 07:37:31 +0000577 // Otherwise, there is an index. The computation we will do will be modulo
578 // the pointer size, so get it.
579 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000580
Chris Lattner2188e402010-01-04 07:37:31 +0000581 Offset &= PtrSizeMask;
582 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000583
Chris Lattner2188e402010-01-04 07:37:31 +0000584 // To do this transformation, any constant index must be a multiple of the
585 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
586 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
587 // multiple of the variable scale.
588 int64_t NewOffs = Offset / (int64_t)VariableScale;
589 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000590 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000591
Chris Lattner2188e402010-01-04 07:37:31 +0000592 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000593 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000594 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
595 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000596 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000597 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000598}
599
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000600/// Returns true if we can rewrite Start as a GEP with pointer Base
601/// and some integer offset. The nodes that need to be re-written
602/// for this transformation will be added to Explored.
603static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
604 const DataLayout &DL,
605 SetVector<Value *> &Explored) {
606 SmallVector<Value *, 16> WorkList(1, Start);
607 Explored.insert(Base);
608
609 // The following traversal gives us an order which can be used
610 // when doing the final transformation. Since in the final
611 // transformation we create the PHI replacement instructions first,
612 // we don't have to get them in any particular order.
613 //
614 // However, for other instructions we will have to traverse the
615 // operands of an instruction first, which means that we have to
616 // do a post-order traversal.
617 while (!WorkList.empty()) {
618 SetVector<PHINode *> PHIs;
619
620 while (!WorkList.empty()) {
621 if (Explored.size() >= 100)
622 return false;
623
624 Value *V = WorkList.back();
625
626 if (Explored.count(V) != 0) {
627 WorkList.pop_back();
628 continue;
629 }
630
631 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
632 !isa<GEPOperator>(V) && !isa<PHINode>(V))
633 // We've found some value that we can't explore which is different from
634 // the base. Therefore we can't do this transformation.
635 return false;
636
637 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
638 auto *CI = dyn_cast<CastInst>(V);
639 if (!CI->isNoopCast(DL))
640 return false;
641
642 if (Explored.count(CI->getOperand(0)) == 0)
643 WorkList.push_back(CI->getOperand(0));
644 }
645
646 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
647 // We're limiting the GEP to having one index. This will preserve
648 // the original pointer type. We could handle more cases in the
649 // future.
650 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
651 GEP->getType() != Start->getType())
652 return false;
653
654 if (Explored.count(GEP->getOperand(0)) == 0)
655 WorkList.push_back(GEP->getOperand(0));
656 }
657
658 if (WorkList.back() == V) {
659 WorkList.pop_back();
660 // We've finished visiting this node, mark it as such.
661 Explored.insert(V);
662 }
663
664 if (auto *PN = dyn_cast<PHINode>(V)) {
David Majnemercdf28732016-03-19 04:39:52 +0000665 // We cannot transform PHIs on unsplittable basic blocks.
666 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
667 return false;
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000668 Explored.insert(PN);
669 PHIs.insert(PN);
670 }
671 }
672
673 // Explore the PHI nodes further.
674 for (auto *PN : PHIs)
675 for (Value *Op : PN->incoming_values())
676 if (Explored.count(Op) == 0)
677 WorkList.push_back(Op);
678 }
679
680 // Make sure that we can do this. Since we can't insert GEPs in a basic
681 // block before a PHI node, we can't easily do this transformation if
682 // we have PHI node users of transformed instructions.
683 for (Value *Val : Explored) {
684 for (Value *Use : Val->uses()) {
685
686 auto *PHI = dyn_cast<PHINode>(Use);
687 auto *Inst = dyn_cast<Instruction>(Val);
688
689 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
690 Explored.count(PHI) == 0)
691 continue;
692
693 if (PHI->getParent() == Inst->getParent())
694 return false;
695 }
696 }
697 return true;
698}
699
700// Sets the appropriate insert point on Builder where we can add
701// a replacement Instruction for V (if that is possible).
702static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
703 bool Before = true) {
704 if (auto *PHI = dyn_cast<PHINode>(V)) {
705 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
706 return;
707 }
708 if (auto *I = dyn_cast<Instruction>(V)) {
709 if (!Before)
710 I = &*std::next(I->getIterator());
711 Builder.SetInsertPoint(I);
712 return;
713 }
714 if (auto *A = dyn_cast<Argument>(V)) {
715 // Set the insertion point in the entry block.
716 BasicBlock &Entry = A->getParent()->getEntryBlock();
717 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
718 return;
719 }
720 // Otherwise, this is a constant and we don't need to set a new
721 // insertion point.
722 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
723}
724
725/// Returns a re-written value of Start as an indexed GEP using Base as a
726/// pointer.
727static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
728 const DataLayout &DL,
729 SetVector<Value *> &Explored) {
730 // Perform all the substitutions. This is a bit tricky because we can
731 // have cycles in our use-def chains.
732 // 1. Create the PHI nodes without any incoming values.
733 // 2. Create all the other values.
734 // 3. Add the edges for the PHI nodes.
735 // 4. Emit GEPs to get the original pointers.
736 // 5. Remove the original instructions.
737 Type *IndexType = IntegerType::get(
738 Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType()));
739
740 DenseMap<Value *, Value *> NewInsts;
741 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
742
743 // Create the new PHI nodes, without adding any incoming values.
744 for (Value *Val : Explored) {
745 if (Val == Base)
746 continue;
747 // Create empty phi nodes. This avoids cyclic dependencies when creating
748 // the remaining instructions.
749 if (auto *PHI = dyn_cast<PHINode>(Val))
750 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
751 PHI->getName() + ".idx", PHI);
752 }
753 IRBuilder<> Builder(Base->getContext());
754
755 // Create all the other instructions.
756 for (Value *Val : Explored) {
757
758 if (NewInsts.find(Val) != NewInsts.end())
759 continue;
760
761 if (auto *CI = dyn_cast<CastInst>(Val)) {
762 NewInsts[CI] = NewInsts[CI->getOperand(0)];
763 continue;
764 }
765 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
766 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
767 : GEP->getOperand(1);
768 setInsertionPoint(Builder, GEP);
769 // Indices might need to be sign extended. GEPs will magically do
770 // this, but we need to do it ourselves here.
771 if (Index->getType()->getScalarSizeInBits() !=
772 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
773 Index = Builder.CreateSExtOrTrunc(
774 Index, NewInsts[GEP->getOperand(0)]->getType(),
775 GEP->getOperand(0)->getName() + ".sext");
776 }
777
778 auto *Op = NewInsts[GEP->getOperand(0)];
779 if (isa<ConstantInt>(Op) && dyn_cast<ConstantInt>(Op)->isZero())
780 NewInsts[GEP] = Index;
781 else
782 NewInsts[GEP] = Builder.CreateNSWAdd(
783 Op, Index, GEP->getOperand(0)->getName() + ".add");
784 continue;
785 }
786 if (isa<PHINode>(Val))
787 continue;
788
789 llvm_unreachable("Unexpected instruction type");
790 }
791
792 // Add the incoming values to the PHI nodes.
793 for (Value *Val : Explored) {
794 if (Val == Base)
795 continue;
796 // All the instructions have been created, we can now add edges to the
797 // phi nodes.
798 if (auto *PHI = dyn_cast<PHINode>(Val)) {
799 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
800 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
801 Value *NewIncoming = PHI->getIncomingValue(I);
802
803 if (NewInsts.find(NewIncoming) != NewInsts.end())
804 NewIncoming = NewInsts[NewIncoming];
805
806 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
807 }
808 }
809 }
810
811 for (Value *Val : Explored) {
812 if (Val == Base)
813 continue;
814
815 // Depending on the type, for external users we have to emit
816 // a GEP or a GEP + ptrtoint.
817 setInsertionPoint(Builder, Val, false);
818
819 // If required, create an inttoptr instruction for Base.
820 Value *NewBase = Base;
821 if (!Base->getType()->isPointerTy())
822 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
823 Start->getName() + "to.ptr");
824
825 Value *GEP = Builder.CreateInBoundsGEP(
826 Start->getType()->getPointerElementType(), NewBase,
827 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
828
829 if (!Val->getType()->isPointerTy()) {
830 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
831 Val->getName() + ".conv");
832 GEP = Cast;
833 }
834 Val->replaceAllUsesWith(GEP);
835 }
836
837 return NewInsts[Start];
838}
839
840/// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
841/// the input Value as a constant indexed GEP. Returns a pair containing
842/// the GEPs Pointer and Index.
843static std::pair<Value *, Value *>
844getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
845 Type *IndexType = IntegerType::get(V->getContext(),
846 DL.getPointerTypeSizeInBits(V->getType()));
847
848 Constant *Index = ConstantInt::getNullValue(IndexType);
849 while (true) {
850 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
851 // We accept only inbouds GEPs here to exclude the possibility of
852 // overflow.
853 if (!GEP->isInBounds())
854 break;
855 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
856 GEP->getType() == V->getType()) {
857 V = GEP->getOperand(0);
858 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
859 Index = ConstantExpr::getAdd(
860 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
861 continue;
862 }
863 break;
864 }
865 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
866 if (!CI->isNoopCast(DL))
867 break;
868 V = CI->getOperand(0);
869 continue;
870 }
871 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
872 if (!CI->isNoopCast(DL))
873 break;
874 V = CI->getOperand(0);
875 continue;
876 }
877 break;
878 }
879 return {V, Index};
880}
881
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000882/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
883/// We can look through PHIs, GEPs and casts in order to determine a common base
884/// between GEPLHS and RHS.
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000885static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
886 ICmpInst::Predicate Cond,
887 const DataLayout &DL) {
888 if (!GEPLHS->hasAllConstantIndices())
889 return nullptr;
890
891 Value *PtrBase, *Index;
892 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
893
894 // The set of nodes that will take part in this transformation.
895 SetVector<Value *> Nodes;
896
897 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
898 return nullptr;
899
900 // We know we can re-write this as
901 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
902 // Since we've only looked through inbouds GEPs we know that we
903 // can't have overflow on either side. We can therefore re-write
904 // this as:
905 // OFFSET1 cmp OFFSET2
906 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
907
908 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
909 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
910 // offset. Since Index is the offset of LHS to the base pointer, we will now
911 // compare the offsets instead of comparing the pointers.
912 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
913}
914
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000915/// Fold comparisons between a GEP instruction and something else. At this point
916/// we know that the GEP is on the LHS of the comparison.
Sanjay Patel43395062016-07-21 18:07:40 +0000917Instruction *InstCombiner::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000918 ICmpInst::Predicate Cond,
919 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000920 // Don't transform signed compares of GEPs into index compares. Even if the
921 // GEP is inbounds, the final add of the base pointer can have signed overflow
922 // and would change the result of the icmp.
923 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000924 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000925 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000926 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000927
Matt Arsenault44f60d02014-06-09 19:20:29 +0000928 // Look through bitcasts and addrspacecasts. We do not however want to remove
929 // 0 GEPs.
930 if (!isa<GetElementPtrInst>(RHS))
931 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000932
933 Value *PtrBase = GEPLHS->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000934 if (PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000935 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
936 // This transformation (ignoring the base and scales) is valid because we
937 // know pointers can't overflow since the gep is inbounds. See if we can
938 // output an optimized form.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000939 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this, DL);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000940
Chris Lattner2188e402010-01-04 07:37:31 +0000941 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000942 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000943 Offset = EmitGEPOffset(GEPLHS);
944 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
945 Constant::getNullValue(Offset->getType()));
946 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
947 // If the base pointers are different, but the indices are the same, just
948 // compare the base pointer.
949 if (PtrBase != GEPRHS->getOperand(0)) {
950 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
951 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
952 GEPRHS->getOperand(0)->getType();
953 if (IndicesTheSame)
954 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
955 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
956 IndicesTheSame = false;
957 break;
958 }
959
960 // If all indices are the same, just compare the base pointers.
961 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000962 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000963
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000964 // If we're comparing GEPs with two base pointers that only differ in type
965 // and both GEPs have only constant indices or just one use, then fold
966 // the compare with the adjusted indices.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000967 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000968 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
969 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
970 PtrBase->stripPointerCasts() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000971 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000972 Value *LOffset = EmitGEPOffset(GEPLHS);
973 Value *ROffset = EmitGEPOffset(GEPRHS);
974
975 // If we looked through an addrspacecast between different sized address
976 // spaces, the LHS and RHS pointers are different sized
977 // integers. Truncate to the smaller one.
978 Type *LHSIndexTy = LOffset->getType();
979 Type *RHSIndexTy = ROffset->getType();
980 if (LHSIndexTy != RHSIndexTy) {
981 if (LHSIndexTy->getPrimitiveSizeInBits() <
982 RHSIndexTy->getPrimitiveSizeInBits()) {
983 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
984 } else
985 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
986 }
987
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000988 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000989 LOffset, ROffset);
Sanjay Patel4b198802016-02-01 22:23:39 +0000990 return replaceInstUsesWith(I, Cmp);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000991 }
992
Chris Lattner2188e402010-01-04 07:37:31 +0000993 // Otherwise, the base pointers are different and the indices are
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000994 // different. Try convert this to an indexed compare by looking through
995 // PHIs/casts.
996 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +0000997 }
998
999 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001000 if (GEPLHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +00001001 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +00001002 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +00001003
1004 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001005 if (GEPRHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +00001006 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner2188e402010-01-04 07:37:31 +00001007
Stuart Hastings66a82b92011-05-14 05:55:10 +00001008 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +00001009 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
1010 // If the GEPs only differ by one index, compare it.
1011 unsigned NumDifferences = 0; // Keep track of # differences.
1012 unsigned DiffOperand = 0; // The operand that differs.
1013 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
1014 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
1015 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
1016 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
1017 // Irreconcilable differences.
1018 NumDifferences = 2;
1019 break;
1020 } else {
1021 if (NumDifferences++) break;
1022 DiffOperand = i;
1023 }
1024 }
1025
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +00001026 if (NumDifferences == 0) // SAME GEP?
Sanjay Patel4b198802016-02-01 22:23:39 +00001027 return replaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +00001028 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +00001029
Stuart Hastings66a82b92011-05-14 05:55:10 +00001030 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +00001031 Value *LHSV = GEPLHS->getOperand(DiffOperand);
1032 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1033 // Make sure we do a signed comparison here.
1034 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
1035 }
1036 }
1037
1038 // Only lower this if the icmp is the only user of the GEP or if we expect
1039 // the result to fold to a constant!
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001040 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner2188e402010-01-04 07:37:31 +00001041 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1042 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
1043 Value *L = EmitGEPOffset(GEPLHS);
1044 Value *R = EmitGEPOffset(GEPRHS);
1045 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1046 }
1047 }
Silviu Barangaf29dfd32016-01-15 15:52:05 +00001048
1049 // Try convert this to an indexed compare by looking through PHIs/casts as a
1050 // last resort.
1051 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +00001052}
1053
Pete Cooper980a9352016-08-12 17:13:28 +00001054Instruction *InstCombiner::foldAllocaCmp(ICmpInst &ICI,
1055 const AllocaInst *Alloca,
1056 const Value *Other) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001057 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1058
1059 // It would be tempting to fold away comparisons between allocas and any
1060 // pointer not based on that alloca (e.g. an argument). However, even
1061 // though such pointers cannot alias, they can still compare equal.
1062 //
1063 // But LLVM doesn't specify where allocas get their memory, so if the alloca
1064 // doesn't escape we can argue that it's impossible to guess its value, and we
1065 // can therefore act as if any such guesses are wrong.
1066 //
1067 // The code below checks that the alloca doesn't escape, and that it's only
1068 // used in a comparison once (the current instruction). The
1069 // single-comparison-use condition ensures that we're trivially folding all
1070 // comparisons against the alloca consistently, and avoids the risk of
1071 // erroneously folding a comparison of the pointer with itself.
1072
1073 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1074
Pete Cooper980a9352016-08-12 17:13:28 +00001075 SmallVector<const Use *, 32> Worklist;
1076 for (const Use &U : Alloca->uses()) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001077 if (Worklist.size() >= MaxIter)
1078 return nullptr;
1079 Worklist.push_back(&U);
1080 }
1081
1082 unsigned NumCmps = 0;
1083 while (!Worklist.empty()) {
1084 assert(Worklist.size() <= MaxIter);
Pete Cooper980a9352016-08-12 17:13:28 +00001085 const Use *U = Worklist.pop_back_val();
1086 const Value *V = U->getUser();
Hans Wennborgf1f36512015-10-07 00:20:07 +00001087 --MaxIter;
1088
1089 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1090 isa<SelectInst>(V)) {
1091 // Track the uses.
1092 } else if (isa<LoadInst>(V)) {
1093 // Loading from the pointer doesn't escape it.
1094 continue;
Pete Cooper980a9352016-08-12 17:13:28 +00001095 } else if (const auto *SI = dyn_cast<StoreInst>(V)) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001096 // Storing *to* the pointer is fine, but storing the pointer escapes it.
1097 if (SI->getValueOperand() == U->get())
1098 return nullptr;
1099 continue;
1100 } else if (isa<ICmpInst>(V)) {
1101 if (NumCmps++)
1102 return nullptr; // Found more than one cmp.
1103 continue;
Pete Cooper980a9352016-08-12 17:13:28 +00001104 } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001105 switch (Intrin->getIntrinsicID()) {
1106 // These intrinsics don't escape or compare the pointer. Memset is safe
1107 // because we don't allow ptrtoint. Memcpy and memmove are safe because
1108 // we don't allow stores, so src cannot point to V.
1109 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1110 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
1111 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1112 continue;
1113 default:
1114 return nullptr;
1115 }
1116 } else {
1117 return nullptr;
1118 }
Pete Cooper980a9352016-08-12 17:13:28 +00001119 for (const Use &U : V->uses()) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001120 if (Worklist.size() >= MaxIter)
1121 return nullptr;
1122 Worklist.push_back(&U);
1123 }
1124 }
1125
1126 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001127 return replaceInstUsesWith(
Hans Wennborgf1f36512015-10-07 00:20:07 +00001128 ICI,
1129 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1130}
1131
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001132/// Fold "icmp pred (X+CI), X".
Sanjay Patel43395062016-07-21 18:07:40 +00001133Instruction *InstCombiner::foldICmpAddOpConst(Instruction &ICI,
1134 Value *X, ConstantInt *CI,
1135 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +00001136 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001137 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +00001138 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +00001139
Chris Lattner8c92b572010-01-08 17:48:19 +00001140 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +00001141 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
1142 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
1143 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00001144 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +00001145 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +00001146 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1147 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001148
Chris Lattner2188e402010-01-04 07:37:31 +00001149 // (X+1) >u X --> X <u (0-1) --> X != 255
1150 // (X+2) >u X --> X <u (0-2) --> X <u 254
1151 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +00001152 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +00001153 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001154
Chris Lattner2188e402010-01-04 07:37:31 +00001155 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
1156 ConstantInt *SMax = ConstantInt::get(X->getContext(),
1157 APInt::getSignedMaxValue(BitWidth));
1158
1159 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1160 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1161 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1162 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1163 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1164 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +00001165 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +00001166 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001167
Chris Lattner2188e402010-01-04 07:37:31 +00001168 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1169 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1170 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1171 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1172 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1173 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +00001174
Chris Lattner2188e402010-01-04 07:37:31 +00001175 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +00001176 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +00001177 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
1178}
1179
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001180/// Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS and CmpRHS are
1181/// both known to be integer constants.
Sanjay Patela3f4f082016-08-16 17:54:36 +00001182Instruction *InstCombiner::foldICmpDivConstConst(ICmpInst &ICI,
1183 BinaryOperator *DivI,
1184 ConstantInt *DivRHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001185 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
1186 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001187
1188 // FIXME: If the operand types don't match the type of the divide
Chris Lattner2188e402010-01-04 07:37:31 +00001189 // then don't attempt this transform. The code below doesn't have the
1190 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach129c52a2011-09-30 18:09:53 +00001191 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner2188e402010-01-04 07:37:31 +00001192 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach129c52a2011-09-30 18:09:53 +00001193 // (x /u C1) <u C2. Simply casting the operands and result won't
1194 // work. :( The if statement below tests that condition and bails
Chris Lattner98457102011-02-10 05:23:05 +00001195 // if it finds it.
Chris Lattner2188e402010-01-04 07:37:31 +00001196 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
1197 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Craig Topperf40110f2014-04-25 05:29:35 +00001198 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001199 if (DivRHS->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +00001200 return nullptr; // The ProdOV computation fails on divide by zero.
Chris Lattner2188e402010-01-04 07:37:31 +00001201 if (DivIsSigned && DivRHS->isAllOnesValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001202 return nullptr; // The overflow computation also screws up here
Chris Lattner43273af2011-02-13 08:07:21 +00001203 if (DivRHS->isOne()) {
1204 // This eliminates some funny cases with INT_MIN.
1205 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
1206 return &ICI;
1207 }
Chris Lattner2188e402010-01-04 07:37:31 +00001208
1209 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach129c52a2011-09-30 18:09:53 +00001210 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
1211 // C2 (CI). By solving for X we can turn this into a range check
1212 // instead of computing a divide.
Chris Lattner2188e402010-01-04 07:37:31 +00001213 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
1214
1215 // Determine if the product overflows by seeing if the product is
1216 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach129c52a2011-09-30 18:09:53 +00001217 // as in the LHS instruction that we're folding.
Chris Lattner2188e402010-01-04 07:37:31 +00001218 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
1219 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
1220
1221 // Get the ICmp opcode
1222 ICmpInst::Predicate Pred = ICI.getPredicate();
1223
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001224 // If the division is known to be exact, then there is no remainder from the
1225 // divide, so the covered range size is unit, otherwise it is the divisor.
Chris Lattner98457102011-02-10 05:23:05 +00001226 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001227
Chris Lattner2188e402010-01-04 07:37:31 +00001228 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach129c52a2011-09-30 18:09:53 +00001229 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner2188e402010-01-04 07:37:31 +00001230 // Compute this interval based on the constants involved and the signedness of
1231 // the compare/divide. This computes a half-open interval, keeping track of
1232 // whether either value in the interval overflows. After analysis each
1233 // overflow variable is set to 0 if it's corresponding bound variable is valid
1234 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
1235 int LoOverflow = 0, HiOverflow = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001236 Constant *LoBound = nullptr, *HiBound = nullptr;
Chris Lattner98457102011-02-10 05:23:05 +00001237
Chris Lattner2188e402010-01-04 07:37:31 +00001238 if (!DivIsSigned) { // udiv
1239 // e.g. X/5 op 3 --> [15, 20)
1240 LoBound = Prod;
1241 HiOverflow = LoOverflow = ProdOV;
Chris Lattner98457102011-02-10 05:23:05 +00001242 if (!HiOverflow) {
1243 // If this is not an exact divide, then many values in the range collapse
1244 // to the same result value.
1245 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
1246 }
Chris Lattner2188e402010-01-04 07:37:31 +00001247 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
1248 if (CmpRHSV == 0) { // (X / pos) op 0
1249 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner98457102011-02-10 05:23:05 +00001250 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
1251 HiBound = RangeSize;
Chris Lattner2188e402010-01-04 07:37:31 +00001252 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
1253 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
1254 HiOverflow = LoOverflow = ProdOV;
1255 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001256 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +00001257 } else { // (X / pos) op neg
1258 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
1259 HiBound = AddOne(Prod);
1260 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
1261 if (!LoOverflow) {
Chris Lattner98457102011-02-10 05:23:05 +00001262 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001263 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattner98457102011-02-10 05:23:05 +00001264 }
Chris Lattner2188e402010-01-04 07:37:31 +00001265 }
Chris Lattnerb1a15122011-07-15 06:08:15 +00001266 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattner98457102011-02-10 05:23:05 +00001267 if (DivI->isExact())
1268 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001269 if (CmpRHSV == 0) { // (X / neg) op 0
1270 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner98457102011-02-10 05:23:05 +00001271 LoBound = AddOne(RangeSize);
1272 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001273 if (HiBound == DivRHS) { // -INTMIN = INTMIN
1274 HiOverflow = 1; // [INTMIN+1, overflow)
Craig Topperf40110f2014-04-25 05:29:35 +00001275 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
Chris Lattner2188e402010-01-04 07:37:31 +00001276 }
1277 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
1278 // e.g. X/-5 op 3 --> [-19, -14)
1279 HiBound = AddOne(Prod);
1280 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
1281 if (!LoOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001282 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner2188e402010-01-04 07:37:31 +00001283 } else { // (X / neg) op neg
1284 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
1285 LoOverflow = HiOverflow = ProdOV;
1286 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001287 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +00001288 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001289
Chris Lattner2188e402010-01-04 07:37:31 +00001290 // Dividing by a negative swaps the condition. LT <-> GT
1291 Pred = ICmpInst::getSwappedPredicate(Pred);
1292 }
1293
1294 Value *X = DivI->getOperand(0);
1295 switch (Pred) {
1296 default: llvm_unreachable("Unhandled icmp opcode!");
1297 case ICmpInst::ICMP_EQ:
1298 if (LoOverflow && HiOverflow)
Sanjay Patel4b198802016-02-01 22:23:39 +00001299 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner067459c2010-03-05 08:46:26 +00001300 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001301 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1302 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +00001303 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001304 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1305 ICmpInst::ICMP_ULT, X, HiBound);
Sanjay Patel4b198802016-02-01 22:23:39 +00001306 return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
Chris Lattner98457102011-02-10 05:23:05 +00001307 DivIsSigned, true));
Chris Lattner2188e402010-01-04 07:37:31 +00001308 case ICmpInst::ICMP_NE:
1309 if (LoOverflow && HiOverflow)
Sanjay Patel4b198802016-02-01 22:23:39 +00001310 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner067459c2010-03-05 08:46:26 +00001311 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001312 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1313 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +00001314 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001315 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1316 ICmpInst::ICMP_UGE, X, HiBound);
Sanjay Patel4b198802016-02-01 22:23:39 +00001317 return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
Chris Lattner067459c2010-03-05 08:46:26 +00001318 DivIsSigned, false));
Chris Lattner2188e402010-01-04 07:37:31 +00001319 case ICmpInst::ICMP_ULT:
1320 case ICmpInst::ICMP_SLT:
1321 if (LoOverflow == +1) // Low bound is greater than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001322 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001323 if (LoOverflow == -1) // Low bound is less than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001324 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001325 return new ICmpInst(Pred, X, LoBound);
1326 case ICmpInst::ICMP_UGT:
1327 case ICmpInst::ICMP_SGT:
1328 if (HiOverflow == +1) // High bound greater than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001329 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner98457102011-02-10 05:23:05 +00001330 if (HiOverflow == -1) // High bound less than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001331 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001332 if (Pred == ICmpInst::ICMP_UGT)
1333 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +00001334 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner2188e402010-01-04 07:37:31 +00001335 }
1336}
1337
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001338/// Handle "icmp(([al]shr X, cst1), cst2)".
Sanjay Patela3f4f082016-08-16 17:54:36 +00001339Instruction *InstCombiner::foldICmpShrConstConst(ICmpInst &ICI,
1340 BinaryOperator *Shr,
1341 ConstantInt *ShAmt) {
Chris Lattnerd369f572011-02-13 07:43:07 +00001342 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001343
Chris Lattnerd369f572011-02-13 07:43:07 +00001344 // Check that the shift amount is in range. If not, don't perform
1345 // undefined shifts. When the shift is visited it will be
1346 // simplified.
1347 uint32_t TypeBits = CmpRHSV.getBitWidth();
1348 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner43273af2011-02-13 08:07:21 +00001349 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001350 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001351
Chris Lattner43273af2011-02-13 08:07:21 +00001352 if (!ICI.isEquality()) {
1353 // If we have an unsigned comparison and an ashr, we can't simplify this.
1354 // Similarly for signed comparisons with lshr.
1355 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
Craig Topperf40110f2014-04-25 05:29:35 +00001356 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001357
Eli Friedman865866e2011-05-25 23:26:20 +00001358 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
1359 // by a power of 2. Since we already have logic to simplify these,
1360 // transform to div and then simplify the resultant comparison.
Chris Lattner43273af2011-02-13 08:07:21 +00001361 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedman865866e2011-05-25 23:26:20 +00001362 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Craig Topperf40110f2014-04-25 05:29:35 +00001363 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001364
Chris Lattner43273af2011-02-13 08:07:21 +00001365 // Revisit the shift (to delete it).
1366 Worklist.Add(Shr);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001367
Chris Lattner43273af2011-02-13 08:07:21 +00001368 Constant *DivCst =
1369 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001370
Chris Lattner43273af2011-02-13 08:07:21 +00001371 Value *Tmp =
1372 Shr->getOpcode() == Instruction::AShr ?
1373 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
1374 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001375
Chris Lattner43273af2011-02-13 08:07:21 +00001376 ICI.setOperand(0, Tmp);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001377
Chris Lattner43273af2011-02-13 08:07:21 +00001378 // If the builder folded the binop, just return it.
1379 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
Craig Topperf40110f2014-04-25 05:29:35 +00001380 if (!TheDiv)
Chris Lattner43273af2011-02-13 08:07:21 +00001381 return &ICI;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001382
Chris Lattner43273af2011-02-13 08:07:21 +00001383 // Otherwise, fold this div/compare.
1384 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1385 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001386
Sanjay Patela3f4f082016-08-16 17:54:36 +00001387 Instruction *Res =
1388 foldICmpDivConstConst(ICI, TheDiv, cast<ConstantInt>(DivCst));
Chris Lattner43273af2011-02-13 08:07:21 +00001389 assert(Res && "This div/cst should have folded!");
1390 return Res;
1391 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001392
Chris Lattnerd369f572011-02-13 07:43:07 +00001393 // If we are comparing against bits always shifted out, the
1394 // comparison cannot succeed.
1395 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszakbddea112013-06-06 20:18:46 +00001396 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattnerd369f572011-02-13 07:43:07 +00001397 if (Shr->getOpcode() == Instruction::LShr)
1398 Comp = Comp.lshr(ShAmtVal);
1399 else
1400 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001401
Chris Lattnerd369f572011-02-13 07:43:07 +00001402 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1403 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001404 Constant *Cst = Builder->getInt1(IsICMP_NE);
Sanjay Patel4b198802016-02-01 22:23:39 +00001405 return replaceInstUsesWith(ICI, Cst);
Chris Lattnerd369f572011-02-13 07:43:07 +00001406 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001407
Chris Lattnerd369f572011-02-13 07:43:07 +00001408 // Otherwise, check to see if the bits shifted out are known to be zero.
1409 // If so, we can compare against the unshifted value:
1410 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattner9bd7fdf2011-02-13 18:30:09 +00001411 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattnerd369f572011-02-13 07:43:07 +00001412 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001413
Chris Lattnerd369f572011-02-13 07:43:07 +00001414 if (Shr->hasOneUse()) {
1415 // Otherwise strength reduce the shift into an and.
1416 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszakbddea112013-06-06 20:18:46 +00001417 Constant *Mask = Builder->getInt(Val);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001418
Chris Lattnerd369f572011-02-13 07:43:07 +00001419 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1420 Mask, Shr->getName()+".mask");
1421 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1422 }
Craig Topperf40110f2014-04-25 05:29:35 +00001423 return nullptr;
Chris Lattnerd369f572011-02-13 07:43:07 +00001424}
1425
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001426/// Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001427/// (icmp eq/ne A, Log2(const2/const1)) ->
1428/// (icmp eq/ne A, Log2(const2) - Log2(const1)).
Sanjay Patel43395062016-07-21 18:07:40 +00001429Instruction *InstCombiner::foldICmpCstShrConst(ICmpInst &I, Value *Op, Value *A,
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001430 ConstantInt *CI1,
1431 ConstantInt *CI2) {
1432 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1433
1434 auto getConstant = [&I, this](bool IsTrue) {
1435 if (I.getPredicate() == I.ICMP_NE)
1436 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001437 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001438 };
1439
1440 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1441 if (I.getPredicate() == I.ICMP_NE)
1442 Pred = CmpInst::getInversePredicate(Pred);
1443 return new ICmpInst(Pred, LHS, RHS);
1444 };
1445
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001446 const APInt &AP1 = CI1->getValue();
1447 const APInt &AP2 = CI2->getValue();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001448
David Majnemer2abb8182014-10-25 07:13:13 +00001449 // Don't bother doing any work for cases which InstSimplify handles.
1450 if (AP2 == 0)
1451 return nullptr;
1452 bool IsAShr = isa<AShrOperator>(Op);
1453 if (IsAShr) {
1454 if (AP2.isAllOnesValue())
1455 return nullptr;
1456 if (AP2.isNegative() != AP1.isNegative())
1457 return nullptr;
1458 if (AP2.sgt(AP1))
1459 return nullptr;
1460 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001461
David Majnemerd2056022014-10-21 19:51:55 +00001462 if (!AP1)
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001463 // 'A' must be large enough to shift out the highest set bit.
1464 return getICmp(I.ICMP_UGT, A,
1465 ConstantInt::get(A->getType(), AP2.logBase2()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001466
David Majnemerd2056022014-10-21 19:51:55 +00001467 if (AP1 == AP2)
1468 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001469
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001470 int Shift;
David Majnemerd2056022014-10-21 19:51:55 +00001471 if (IsAShr && AP1.isNegative())
David Majnemere5977eb2015-09-19 00:48:26 +00001472 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001473 else
David Majnemere5977eb2015-09-19 00:48:26 +00001474 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001475
David Majnemerd2056022014-10-21 19:51:55 +00001476 if (Shift > 0) {
David Majnemere5977eb2015-09-19 00:48:26 +00001477 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1478 // There are multiple solutions if we are comparing against -1 and the LHS
David Majnemer47ce0b82015-09-19 00:48:31 +00001479 // of the ashr is not a power of two.
David Majnemere5977eb2015-09-19 00:48:26 +00001480 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1481 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
David Majnemerd2056022014-10-21 19:51:55 +00001482 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
David Majnemere5977eb2015-09-19 00:48:26 +00001483 } else if (AP1 == AP2.lshr(Shift)) {
1484 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1485 }
David Majnemerd2056022014-10-21 19:51:55 +00001486 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001487 // Shifting const2 will never be equal to const1.
1488 return getConstant(false);
1489}
Chris Lattner2188e402010-01-04 07:37:31 +00001490
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001491/// Handle "(icmp eq/ne (shl const2, A), const1)" ->
David Majnemer59939ac2014-10-19 08:23:08 +00001492/// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)).
Sanjay Patel43395062016-07-21 18:07:40 +00001493Instruction *InstCombiner::foldICmpCstShlConst(ICmpInst &I, Value *Op, Value *A,
1494 ConstantInt *CI1,
1495 ConstantInt *CI2) {
David Majnemer59939ac2014-10-19 08:23:08 +00001496 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1497
1498 auto getConstant = [&I, this](bool IsTrue) {
1499 if (I.getPredicate() == I.ICMP_NE)
1500 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001501 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
David Majnemer59939ac2014-10-19 08:23:08 +00001502 };
1503
1504 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1505 if (I.getPredicate() == I.ICMP_NE)
1506 Pred = CmpInst::getInversePredicate(Pred);
1507 return new ICmpInst(Pred, LHS, RHS);
1508 };
1509
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001510 const APInt &AP1 = CI1->getValue();
1511 const APInt &AP2 = CI2->getValue();
David Majnemer59939ac2014-10-19 08:23:08 +00001512
David Majnemer2abb8182014-10-25 07:13:13 +00001513 // Don't bother doing any work for cases which InstSimplify handles.
1514 if (AP2 == 0)
1515 return nullptr;
David Majnemer59939ac2014-10-19 08:23:08 +00001516
1517 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1518
1519 if (!AP1 && AP2TrailingZeros != 0)
1520 return getICmp(I.ICMP_UGE, A,
1521 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1522
1523 if (AP1 == AP2)
1524 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1525
1526 // Get the distance between the lowest bits that are set.
1527 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1528
1529 if (Shift > 0 && AP2.shl(Shift) == AP1)
1530 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1531
1532 // Shifting const2 will never be equal to const1.
1533 return getConstant(false);
1534}
1535
Sanjay Patela3f4f082016-08-16 17:54:36 +00001536Instruction *InstCombiner::foldICmpTruncConstant(ICmpInst &ICI,
1537 Instruction *LHSI,
1538 const APInt *RHSV) {
1539 // FIXME: This check restricts all folds under here to scalar types.
1540 ConstantInt *RHS = dyn_cast<ConstantInt>(ICI.getOperand(1));
1541 if (!RHS)
1542 return nullptr;
1543
1544 if (RHS->isOne() && RHSV->getBitWidth() > 1) {
1545 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1546 Value *V = nullptr;
1547 if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1548 match(LHSI->getOperand(0), m_Signum(m_Value(V))))
1549 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1550 ConstantInt::get(V->getType(), 1));
1551 }
1552 if (ICI.isEquality() && LHSI->hasOneUse()) {
1553 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1554 // of the high bits truncated out of x are known.
1555 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1556 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
1557 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
1558 computeKnownBits(LHSI->getOperand(0), KnownZero, KnownOne, 0, &ICI);
1559
1560 // If all the high bits are known, we can do this xform.
1561 if ((KnownZero | KnownOne).countLeadingOnes() >= SrcBits - DstBits) {
1562 // Pull in the high bits from known-ones set.
1563 APInt NewRHS = RHS->getValue().zext(SrcBits);
1564 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1565 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1566 Builder->getInt(NewRHS));
1567 }
1568 }
1569 return nullptr;
1570}
1571
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001572/// Fold icmp (xor X, Y), C.
1573Instruction *InstCombiner::foldICmpXorConstant(ICmpInst &Cmp, Instruction *Xor,
1574 const APInt *C) {
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001575 Value *X = Xor->getOperand(0);
1576 Value *Y = Xor->getOperand(1);
Sanjay Pateldaffec912016-08-17 19:45:18 +00001577 const APInt *XorC;
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001578 if (!match(Y, m_APInt(XorC)))
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001579 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001580
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001581 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1582 // fold the xor.
1583 ICmpInst::Predicate Pred = Cmp.getPredicate();
1584 if ((Pred == ICmpInst::ICMP_SLT && *C == 0) ||
1585 (Pred == ICmpInst::ICMP_SGT && C->isAllOnesValue())) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001586
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001587 // If the sign bit of the XorCst is not set, there is no change to
1588 // the operation, just stop using the Xor.
Sanjay Pateldaffec912016-08-17 19:45:18 +00001589 if (!XorC->isNegative()) {
1590 Cmp.setOperand(0, X);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001591 Worklist.Add(Xor);
1592 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001593 }
1594
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001595 // Was the old condition true if the operand is positive?
1596 bool isTrueIfPositive = Pred == ICmpInst::ICMP_SGT;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001597
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001598 // If so, the new one isn't.
1599 isTrueIfPositive ^= true;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001600
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001601 Constant *CmpConstant = cast<Constant>(Cmp.getOperand(1));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001602 if (isTrueIfPositive)
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001603 return new ICmpInst(ICmpInst::ICMP_SGT, X, SubOne(CmpConstant));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001604 else
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001605 return new ICmpInst(ICmpInst::ICMP_SLT, X, AddOne(CmpConstant));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001606 }
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001607
1608 if (Xor->hasOneUse()) {
Sanjay Pateldaffec912016-08-17 19:45:18 +00001609 // (icmp u/s (xor X SignBit), C) -> (icmp s/u X, (xor C SignBit))
1610 if (!Cmp.isEquality() && XorC->isSignBit()) {
1611 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1612 : Cmp.getSignedPredicate();
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001613 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001614 }
1615
Sanjay Pateldaffec912016-08-17 19:45:18 +00001616 // (icmp u/s (xor X ~SignBit), C) -> (icmp s/u X, (xor C ~SignBit))
1617 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1618 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1619 : Cmp.getSignedPredicate();
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001620 Pred = Cmp.getSwappedPredicate(Pred);
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001621 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001622 }
1623 }
1624
1625 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1626 // iff -C is a power of 2
Sanjay Pateldaffec912016-08-17 19:45:18 +00001627 if (Pred == ICmpInst::ICMP_UGT && *XorC == ~(*C) && (*C + 1).isPowerOf2())
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001628 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001629
1630 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1631 // iff -C is a power of 2
Sanjay Pateldaffec912016-08-17 19:45:18 +00001632 if (Pred == ICmpInst::ICMP_ULT && *XorC == -(*C) && C->isPowerOf2())
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001633 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001634
Sanjay Patela3f4f082016-08-16 17:54:36 +00001635 return nullptr;
1636}
1637
1638Instruction *InstCombiner::foldICmpAndConstant(ICmpInst &ICI, Instruction *LHSI,
1639 const APInt *RHSV) {
1640 // FIXME: This check restricts all folds under here to scalar types.
1641 ConstantInt *RHS = dyn_cast<ConstantInt>(ICI.getOperand(1));
1642 if (!RHS)
1643 return nullptr;
1644
1645 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1646 LHSI->getOperand(0)->hasOneUse()) {
1647 ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
1648
1649 // If the LHS is an AND of a truncating cast, we can widen the
1650 // and/compare to be the input width without changing the value
1651 // produced, eliminating a cast.
1652 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1653 // We can do this transformation if either the AND constant does not
1654 // have its sign bit set or if it is an equality comparison.
1655 // Extending a relational comparison when we're checking the sign
1656 // bit would not work.
1657 if (ICI.isEquality() ||
1658 (!AndCst->isNegative() && RHSV->isNonNegative())) {
1659 Value *NewAnd =
1660 Builder->CreateAnd(Cast->getOperand(0),
1661 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
1662 NewAnd->takeName(LHSI);
1663 return new ICmpInst(ICI.getPredicate(), NewAnd,
1664 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
1665 }
1666 }
1667
1668 // If the LHS is an AND of a zext, and we have an equality compare, we can
1669 // shrink the and/compare to the smaller type, eliminating the cast.
1670 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
1671 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
1672 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1673 // should fold the icmp to true/false in that case.
1674 if (ICI.isEquality() && RHSV->getActiveBits() <= Ty->getBitWidth()) {
1675 Value *NewAnd = Builder->CreateAnd(Cast->getOperand(0),
1676 ConstantExpr::getTrunc(AndCst, Ty));
1677 NewAnd->takeName(LHSI);
1678 return new ICmpInst(ICI.getPredicate(), NewAnd,
1679 ConstantExpr::getTrunc(RHS, Ty));
1680 }
1681 }
1682
1683 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1684 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1685 // happens a LOT in code produced by the C front-end, for bitfield
1686 // access.
1687 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1688 if (Shift && !Shift->isShift())
1689 Shift = nullptr;
1690
1691 ConstantInt *ShAmt;
1692 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : nullptr;
1693
1694 // This seemingly simple opportunity to fold away a shift turns out to
1695 // be rather complicated. See PR17827
1696 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
1697 if (ShAmt) {
1698 bool CanFold = false;
1699 unsigned ShiftOpcode = Shift->getOpcode();
1700 if (ShiftOpcode == Instruction::AShr) {
1701 // There may be some constraints that make this possible,
1702 // but nothing simple has been discovered yet.
1703 CanFold = false;
1704 } else if (ShiftOpcode == Instruction::Shl) {
1705 // For a left shift, we can fold if the comparison is not signed.
1706 // We can also fold a signed comparison if the mask value and
1707 // comparison value are not negative. These constraints may not be
1708 // obvious, but we can prove that they are correct using an SMT
1709 // solver.
1710 if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
1711 CanFold = true;
1712 } else if (ShiftOpcode == Instruction::LShr) {
1713 // For a logical right shift, we can fold if the comparison is not
1714 // signed. We can also fold a signed comparison if the shifted mask
1715 // value and the shifted comparison value are not negative.
1716 // These constraints may not be obvious, but we can prove that they
1717 // are correct using an SMT solver.
1718 if (!ICI.isSigned())
1719 CanFold = true;
1720 else {
1721 ConstantInt *ShiftedAndCst =
1722 cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1723 ConstantInt *ShiftedRHSCst =
1724 cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1725
1726 if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1727 CanFold = true;
1728 }
1729 }
1730
1731 if (CanFold) {
1732 Constant *NewCst;
1733 if (ShiftOpcode == Instruction::Shl)
1734 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1735 else
1736 NewCst = ConstantExpr::getShl(RHS, ShAmt);
1737
1738 // Check to see if we are shifting out any of the bits being
1739 // compared.
1740 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
1741 // If we shifted bits out, the fold is not going to work out.
1742 // As a special case, check to see if this means that the
1743 // result is always true or false now.
1744 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1745 return replaceInstUsesWith(ICI, Builder->getFalse());
1746 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1747 return replaceInstUsesWith(ICI, Builder->getTrue());
1748 } else {
1749 ICI.setOperand(1, NewCst);
1750 Constant *NewAndCst;
1751 if (ShiftOpcode == Instruction::Shl)
1752 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
1753 else
1754 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1755 LHSI->setOperand(1, NewAndCst);
1756 LHSI->setOperand(0, Shift->getOperand(0));
1757 Worklist.Add(Shift); // Shift is dead.
1758 return &ICI;
1759 }
1760 }
1761 }
1762
1763 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1764 // preferable because it allows the C<<Y expression to be hoisted out
1765 // of a loop if Y is invariant and X is not.
1766 if (Shift && Shift->hasOneUse() && *RHSV == 0 && ICI.isEquality() &&
1767 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1768 // Compute C << Y.
1769 Value *NS;
1770 if (Shift->getOpcode() == Instruction::LShr) {
1771 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
1772 } else {
1773 // Insert a logical shift.
1774 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
1775 }
1776
1777 // Compute X & (C << Y).
1778 Value *NewAnd =
1779 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1780
1781 ICI.setOperand(0, NewAnd);
1782 return &ICI;
1783 }
1784
1785 // (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
1827 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1828 // bit set in (X & AndCst) will produce a result greater than RHSV.
1829 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
1830 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1831 if ((NTZ < AndCst->getBitWidth()) &&
1832 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(*RHSV))
1833 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1834 Constant::getNullValue(RHS->getType()));
1835 }
1836 }
1837
1838 // 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 = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1841 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1842 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1843 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1844 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1845 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, ICI, C))
1846 return Res;
1847 }
1848 }
1849
1850 // X & -C == -C -> X > u ~C
1851 // X & -C != -C -> X <= u ~C
1852 // iff C is a power of 2
1853 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-(*RHSV)).isPowerOf2())
1854 return new ICmpInst(ICI.getPredicate() == ICmpInst::ICMP_EQ
1855 ? ICmpInst::ICMP_UGT
1856 : ICmpInst::ICMP_ULE,
1857 LHSI->getOperand(0), SubOne(RHS));
1858
1859 // (icmp eq (and %A, C), 0) -> (icmp sgt (trunc %A), -1)
1860 // iff C is a power of 2
1861 if (ICI.isEquality() && LHSI->hasOneUse() && match(RHS, m_Zero())) {
1862 if (auto *CI = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1863 const APInt &AI = CI->getValue();
1864 int32_t ExactLogBase2 = AI.exactLogBase2();
1865 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1866 Type *NTy = IntegerType::get(ICI.getContext(), ExactLogBase2 + 1);
1867 Value *Trunc = Builder->CreateTrunc(LHSI->getOperand(0), NTy);
1868 return new ICmpInst(ICI.getPredicate() == ICmpInst::ICMP_EQ
1869 ? ICmpInst::ICMP_SGE
1870 : ICmpInst::ICMP_SLT,
1871 Trunc, Constant::getNullValue(NTy));
1872 }
1873 }
1874 }
1875 return nullptr;
1876}
1877
Sanjay Patel943e92e2016-08-17 16:30:43 +00001878/// Fold icmp (or X, Y), C.
1879Instruction *InstCombiner::foldICmpOrConstant(ICmpInst &Cmp, Instruction *Or,
1880 const APInt *C) {
Sanjay Patel943e92e2016-08-17 16:30:43 +00001881 ICmpInst::Predicate Pred = Cmp.getPredicate();
1882 if (*C == 1) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001883 // icmp slt signum(V) 1 --> icmp slt V, 1
1884 Value *V = nullptr;
Sanjay Patel943e92e2016-08-17 16:30:43 +00001885 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001886 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1887 ConstantInt::get(V->getType(), 1));
1888 }
1889
Sanjay Patel943e92e2016-08-17 16:30:43 +00001890 if (!Cmp.isEquality() || *C != 0 || !Or->hasOneUse())
Sanjay Patela3f4f082016-08-16 17:54:36 +00001891 return nullptr;
1892
1893 Value *P, *Q;
Sanjay Patel943e92e2016-08-17 16:30:43 +00001894 if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001895 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1896 // -> and (icmp eq P, null), (icmp eq Q, null).
Sanjay Patel943e92e2016-08-17 16:30:43 +00001897 Constant *NullVal = ConstantInt::getNullValue(P->getType());
1898 Value *CmpP = Builder->CreateICmp(Pred, P, NullVal);
1899 Value *CmpQ = Builder->CreateICmp(Pred, Q, NullVal);
1900 auto LogicOpc = Pred == ICmpInst::Predicate::ICMP_EQ ? Instruction::And
1901 : Instruction::Or;
1902 return BinaryOperator::Create(LogicOpc, CmpP, CmpQ);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001903 }
Sanjay Patel943e92e2016-08-17 16:30:43 +00001904
Sanjay Patela3f4f082016-08-16 17:54:36 +00001905 return nullptr;
1906}
1907
1908Instruction *InstCombiner::foldICmpMulConstant(ICmpInst &ICI, Instruction *LHSI,
1909 const APInt *RHSV) {
1910 // FIXME: This check restricts all folds under here to scalar types.
1911 ConstantInt *RHS = dyn_cast<ConstantInt>(ICI.getOperand(1));
1912 if (!RHS)
1913 return nullptr;
1914
1915 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1916 if (!Val)
1917 return nullptr;
1918
1919 // If this is a signed comparison to 0 and the mul is sign preserving,
1920 // use the mul LHS operand instead.
1921 ICmpInst::Predicate pred = ICI.getPredicate();
1922 if (isSignTest(pred, RHS) && !Val->isZero() &&
1923 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1924 return new ICmpInst(Val->isNegative() ?
1925 ICmpInst::getSwappedPredicate(pred) : pred,
1926 LHSI->getOperand(0),
1927 Constant::getNullValue(RHS->getType()));
1928
1929 return nullptr;
1930}
1931
1932Instruction *InstCombiner::foldICmpShlConstant(ICmpInst &ICI, Instruction *LHSI,
1933 const APInt *RHSV) {
1934 // FIXME: This check restricts all folds under here to scalar types.
1935 ConstantInt *RHS = dyn_cast<ConstantInt>(ICI.getOperand(1));
1936 if (!RHS)
1937 return nullptr;
1938
1939 uint32_t TypeBits = RHSV->getBitWidth();
1940 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1941 if (!ShAmt) {
1942 Value *X;
1943 // (1 << X) pred P2 -> X pred Log2(P2)
1944 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1945 bool RHSVIsPowerOf2 = RHSV->isPowerOf2();
1946 ICmpInst::Predicate Pred = ICI.getPredicate();
1947 if (ICI.isUnsigned()) {
1948 if (!RHSVIsPowerOf2) {
1949 // (1 << X) < 30 -> X <= 4
1950 // (1 << X) <= 30 -> X <= 4
1951 // (1 << X) >= 30 -> X > 4
1952 // (1 << X) > 30 -> X > 4
1953 if (Pred == ICmpInst::ICMP_ULT)
1954 Pred = ICmpInst::ICMP_ULE;
1955 else if (Pred == ICmpInst::ICMP_UGE)
1956 Pred = ICmpInst::ICMP_UGT;
1957 }
1958 unsigned RHSLog2 = RHSV->logBase2();
1959
1960 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
1961 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1962 if (RHSLog2 == TypeBits - 1) {
1963 if (Pred == ICmpInst::ICMP_UGE)
1964 Pred = ICmpInst::ICMP_EQ;
1965 else if (Pred == ICmpInst::ICMP_ULT)
1966 Pred = ICmpInst::ICMP_NE;
1967 }
1968
1969 return new ICmpInst(Pred, X, ConstantInt::get(RHS->getType(), RHSLog2));
1970 } else if (ICI.isSigned()) {
1971 if (RHSV->isAllOnesValue()) {
1972 // (1 << X) <= -1 -> X == 31
1973 if (Pred == ICmpInst::ICMP_SLE)
1974 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1975 ConstantInt::get(RHS->getType(), TypeBits - 1));
1976
1977 // (1 << X) > -1 -> X != 31
1978 if (Pred == ICmpInst::ICMP_SGT)
1979 return new ICmpInst(ICmpInst::ICMP_NE, X,
1980 ConstantInt::get(RHS->getType(), TypeBits - 1));
1981 } else if (!(*RHSV)) {
1982 // (1 << X) < 0 -> X == 31
1983 // (1 << X) <= 0 -> X == 31
1984 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1985 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1986 ConstantInt::get(RHS->getType(), TypeBits - 1));
1987
1988 // (1 << X) >= 0 -> X != 31
1989 // (1 << X) > 0 -> X != 31
1990 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1991 return new ICmpInst(ICmpInst::ICMP_NE, X,
1992 ConstantInt::get(RHS->getType(), TypeBits - 1));
1993 }
1994 } else if (ICI.isEquality()) {
1995 if (RHSVIsPowerOf2)
1996 return new ICmpInst(
1997 Pred, X, ConstantInt::get(RHS->getType(), RHSV->logBase2()));
1998 }
1999 }
2000 return nullptr;
2001 }
2002
2003 // Check that the shift amount is in range. If not, don't perform
2004 // undefined shifts. When the shift is visited it will be
2005 // simplified.
2006 if (ShAmt->uge(TypeBits))
2007 return nullptr;
2008
2009 if (ICI.isEquality()) {
2010 // If we are comparing against bits always shifted out, the
2011 // comparison cannot succeed.
2012 Constant *Comp =
2013 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
2014 if (Comp != RHS) { // Comparing against a bit that we know is zero.
2015 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
2016 Constant *Cst = Builder->getInt1(IsICMP_NE);
2017 return replaceInstUsesWith(ICI, Cst);
2018 }
2019
2020 // If the shift is NUW, then it is just shifting out zeros, no need for an
2021 // AND.
2022 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
2023 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2024 ConstantExpr::getLShr(RHS, ShAmt));
2025
2026 // If the shift is NSW and we compare to 0, then it is just shifting out
2027 // sign bits, no need for an AND either.
2028 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && *RHSV == 0)
2029 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2030 ConstantExpr::getLShr(RHS, ShAmt));
2031
2032 if (LHSI->hasOneUse()) {
2033 // Otherwise strength reduce the shift into an and.
2034 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
2035 Constant *Mask =
2036 Builder->getInt(APInt::getLowBitsSet(TypeBits, TypeBits - ShAmtVal));
2037
2038 Value *And = Builder->CreateAnd(LHSI->getOperand(0), Mask,
2039 LHSI->getName() + ".mask");
2040 return new ICmpInst(ICI.getPredicate(), And,
2041 ConstantExpr::getLShr(RHS, ShAmt));
2042 }
2043 }
2044
2045 // If this is a signed comparison to 0 and the shift is sign preserving,
2046 // use the shift LHS operand instead.
2047 ICmpInst::Predicate pred = ICI.getPredicate();
2048 if (isSignTest(pred, RHS) && cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
2049 return new ICmpInst(pred, LHSI->getOperand(0),
2050 Constant::getNullValue(RHS->getType()));
2051
2052 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2053 bool TrueIfSigned = false;
2054 if (LHSI->hasOneUse() &&
2055 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
2056 // (X << 31) <s 0 --> (X&1) != 0
2057 Constant *Mask = ConstantInt::get(
2058 LHSI->getOperand(0)->getType(),
2059 APInt::getOneBitSet(TypeBits, TypeBits - ShAmt->getZExtValue() - 1));
2060 Value *And = Builder->CreateAnd(LHSI->getOperand(0), Mask,
2061 LHSI->getName() + ".mask");
2062 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2063 And, Constant::getNullValue(And->getType()));
2064 }
2065
2066 // Transform (icmp pred iM (shl iM %v, N), CI)
2067 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
2068 // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
2069 // This enables to get rid of the shift in favor of a trunc which can be
2070 // free on the target. It has the additional benefit of comparing to a
2071 // smaller constant, which will be target friendly.
2072 unsigned Amt = ShAmt->getLimitedValue(TypeBits - 1);
2073 if (LHSI->hasOneUse() && Amt != 0 && RHSV->countTrailingZeros() >= Amt) {
2074 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
2075 Constant *NCI = ConstantExpr::getTrunc(
2076 ConstantExpr::getAShr(RHS, ConstantInt::get(RHS->getType(), Amt)), NTy);
2077 return new ICmpInst(ICI.getPredicate(),
2078 Builder->CreateTrunc(LHSI->getOperand(0), NTy), NCI);
2079 }
2080
2081 return nullptr;
2082}
2083
2084Instruction *InstCombiner::foldICmpShrConstant(ICmpInst &ICI, Instruction *LHSI,
2085 const APInt *RHSV) {
2086 // FIXME: This check restricts all folds under here to scalar types.
2087 ConstantInt *RHS = dyn_cast<ConstantInt>(ICI.getOperand(1));
2088 if (!RHS)
2089 return nullptr;
2090
2091 // Handle equality comparisons of shift-by-constant.
2092 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
2093 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2094 if (Instruction *Res = foldICmpShrConstConst(ICI, BO, ShAmt))
2095 return Res;
2096 }
2097
2098 // Handle exact shr's.
2099 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
2100 if (RHSV->isMinValue())
2101 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
2102 }
2103
2104 return nullptr;
2105}
2106
2107Instruction *InstCombiner::foldICmpUDivConstant(ICmpInst &ICI,
2108 Instruction *LHSI,
2109 const APInt *RHSV) {
2110 // FIXME: This check restricts all folds under here to scalar types.
2111 ConstantInt *RHS = dyn_cast<ConstantInt>(ICI.getOperand(1));
2112 if (!RHS)
2113 return nullptr;
2114
2115 if (ConstantInt *DivLHS = dyn_cast<ConstantInt>(LHSI->getOperand(0))) {
2116 Value *X = LHSI->getOperand(1);
2117 const APInt &C1 = RHS->getValue();
2118 const APInt &C2 = DivLHS->getValue();
2119 assert(C2 != 0 && "udiv 0, X should have been simplified already.");
2120 // (icmp ugt (udiv C2, X), C1) -> (icmp ule X, C2/(C1+1))
2121 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
2122 assert(!C1.isMaxValue() &&
2123 "icmp ugt X, UINT_MAX should have been simplified already.");
2124 return new ICmpInst(ICmpInst::ICMP_ULE, X,
2125 ConstantInt::get(X->getType(), C2.udiv(C1 + 1)));
2126 }
2127 // (icmp ult (udiv C2, X), C1) -> (icmp ugt X, C2/C1)
2128 if (ICI.getPredicate() == ICmpInst::ICMP_ULT) {
2129 assert(C1 != 0 && "icmp ult X, 0 should have been simplified already.");
2130 return new ICmpInst(ICmpInst::ICMP_UGT, X,
2131 ConstantInt::get(X->getType(), C2.udiv(C1)));
2132 }
2133 }
2134
2135 return nullptr;
2136}
2137
2138Instruction *InstCombiner::foldICmpDivConstant(ICmpInst &ICI, Instruction *LHSI,
2139 const APInt *RHSV) {
2140 // FIXME: This check restricts all folds under here to scalar types.
2141 ConstantInt *RHS = dyn_cast<ConstantInt>(ICI.getOperand(1));
2142 if (!RHS)
2143 return nullptr;
2144
2145 // Fold: icmp pred ([us]div X, C1), C2 -> range test
2146 // Fold this div into the comparison, producing a range check.
2147 // Determine, based on the divide type, what the range is being
2148 // checked. If there is an overflow on the low or high side, remember
2149 // it, otherwise compute the range [low, hi) bounding the new value.
2150 // See: InsertRangeTest above for the kinds of replacements possible.
2151 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
2152 if (Instruction *R =
2153 foldICmpDivConstConst(ICI, cast<BinaryOperator>(LHSI), DivRHS))
2154 return R;
2155
2156 return nullptr;
2157}
2158
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002159/// Fold icmp (sub X, Y), C.
2160Instruction *InstCombiner::foldICmpSubConstant(ICmpInst &Cmp, Instruction *Sub,
2161 const APInt *C) {
Sanjay Patele47df1a2016-08-16 21:53:19 +00002162 const APInt *C2;
2163 if (!match(Sub->getOperand(0), m_APInt(C2)) || !Sub->hasOneUse())
Sanjay Patela3f4f082016-08-16 17:54:36 +00002164 return nullptr;
2165
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002166 // C-X <u C2 -> (X|(C2-1)) == C
2167 // iff C & (C2-1) == C2-1
Sanjay Patela3f4f082016-08-16 17:54:36 +00002168 // C2 is a power of 2
Sanjay Patele47df1a2016-08-16 21:53:19 +00002169 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && C->isPowerOf2() &&
2170 (*C2 & (*C - 1)) == (*C - 1))
Sanjay Patela3f4f082016-08-16 17:54:36 +00002171 return new ICmpInst(ICmpInst::ICMP_EQ,
Sanjay Patele47df1a2016-08-16 21:53:19 +00002172 Builder->CreateOr(Sub->getOperand(1), *C - 1),
2173 Sub->getOperand(0));
Sanjay Patela3f4f082016-08-16 17:54:36 +00002174
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002175 // C-X >u C2 -> (X|C2) != C
2176 // iff C & C2 == C2
Sanjay Patela3f4f082016-08-16 17:54:36 +00002177 // C2+1 is a power of 2
Sanjay Patele47df1a2016-08-16 21:53:19 +00002178 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() &&
2179 (*C2 & *C) == *C)
Sanjay Patela3f4f082016-08-16 17:54:36 +00002180 return new ICmpInst(ICmpInst::ICMP_NE,
Sanjay Patele47df1a2016-08-16 21:53:19 +00002181 Builder->CreateOr(Sub->getOperand(1), *C),
2182 Sub->getOperand(0));
Sanjay Patela3f4f082016-08-16 17:54:36 +00002183
2184 return nullptr;
2185}
2186
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002187/// Fold icmp (add X, Y), C.
2188Instruction *InstCombiner::foldICmpAddConstant(ICmpInst &Cmp, Instruction *Add,
2189 const APInt *C) {
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002190 Value *Y = Add->getOperand(1);
2191 const APInt *C2;
2192 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00002193 return nullptr;
2194
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002195 // Fold icmp pred (add X, C2), C.
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002196 Value *X = Add->getOperand(0);
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002197 Type *Ty = Add->getType();
2198 auto CR = Cmp.makeConstantRange(Cmp.getPredicate(), *C).subtract(*C2);
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002199 const APInt &Upper = CR.getUpper();
2200 const APInt &Lower = CR.getLower();
2201 if (Cmp.isSigned()) {
2202 if (Lower.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002203 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002204 if (Upper.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002205 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002206 } else {
2207 if (Lower.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002208 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002209 if (Upper.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002210 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002211 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002212
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002213 if (!Add->hasOneUse())
2214 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002215
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002216 // X+C <u C2 -> (X & -C2) == C
2217 // iff C & (C2-1) == 0
2218 // C2 is a power of 2
2219 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && C->isPowerOf2() &&
2220 (*C2 & (*C - 1)) == 0)
2221 return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateAnd(X, -(*C)),
2222 ConstantExpr::getNeg(cast<Constant>(Y)));
2223
2224 // X+C >u C2 -> (X & ~C2) != C
2225 // iff C & C2 == 0
2226 // C2+1 is a power of 2
2227 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() &&
2228 (*C2 & *C) == 0)
2229 return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateAnd(X, ~(*C)),
2230 ConstantExpr::getNeg(cast<Constant>(Y)));
2231
Sanjay Patela3f4f082016-08-16 17:54:36 +00002232 return nullptr;
2233}
2234
Sanjay Patel1e5b2d12016-08-16 16:08:11 +00002235/// Try to fold integer comparisons with a constant operand: icmp Pred X, C.
2236Instruction *InstCombiner::foldICmpWithConstant(ICmpInst &ICI) {
2237 Instruction *LHSI;
2238 const APInt *RHSV;
2239 if (!match(ICI.getOperand(0), m_Instruction(LHSI)) ||
2240 !match(ICI.getOperand(1), m_APInt(RHSV)))
2241 return nullptr;
2242
Chris Lattner2188e402010-01-04 07:37:31 +00002243 switch (LHSI->getOpcode()) {
2244 case Instruction::Trunc:
Sanjay Patela3f4f082016-08-16 17:54:36 +00002245 if (Instruction *I = foldICmpTruncConstant(ICI, LHSI, RHSV))
2246 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002247 break;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002248 case Instruction::Xor:
2249 if (Instruction *I = foldICmpXorConstant(ICI, LHSI, RHSV))
2250 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002251 break;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002252 case Instruction::And:
2253 if (Instruction *I = foldICmpAndConstant(ICI, LHSI, RHSV))
2254 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002255 break;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002256 case Instruction::Or:
2257 if (Instruction *I = foldICmpOrConstant(ICI, LHSI, RHSV))
2258 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002259 break;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002260 case Instruction::Mul:
2261 if (Instruction *I = foldICmpMulConstant(ICI, LHSI, RHSV))
2262 return I;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002263 break;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002264 case Instruction::Shl:
2265 if (Instruction *I = foldICmpShlConstant(ICI, LHSI, RHSV))
2266 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002267 break;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002268 case Instruction::LShr:
2269 case Instruction::AShr:
2270 if (Instruction *I = foldICmpShrConstant(ICI, LHSI, RHSV))
2271 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002272 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002273 case Instruction::UDiv:
Sanjay Patela3f4f082016-08-16 17:54:36 +00002274 if (Instruction *I = foldICmpUDivConstant(ICI, LHSI, RHSV))
2275 return I;
Justin Bognerb03fd122016-08-17 05:10:15 +00002276 LLVM_FALLTHROUGH;
Chad Rosier4e6cda22016-05-10 20:22:09 +00002277 case Instruction::SDiv:
Sanjay Patela3f4f082016-08-16 17:54:36 +00002278 if (Instruction *I = foldICmpDivConstant(ICI, LHSI, RHSV))
2279 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002280 break;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002281 case Instruction::Sub:
2282 if (Instruction *I = foldICmpSubConstant(ICI, LHSI, RHSV))
2283 return I;
David Majnemerf2a9a512013-07-09 07:50:59 +00002284 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002285 case Instruction::Add:
Sanjay Patela3f4f082016-08-16 17:54:36 +00002286 if (Instruction *I = foldICmpAddConstant(ICI, LHSI, RHSV))
2287 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002288 break;
2289 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002290
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002291 return nullptr;
2292}
Jim Grosbach129c52a2011-09-30 18:09:53 +00002293
Sanjay Patelab50a932016-08-02 22:38:33 +00002294/// Simplify icmp_eq and icmp_ne instructions with binary operator LHS and
2295/// integer constant RHS.
2296Instruction *InstCombiner::foldICmpEqualityWithConstant(ICmpInst &ICI) {
Sanjay Patelab50a932016-08-02 22:38:33 +00002297 BinaryOperator *BO;
Sanjay Patel43aeb002016-08-03 18:59:03 +00002298 const APInt *RHSV;
2299 // FIXME: Some of these folds could work with arbitrary constants, but this
2300 // match is limited to scalars and vector splat constants.
Sanjay Patelab50a932016-08-02 22:38:33 +00002301 if (!ICI.isEquality() || !match(ICI.getOperand(0), m_BinOp(BO)) ||
Sanjay Patel43aeb002016-08-03 18:59:03 +00002302 !match(ICI.getOperand(1), m_APInt(RHSV)))
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002303 return nullptr;
2304
Sanjay Patel43aeb002016-08-03 18:59:03 +00002305 Constant *RHS = cast<Constant>(ICI.getOperand(1));
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002306 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002307 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002308
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002309 switch (BO->getOpcode()) {
2310 case Instruction::SRem:
2311 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Sanjay Patel2e9675f2016-08-03 19:48:40 +00002312 if (*RHSV == 0 && BO->hasOneUse()) {
2313 const APInt *BOC;
2314 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002315 Value *NewRem = Builder->CreateURem(BOp0, BOp1, BO->getName());
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002316 return new ICmpInst(ICI.getPredicate(), NewRem,
2317 Constant::getNullValue(BO->getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002318 }
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002319 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002320 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002321 case Instruction::Add: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002322 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
Sanjay Patel00a324e2016-08-03 22:08:44 +00002323 const APInt *BOC;
2324 if (match(BOp1, m_APInt(BOC))) {
2325 if (BO->hasOneUse()) {
2326 Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1));
2327 return new ICmpInst(ICI.getPredicate(), BOp0, SubC);
2328 }
Sanjay Patel43aeb002016-08-03 18:59:03 +00002329 } else if (*RHSV == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002330 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2331 // efficiently invertible, or if the add has just this one use.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002332 if (Value *NegVal = dyn_castNegVal(BOp1))
2333 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
2334 if (Value *NegVal = dyn_castNegVal(BOp0))
2335 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
2336 if (BO->hasOneUse()) {
2337 Value *Neg = Builder->CreateNeg(BOp1);
2338 Neg->takeName(BO);
2339 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
2340 }
2341 }
2342 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002343 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002344 case Instruction::Xor:
2345 if (BO->hasOneUse()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002346 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002347 // For the xor case, we can xor two constants together, eliminating
2348 // the explicit xor.
Sanjay Patel51a767c2016-08-03 17:23:08 +00002349 return new ICmpInst(ICI.getPredicate(), BOp0,
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002350 ConstantExpr::getXor(RHS, BOC));
Sanjay Patel43aeb002016-08-03 18:59:03 +00002351 } else if (*RHSV == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002352 // Replace ((xor A, B) != 0) with (A != B)
Sanjay Patel51a767c2016-08-03 17:23:08 +00002353 return new ICmpInst(ICI.getPredicate(), BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002354 }
2355 }
2356 break;
2357 case Instruction::Sub:
2358 if (BO->hasOneUse()) {
Sanjay Patel9d591d12016-08-04 15:19:25 +00002359 const APInt *BOC;
2360 if (match(BOp0, m_APInt(BOC))) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002361 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
Sanjay Patel9d591d12016-08-04 15:19:25 +00002362 Constant *SubC = ConstantExpr::getSub(cast<Constant>(BOp0), RHS);
2363 return new ICmpInst(ICI.getPredicate(), BOp1, SubC);
Sanjay Patel43aeb002016-08-03 18:59:03 +00002364 } else if (*RHSV == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002365 // Replace ((sub A, B) != 0) with (A != B)
Sanjay Patel51a767c2016-08-03 17:23:08 +00002366 return new ICmpInst(ICI.getPredicate(), BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002367 }
2368 }
2369 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002370 case Instruction::Or: {
2371 const APInt *BOC;
2372 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002373 // Comparing if all bits outside of a constant mask are set?
2374 // Replace (X | C) == -1 with (X & ~C) == ~C.
2375 // This removes the -1 constant.
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002376 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
2377 Value *And = Builder->CreateAnd(BOp0, NotBOC);
2378 return new ICmpInst(ICI.getPredicate(), And, NotBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002379 }
2380 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002381 }
Sanjay Pateld938e882016-08-04 20:05:02 +00002382 case Instruction::And: {
2383 const APInt *BOC;
2384 if (match(BOp1, m_APInt(BOC))) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002385 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Sanjay Pateld938e882016-08-04 20:05:02 +00002386 if (RHSV == BOC && RHSV->isPowerOf2())
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002387 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
Sanjay Patelab50a932016-08-02 22:38:33 +00002388 BO, Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002389
2390 // Don't perform the following transforms if the AND has multiple uses
2391 if (!BO->hasOneUse())
2392 break;
2393
2394 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Sanjay Pateld938e882016-08-04 20:05:02 +00002395 if (BOC->isSignBit()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002396 Constant *Zero = Constant::getNullValue(BOp0->getType());
2397 ICmpInst::Predicate Pred =
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002398 isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002399 return new ICmpInst(Pred, BOp0, Zero);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002400 }
2401
2402 // ((X & ~7) == 0) --> X < 8
Sanjay Pateld938e882016-08-04 20:05:02 +00002403 if (*RHSV == 0 && (~(*BOC) + 1).isPowerOf2()) {
2404 Constant *NegBOC = ConstantExpr::getNeg(cast<Constant>(BOp1));
Sanjay Patel51a767c2016-08-03 17:23:08 +00002405 ICmpInst::Predicate Pred =
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002406 isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Sanjay Pateld938e882016-08-04 20:05:02 +00002407 return new ICmpInst(Pred, BOp0, NegBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002408 }
2409 }
2410 break;
Sanjay Pateld938e882016-08-04 20:05:02 +00002411 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002412 case Instruction::Mul:
Sanjay Patel43aeb002016-08-03 18:59:03 +00002413 if (*RHSV == 0 && BO->hasNoSignedWrap()) {
Sanjay Patel3bade132016-08-04 22:19:27 +00002414 const APInt *BOC;
2415 if (match(BOp1, m_APInt(BOC)) && *BOC != 0) {
2416 // The trivial case (mul X, 0) is handled by InstSimplify.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002417 // General case : (mul X, C) != 0 iff X != 0
2418 // (mul X, C) == 0 iff X == 0
Sanjay Patel3bade132016-08-04 22:19:27 +00002419 return new ICmpInst(ICI.getPredicate(), BOp0,
2420 Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002421 }
2422 }
2423 break;
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002424 case Instruction::UDiv:
Sanjay Patel43aeb002016-08-03 18:59:03 +00002425 if (*RHSV == 0) {
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002426 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
2427 ICmpInst::Predicate Pred =
2428 isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002429 return new ICmpInst(Pred, BOp1, BOp0);
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002430 }
2431 break;
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002432 default:
2433 break;
2434 }
2435 return nullptr;
2436}
2437
Sanjay Patel1271bf92016-07-23 13:06:49 +00002438Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &ICI) {
2439 IntrinsicInst *II = dyn_cast<IntrinsicInst>(ICI.getOperand(0));
2440 const APInt *Op1C;
2441 if (!II || !ICI.isEquality() || !match(ICI.getOperand(1), m_APInt(Op1C)))
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002442 return nullptr;
2443
2444 // Handle icmp {eq|ne} <intrinsic>, intcst.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002445 switch (II->getIntrinsicID()) {
2446 case Intrinsic::bswap:
2447 Worklist.Add(II);
2448 ICI.setOperand(0, II->getArgOperand(0));
Sanjay Patel1271bf92016-07-23 13:06:49 +00002449 ICI.setOperand(1, Builder->getInt(Op1C->byteSwap()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002450 return &ICI;
2451 case Intrinsic::ctlz:
2452 case Intrinsic::cttz:
Amaury Sechet6bea6742016-08-04 05:27:20 +00002453 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
Sanjay Patel1271bf92016-07-23 13:06:49 +00002454 if (*Op1C == Op1C->getBitWidth()) {
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002455 Worklist.Add(II);
2456 ICI.setOperand(0, II->getArgOperand(0));
Sanjay Patel1271bf92016-07-23 13:06:49 +00002457 ICI.setOperand(1, ConstantInt::getNullValue(II->getType()));
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002458 return &ICI;
Chris Lattner2188e402010-01-04 07:37:31 +00002459 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002460 break;
Amaury Sechet6bea6742016-08-04 05:27:20 +00002461 case Intrinsic::ctpop: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002462 // popcount(A) == 0 -> A == 0 and likewise for !=
Amaury Sechet6bea6742016-08-04 05:27:20 +00002463 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
2464 bool IsZero = *Op1C == 0;
2465 if (IsZero || *Op1C == Op1C->getBitWidth()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002466 Worklist.Add(II);
2467 ICI.setOperand(0, II->getArgOperand(0));
Amaury Sechet6bea6742016-08-04 05:27:20 +00002468 auto *NewOp = IsZero
2469 ? ConstantInt::getNullValue(II->getType())
2470 : ConstantInt::getAllOnesValue(II->getType());
2471 ICI.setOperand(1, NewOp);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002472 return &ICI;
2473 }
Amaury Sechet6bea6742016-08-04 05:27:20 +00002474 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002475 break;
2476 default:
2477 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002478 }
Craig Topperf40110f2014-04-25 05:29:35 +00002479 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002480}
2481
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002482/// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so
2483/// far.
Sanjay Patel43395062016-07-21 18:07:40 +00002484Instruction *InstCombiner::foldICmpWithCastAndCast(ICmpInst &ICmp) {
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002485 const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00002486 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002487 Type *SrcTy = LHSCIOp->getType();
2488 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002489 Value *RHSCIOp;
2490
Jim Grosbach129c52a2011-09-30 18:09:53 +00002491 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00002492 // integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002493 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
2494 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002495 Value *RHSOp = nullptr;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002496 if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
Michael Liaod266b922015-02-13 04:51:26 +00002497 Value *RHSCIOp = RHSC->getOperand(0);
2498 if (RHSCIOp->getType()->getPointerAddressSpace() ==
2499 LHSCIOp->getType()->getPointerAddressSpace()) {
2500 RHSOp = RHSC->getOperand(0);
2501 // If the pointer types don't match, insert a bitcast.
2502 if (LHSCIOp->getType() != RHSOp->getType())
2503 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
2504 }
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002505 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002506 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002507 }
Chris Lattner2188e402010-01-04 07:37:31 +00002508
2509 if (RHSOp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002510 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002511 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002512
Chris Lattner2188e402010-01-04 07:37:31 +00002513 // The code below only handles extension cast instructions, so far.
2514 // Enforce this.
2515 if (LHSCI->getOpcode() != Instruction::ZExt &&
2516 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002517 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002518
2519 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002520 bool isSignedCmp = ICmp.isSigned();
Chris Lattner2188e402010-01-04 07:37:31 +00002521
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002522 if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002523 // Not an extension from the same type?
2524 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002525 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00002526 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002527
Chris Lattner2188e402010-01-04 07:37:31 +00002528 // If the signedness of the two casts doesn't agree (i.e. one is a sext
2529 // and the other is a zext), then we can't handle this.
2530 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00002531 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002532
2533 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002534 if (ICmp.isEquality())
2535 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002536
2537 // A signed comparison of sign extended values simplifies into a
2538 // signed comparison.
2539 if (isSignedCmp && isSignedExt)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002540 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002541
2542 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002543 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002544 }
2545
Sanjay Patel4c204232016-06-04 20:39:22 +00002546 // If we aren't dealing with a constant on the RHS, exit early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002547 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
2548 if (!C)
Craig Topperf40110f2014-04-25 05:29:35 +00002549 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002550
2551 // Compute the constant that would happen if we truncated to SrcTy then
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002552 // re-extended to DestTy.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002553 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002554 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattner2188e402010-01-04 07:37:31 +00002555
2556 // If the re-extended constant didn't change...
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002557 if (Res2 == C) {
Chris Lattner2188e402010-01-04 07:37:31 +00002558 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002559 if (ICmp.isEquality())
2560 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002561
2562 // A signed comparison of sign extended values simplifies into a
2563 // signed comparison.
2564 if (isSignedExt && isSignedCmp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002565 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002566
2567 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002568 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002569 }
2570
Sanjay Patel6a333c32016-06-06 16:56:57 +00002571 // The re-extended constant changed, partly changed (in the case of a vector),
2572 // or could not be determined to be equal (in the case of a constant
2573 // expression), so the constant cannot be represented in the shorter type.
2574 // Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002575 // All the cases that fold to true or false will have already been handled
2576 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00002577
Sanjay Patel6a333c32016-06-06 16:56:57 +00002578 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
Craig Topperf40110f2014-04-25 05:29:35 +00002579 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002580
2581 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
2582 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002583
2584 // We're performing an unsigned comp with a sign extended value.
2585 // This is true if the input is >= 0. [aka >s -1]
2586 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002587 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00002588
2589 // Finally, return the value computed.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002590 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
2591 return replaceInstUsesWith(ICmp, Result);
Chris Lattner2188e402010-01-04 07:37:31 +00002592
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002593 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00002594 return BinaryOperator::CreateNot(Result);
2595}
2596
Sanjay Patel5f0217f2016-06-05 16:46:18 +00002597/// The caller has matched a pattern of the form:
Chris Lattneree61c1d2010-12-19 17:52:50 +00002598/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00002599/// If this is of the form:
2600/// sum = a + b
2601/// if (sum+128 >u 255)
2602/// Then replace it with llvm.sadd.with.overflow.i8.
2603///
Chris Lattneree61c1d2010-12-19 17:52:50 +00002604static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2605 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00002606 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00002607 // The transformation we're trying to do here is to transform this into an
2608 // llvm.sadd.with.overflow. To do this, we have to replace the original add
2609 // with a narrower add, and discard the add-with-constant that is part of the
2610 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00002611
Chris Lattnerf29562d2010-12-19 17:59:02 +00002612 // In order to eliminate the add-with-constant, the compare can be its only
2613 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00002614 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00002615 if (!AddWithCst->hasOneUse()) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002616
Chris Lattnerc56c8452010-12-19 18:22:06 +00002617 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
Craig Topperf40110f2014-04-25 05:29:35 +00002618 if (!CI2->getValue().isPowerOf2()) return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002619 unsigned NewWidth = CI2->getValue().countTrailingZeros();
Craig Topperf40110f2014-04-25 05:29:35 +00002620 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002621
Chris Lattnerc56c8452010-12-19 18:22:06 +00002622 // The width of the new add formed is 1 more than the bias.
2623 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002624
Chris Lattnerc56c8452010-12-19 18:22:06 +00002625 // Check to see that CI1 is an all-ones value with NewWidth bits.
2626 if (CI1->getBitWidth() == NewWidth ||
2627 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
Craig Topperf40110f2014-04-25 05:29:35 +00002628 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002629
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002630 // This is only really a signed overflow check if the inputs have been
2631 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2632 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2633 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
Hal Finkel60db0582014-09-07 18:57:58 +00002634 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2635 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
Craig Topperf40110f2014-04-25 05:29:35 +00002636 return nullptr;
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002637
Jim Grosbach129c52a2011-09-30 18:09:53 +00002638 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00002639 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2640 // and truncates that discard the high bits of the add. Verify that this is
2641 // the case.
2642 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00002643 for (User *U : OrigAdd->users()) {
2644 if (U == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002645
Chris Lattnerc56c8452010-12-19 18:22:06 +00002646 // Only accept truncates for now. We would really like a nice recursive
2647 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2648 // chain to see which bits of a value are actually demanded. If the
2649 // original add had another add which was then immediately truncated, we
2650 // could still do the transformation.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002651 TruncInst *TI = dyn_cast<TruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00002652 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2653 return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002654 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002655
Chris Lattneree61c1d2010-12-19 17:52:50 +00002656 // If the pattern matches, truncate the inputs to the narrower type and
2657 // use the sadd_with_overflow intrinsic to efficiently compute both the
2658 // result and the overflow bit.
Jay Foadb804a2b2011-07-12 14:06:48 +00002659 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002660 Value *F = Intrinsic::getDeclaration(I.getModule(),
2661 Intrinsic::sadd_with_overflow, NewType);
Chris Lattner79874562010-12-19 18:35:09 +00002662
Chris Lattnerce2995a2010-12-19 18:38:44 +00002663 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002664
Chris Lattner79874562010-12-19 18:35:09 +00002665 // Put the new code above the original add, in case there are any uses of the
2666 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002667 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002668
Chris Lattner79874562010-12-19 18:35:09 +00002669 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2670 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
David Blaikieff6409d2015-05-18 22:13:54 +00002671 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
Chris Lattner79874562010-12-19 18:35:09 +00002672 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2673 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002674
Chris Lattneree61c1d2010-12-19 17:52:50 +00002675 // The inner add was the result of the narrow add, zero extended to the
2676 // wider type. Replace it with the result computed by the intrinsic.
Sanjay Patel4b198802016-02-01 22:23:39 +00002677 IC.replaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002678
Chris Lattner79874562010-12-19 18:35:09 +00002679 // The original icmp gets replaced with the overflow value.
2680 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00002681}
Chris Lattner2188e402010-01-04 07:37:31 +00002682
Sanjoy Dasb0984472015-04-08 04:27:22 +00002683bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
2684 Value *RHS, Instruction &OrigI,
2685 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00002686 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
2687 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002688
2689 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
2690 Result = OpResult;
2691 Overflow = OverflowVal;
2692 if (ReuseName)
2693 Result->takeName(&OrigI);
2694 return true;
2695 };
2696
Sanjoy Das6f5dca72015-08-28 19:09:31 +00002697 // If the overflow check was an add followed by a compare, the insertion point
2698 // may be pointing to the compare. We want to insert the new instructions
2699 // before the add in case there are uses of the add between the add and the
2700 // compare.
2701 Builder->SetInsertPoint(&OrigI);
2702
Sanjoy Dasb0984472015-04-08 04:27:22 +00002703 switch (OCF) {
2704 case OCF_INVALID:
2705 llvm_unreachable("bad overflow check kind!");
2706
2707 case OCF_UNSIGNED_ADD: {
2708 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
2709 if (OR == OverflowResult::NeverOverflows)
2710 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
2711 true);
2712
2713 if (OR == OverflowResult::AlwaysOverflows)
2714 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002715
2716 // Fall through uadd into sadd
2717 LLVM_FALLTHROUGH;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002718 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00002719 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002720 // X + 0 -> {X, false}
2721 if (match(RHS, m_Zero()))
2722 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002723
2724 // We can strength reduce this signed add into a regular add if we can prove
2725 // that it will never overflow.
2726 if (OCF == OCF_SIGNED_ADD)
2727 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
2728 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
2729 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00002730 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002731 }
2732
2733 case OCF_UNSIGNED_SUB:
2734 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002735 // X - 0 -> {X, false}
2736 if (match(RHS, m_Zero()))
2737 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002738
2739 if (OCF == OCF_SIGNED_SUB) {
2740 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
2741 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
2742 true);
2743 } else {
2744 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
2745 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
2746 true);
2747 }
2748 break;
2749 }
2750
2751 case OCF_UNSIGNED_MUL: {
2752 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
2753 if (OR == OverflowResult::NeverOverflows)
2754 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
2755 true);
2756 if (OR == OverflowResult::AlwaysOverflows)
2757 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002758 LLVM_FALLTHROUGH;
2759 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00002760 case OCF_SIGNED_MUL:
2761 // X * undef -> undef
2762 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00002763 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002764
David Majnemer27e89ba2015-05-21 23:04:21 +00002765 // X * 0 -> {0, false}
2766 if (match(RHS, m_Zero()))
2767 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002768
David Majnemer27e89ba2015-05-21 23:04:21 +00002769 // X * 1 -> {X, false}
2770 if (match(RHS, m_One()))
2771 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002772
2773 if (OCF == OCF_SIGNED_MUL)
2774 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
2775 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
2776 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00002777 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002778 }
2779
2780 return false;
2781}
2782
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002783/// \brief Recognize and process idiom involving test for multiplication
2784/// overflow.
2785///
2786/// The caller has matched a pattern of the form:
2787/// I = cmp u (mul(zext A, zext B), V
2788/// The function checks if this is a test for overflow and if so replaces
2789/// multiplication with call to 'mul.with.overflow' intrinsic.
2790///
2791/// \param I Compare instruction.
2792/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2793/// the compare instruction. Must be of integer type.
2794/// \param OtherVal The other argument of compare instruction.
2795/// \returns Instruction which must replace the compare instruction, NULL if no
2796/// replacement required.
2797static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2798 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00002799 // Don't bother doing this transformation for pointers, don't do it for
2800 // vectors.
2801 if (!isa<IntegerType>(MulVal->getType()))
2802 return nullptr;
2803
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002804 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2805 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00002806 auto *MulInstr = dyn_cast<Instruction>(MulVal);
2807 if (!MulInstr)
2808 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002809 assert(MulInstr->getOpcode() == Instruction::Mul);
2810
David Majnemer634ca232014-11-01 23:46:05 +00002811 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
2812 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002813 assert(LHS->getOpcode() == Instruction::ZExt);
2814 assert(RHS->getOpcode() == Instruction::ZExt);
2815 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2816
2817 // Calculate type and width of the result produced by mul.with.overflow.
2818 Type *TyA = A->getType(), *TyB = B->getType();
2819 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2820 WidthB = TyB->getPrimitiveSizeInBits();
2821 unsigned MulWidth;
2822 Type *MulType;
2823 if (WidthB > WidthA) {
2824 MulWidth = WidthB;
2825 MulType = TyB;
2826 } else {
2827 MulWidth = WidthA;
2828 MulType = TyA;
2829 }
2830
2831 // In order to replace the original mul with a narrower mul.with.overflow,
2832 // all uses must ignore upper bits of the product. The number of used low
2833 // bits must be not greater than the width of mul.with.overflow.
2834 if (MulVal->hasNUsesOrMore(2))
2835 for (User *U : MulVal->users()) {
2836 if (U == &I)
2837 continue;
2838 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2839 // Check if truncation ignores bits above MulWidth.
2840 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2841 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002842 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002843 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2844 // Check if AND ignores bits above MulWidth.
2845 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00002846 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002847 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2848 const APInt &CVal = CI->getValue();
2849 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002850 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002851 }
2852 } else {
2853 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00002854 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002855 }
2856 }
2857
2858 // Recognize patterns
2859 switch (I.getPredicate()) {
2860 case ICmpInst::ICMP_EQ:
2861 case ICmpInst::ICMP_NE:
2862 // Recognize pattern:
2863 // mulval = mul(zext A, zext B)
2864 // cmp eq/neq mulval, zext trunc mulval
2865 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2866 if (Zext->hasOneUse()) {
2867 Value *ZextArg = Zext->getOperand(0);
2868 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2869 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2870 break; //Recognized
2871 }
2872
2873 // Recognize pattern:
2874 // mulval = mul(zext A, zext B)
2875 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2876 ConstantInt *CI;
2877 Value *ValToMask;
2878 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2879 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00002880 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002881 const APInt &CVal = CI->getValue() + 1;
2882 if (CVal.isPowerOf2()) {
2883 unsigned MaskWidth = CVal.logBase2();
2884 if (MaskWidth == MulWidth)
2885 break; // Recognized
2886 }
2887 }
Craig Topperf40110f2014-04-25 05:29:35 +00002888 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002889
2890 case ICmpInst::ICMP_UGT:
2891 // Recognize pattern:
2892 // mulval = mul(zext A, zext B)
2893 // cmp ugt mulval, max
2894 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2895 APInt MaxVal = APInt::getMaxValue(MulWidth);
2896 MaxVal = MaxVal.zext(CI->getBitWidth());
2897 if (MaxVal.eq(CI->getValue()))
2898 break; // Recognized
2899 }
Craig Topperf40110f2014-04-25 05:29:35 +00002900 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002901
2902 case ICmpInst::ICMP_UGE:
2903 // Recognize pattern:
2904 // mulval = mul(zext A, zext B)
2905 // cmp uge mulval, max+1
2906 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2907 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2908 if (MaxVal.eq(CI->getValue()))
2909 break; // Recognized
2910 }
Craig Topperf40110f2014-04-25 05:29:35 +00002911 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002912
2913 case ICmpInst::ICMP_ULE:
2914 // Recognize pattern:
2915 // mulval = mul(zext A, zext B)
2916 // cmp ule mulval, max
2917 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2918 APInt MaxVal = APInt::getMaxValue(MulWidth);
2919 MaxVal = MaxVal.zext(CI->getBitWidth());
2920 if (MaxVal.eq(CI->getValue()))
2921 break; // Recognized
2922 }
Craig Topperf40110f2014-04-25 05:29:35 +00002923 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002924
2925 case ICmpInst::ICMP_ULT:
2926 // Recognize pattern:
2927 // mulval = mul(zext A, zext B)
2928 // cmp ule mulval, max + 1
2929 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002930 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002931 if (MaxVal.eq(CI->getValue()))
2932 break; // Recognized
2933 }
Craig Topperf40110f2014-04-25 05:29:35 +00002934 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002935
2936 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002937 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002938 }
2939
2940 InstCombiner::BuilderTy *Builder = IC.Builder;
2941 Builder->SetInsertPoint(MulInstr);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002942
2943 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2944 Value *MulA = A, *MulB = B;
2945 if (WidthA < MulWidth)
2946 MulA = Builder->CreateZExt(A, MulType);
2947 if (WidthB < MulWidth)
2948 MulB = Builder->CreateZExt(B, MulType);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002949 Value *F = Intrinsic::getDeclaration(I.getModule(),
2950 Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00002951 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002952 IC.Worklist.Add(MulInstr);
2953
2954 // If there are uses of mul result other than the comparison, we know that
2955 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002956 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002957 if (MulVal->hasNUsesOrMore(2)) {
2958 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2959 for (User *U : MulVal->users()) {
2960 if (U == &I || U == OtherVal)
2961 continue;
2962 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2963 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
Sanjay Patel4b198802016-02-01 22:23:39 +00002964 IC.replaceInstUsesWith(*TI, Mul);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002965 else
2966 TI->setOperand(0, Mul);
2967 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2968 assert(BO->getOpcode() == Instruction::And);
2969 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2970 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2971 APInt ShortMask = CI->getValue().trunc(MulWidth);
2972 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2973 Instruction *Zext =
2974 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2975 IC.Worklist.Add(Zext);
Sanjay Patel4b198802016-02-01 22:23:39 +00002976 IC.replaceInstUsesWith(*BO, Zext);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002977 } else {
2978 llvm_unreachable("Unexpected Binary operation");
2979 }
2980 IC.Worklist.Add(cast<Instruction>(U));
2981 }
2982 }
2983 if (isa<Instruction>(OtherVal))
2984 IC.Worklist.Add(cast<Instruction>(OtherVal));
2985
2986 // The original icmp gets replaced with the overflow value, maybe inverted
2987 // depending on predicate.
2988 bool Inverse = false;
2989 switch (I.getPredicate()) {
2990 case ICmpInst::ICMP_NE:
2991 break;
2992 case ICmpInst::ICMP_EQ:
2993 Inverse = true;
2994 break;
2995 case ICmpInst::ICMP_UGT:
2996 case ICmpInst::ICMP_UGE:
2997 if (I.getOperand(0) == MulVal)
2998 break;
2999 Inverse = true;
3000 break;
3001 case ICmpInst::ICMP_ULT:
3002 case ICmpInst::ICMP_ULE:
3003 if (I.getOperand(1) == MulVal)
3004 break;
3005 Inverse = true;
3006 break;
3007 default:
3008 llvm_unreachable("Unexpected predicate");
3009 }
3010 if (Inverse) {
3011 Value *Res = Builder->CreateExtractValue(Call, 1);
3012 return BinaryOperator::CreateNot(Res);
3013 }
3014
3015 return ExtractValueInst::Create(Call, 1);
3016}
3017
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003018/// When performing a comparison against a constant, it is possible that not all
3019/// the bits in the LHS are demanded. This helper method computes the mask that
3020/// IS demanded.
Owen Andersond490c2d2011-01-11 00:36:45 +00003021static APInt DemandedBitsLHSMask(ICmpInst &I,
3022 unsigned BitWidth, bool isSignCheck) {
3023 if (isSignCheck)
3024 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003025
Owen Andersond490c2d2011-01-11 00:36:45 +00003026 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3027 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00003028 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003029
Owen Andersond490c2d2011-01-11 00:36:45 +00003030 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003031 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00003032 // correspond to the trailing ones of the comparand. The value of these
3033 // bits doesn't impact the outcome of the comparison, because any value
3034 // greater than the RHS must differ in a bit higher than these due to carry.
3035 case ICmpInst::ICMP_UGT: {
3036 unsigned trailingOnes = RHS.countTrailingOnes();
3037 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
3038 return ~lowBitsSet;
3039 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003040
Owen Andersond490c2d2011-01-11 00:36:45 +00003041 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
3042 // Any value less than the RHS must differ in a higher bit because of carries.
3043 case ICmpInst::ICMP_ULT: {
3044 unsigned trailingZeros = RHS.countTrailingZeros();
3045 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
3046 return ~lowBitsSet;
3047 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003048
Owen Andersond490c2d2011-01-11 00:36:45 +00003049 default:
3050 return APInt::getAllOnesValue(BitWidth);
3051 }
Owen Andersond490c2d2011-01-11 00:36:45 +00003052}
Chris Lattner2188e402010-01-04 07:37:31 +00003053
Quentin Colombet5ab55552013-09-09 20:56:48 +00003054/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
3055/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00003056/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00003057/// as subtract operands and their positions in those instructions.
3058/// The rational is that several architectures use the same instruction for
3059/// both subtract and cmp, thus it is better if the order of those operands
3060/// match.
3061/// \return true if Op0 and Op1 should be swapped.
3062static bool swapMayExposeCSEOpportunities(const Value * Op0,
3063 const Value * Op1) {
3064 // Filter out pointer value as those cannot appears directly in subtract.
3065 // FIXME: we may want to go through inttoptrs or bitcasts.
3066 if (Op0->getType()->isPointerTy())
3067 return false;
3068 // Count every uses of both Op0 and Op1 in a subtract.
3069 // Each time Op0 is the first operand, count -1: swapping is bad, the
3070 // subtract has already the same layout as the compare.
3071 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00003072 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003073 // At the end, if the benefit is greater than 0, Op0 should come second to
3074 // expose more CSE opportunities.
3075 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003076 for (const User *U : Op0->users()) {
3077 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003078 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
3079 continue;
3080 // If Op0 is the first argument, this is not beneficial to swap the
3081 // arguments.
3082 int LocalSwapBenefits = -1;
3083 unsigned Op1Idx = 1;
3084 if (BinOp->getOperand(Op1Idx) == Op0) {
3085 Op1Idx = 0;
3086 LocalSwapBenefits = 1;
3087 }
3088 if (BinOp->getOperand(Op1Idx) != Op1)
3089 continue;
3090 GlobalSwapBenefits += LocalSwapBenefits;
3091 }
3092 return GlobalSwapBenefits > 0;
3093}
3094
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003095/// \brief Check that one use is in the same block as the definition and all
3096/// other uses are in blocks dominated by a given block
3097///
3098/// \param DI Definition
3099/// \param UI Use
3100/// \param DB Block that must dominate all uses of \p DI outside
3101/// the parent block
3102/// \return true when \p UI is the only use of \p DI in the parent block
3103/// and all other uses of \p DI are in blocks dominated by \p DB.
3104///
3105bool InstCombiner::dominatesAllUses(const Instruction *DI,
3106 const Instruction *UI,
3107 const BasicBlock *DB) const {
3108 assert(DI && UI && "Instruction not defined\n");
3109 // ignore incomplete definitions
3110 if (!DI->getParent())
3111 return false;
3112 // DI and UI must be in the same block
3113 if (DI->getParent() != UI->getParent())
3114 return false;
3115 // Protect from self-referencing blocks
3116 if (DI->getParent() == DB)
3117 return false;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003118 for (const User *U : DI->users()) {
3119 auto *Usr = cast<Instruction>(U);
Justin Bogner99798402016-08-05 01:06:44 +00003120 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003121 return false;
3122 }
3123 return true;
3124}
3125
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003126/// Return true when the instruction sequence within a block is select-cmp-br.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003127static bool isChainSelectCmpBranch(const SelectInst *SI) {
3128 const BasicBlock *BB = SI->getParent();
3129 if (!BB)
3130 return false;
3131 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
3132 if (!BI || BI->getNumSuccessors() != 2)
3133 return false;
3134 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
3135 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
3136 return false;
3137 return true;
3138}
3139
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003140/// \brief True when a select result is replaced by one of its operands
3141/// in select-icmp sequence. This will eventually result in the elimination
3142/// of the select.
3143///
3144/// \param SI Select instruction
3145/// \param Icmp Compare instruction
3146/// \param SIOpd Operand that replaces the select
3147///
3148/// Notes:
3149/// - The replacement is global and requires dominator information
3150/// - The caller is responsible for the actual replacement
3151///
3152/// Example:
3153///
3154/// entry:
3155/// %4 = select i1 %3, %C* %0, %C* null
3156/// %5 = icmp eq %C* %4, null
3157/// br i1 %5, label %9, label %7
3158/// ...
3159/// ; <label>:7 ; preds = %entry
3160/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
3161/// ...
3162///
3163/// can be transformed to
3164///
3165/// %5 = icmp eq %C* %0, null
3166/// %6 = select i1 %3, i1 %5, i1 true
3167/// br i1 %6, label %9, label %7
3168/// ...
3169/// ; <label>:7 ; preds = %entry
3170/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
3171///
3172/// Similar when the first operand of the select is a constant or/and
3173/// the compare is for not equal rather than equal.
3174///
3175/// NOTE: The function is only called when the select and compare constants
3176/// are equal, the optimization can work only for EQ predicates. This is not a
3177/// major restriction since a NE compare should be 'normalized' to an equal
3178/// compare, which usually happens in the combiner and test case
3179/// select-cmp-br.ll
3180/// checks for it.
3181bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
3182 const ICmpInst *Icmp,
3183 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00003184 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003185 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
3186 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
3187 // The check for the unique predecessor is not the best that can be
3188 // done. But it protects efficiently against cases like when SI's
3189 // home block has two successors, Succ and Succ1, and Succ1 predecessor
3190 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
3191 // replaced can be reached on either path. So the uniqueness check
3192 // guarantees that the path all uses of SI (outside SI's parent) are on
3193 // is disjoint from all other paths out of SI. But that information
3194 // is more expensive to compute, and the trade-off here is in favor
3195 // of compile-time.
3196 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
3197 NumSel++;
3198 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
3199 return true;
3200 }
3201 }
3202 return false;
3203}
3204
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003205/// If we have an icmp le or icmp ge instruction with a constant operand, turn
3206/// it into the appropriate icmp lt or icmp gt instruction. This transform
3207/// allows them to be folded in visitICmpInst.
Sanjay Patele9b2c322016-05-17 00:57:57 +00003208static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
3209 ICmpInst::Predicate Pred = I.getPredicate();
3210 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE &&
3211 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE)
3212 return nullptr;
3213
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003214 Value *Op0 = I.getOperand(0);
3215 Value *Op1 = I.getOperand(1);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003216 auto *Op1C = dyn_cast<Constant>(Op1);
3217 if (!Op1C)
3218 return nullptr;
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003219
Sanjay Patele9b2c322016-05-17 00:57:57 +00003220 // Check if the constant operand can be safely incremented/decremented without
3221 // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled
3222 // the edge cases for us, so we just assert on them. For vectors, we must
3223 // handle the edge cases.
3224 Type *Op1Type = Op1->getType();
3225 bool IsSigned = I.isSigned();
3226 bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE);
Sanjay Patel18254932016-05-17 01:12:31 +00003227 auto *CI = dyn_cast<ConstantInt>(Op1C);
3228 if (CI) {
Sanjay Patele9b2c322016-05-17 00:57:57 +00003229 // A <= MAX -> TRUE ; A >= MIN -> TRUE
3230 assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned));
3231 } else if (Op1Type->isVectorTy()) {
Sanjay Patelb79ab272016-05-13 15:10:46 +00003232 // TODO? If the edge cases for vectors were guaranteed to be handled as they
Sanjay Patele9b2c322016-05-17 00:57:57 +00003233 // are for scalar, we could remove the min/max checks. However, to do that,
3234 // we would have to use insertelement/shufflevector to replace edge values.
3235 unsigned NumElts = Op1Type->getVectorNumElements();
3236 for (unsigned i = 0; i != NumElts; ++i) {
3237 Constant *Elt = Op1C->getAggregateElement(i);
Benjamin Kramerca9a0fe2016-05-17 12:08:55 +00003238 if (!Elt)
3239 return nullptr;
3240
Sanjay Patele9b2c322016-05-17 00:57:57 +00003241 if (isa<UndefValue>(Elt))
3242 continue;
3243 // Bail out if we can't determine if this constant is min/max or if we
3244 // know that this constant is min/max.
3245 auto *CI = dyn_cast<ConstantInt>(Elt);
3246 if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned)))
3247 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003248 }
Sanjay Patele9b2c322016-05-17 00:57:57 +00003249 } else {
3250 // ConstantExpr?
3251 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003252 }
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003253
Sanjay Patele9b2c322016-05-17 00:57:57 +00003254 // Increment or decrement the constant and set the new comparison predicate:
3255 // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT
Sanjay Patel22b01fe2016-05-17 20:20:40 +00003256 Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003257 CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT;
3258 NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred;
3259 return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne));
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003260}
3261
Chris Lattner2188e402010-01-04 07:37:31 +00003262Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
3263 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00003264 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003265 unsigned Op0Cplxity = getComplexity(Op0);
3266 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003267
Chris Lattner2188e402010-01-04 07:37:31 +00003268 /// Orders the operands of the compare so that they are listed from most
3269 /// complex to least complex. This puts constants before unary operators,
3270 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003271 if (Op0Cplxity < Op1Cplxity ||
Sanjay Patel4c204232016-06-04 20:39:22 +00003272 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003273 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00003274 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003275 Changed = true;
3276 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003277
Jingyue Wu5e34ce32015-06-25 20:14:47 +00003278 if (Value *V =
Justin Bogner99798402016-08-05 01:06:44 +00003279 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00003280 return replaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003281
Pete Cooperbc5c5242011-12-01 03:58:40 +00003282 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00003283 // ie, abs(val) != 0 -> val != 0
Sanjay Patel4c204232016-06-04 20:39:22 +00003284 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003285 Value *Cond, *SelectTrue, *SelectFalse;
3286 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00003287 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003288 if (Value *V = dyn_castNegVal(SelectTrue)) {
3289 if (V == SelectFalse)
3290 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
3291 }
3292 else if (Value *V = dyn_castNegVal(SelectFalse)) {
3293 if (V == SelectTrue)
3294 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00003295 }
3296 }
3297 }
3298
Chris Lattner229907c2011-07-18 04:54:35 +00003299 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00003300
3301 // icmp's with boolean values can always be turned into bitwise operations
Sanjay Patela6fbc822016-06-05 17:49:45 +00003302 if (Ty->getScalarType()->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00003303 switch (I.getPredicate()) {
3304 default: llvm_unreachable("Invalid icmp instruction!");
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003305 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
3306 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003307 return BinaryOperator::CreateNot(Xor);
3308 }
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003309 case ICmpInst::ICMP_NE: // icmp ne i1 A, B -> A^B
Chris Lattner2188e402010-01-04 07:37:31 +00003310 return BinaryOperator::CreateXor(Op0, Op1);
3311
3312 case ICmpInst::ICMP_UGT:
3313 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003314 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003315 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
3316 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003317 return BinaryOperator::CreateAnd(Not, Op1);
3318 }
3319 case ICmpInst::ICMP_SGT:
3320 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003321 LLVM_FALLTHROUGH;
Chris Lattner2188e402010-01-04 07:37:31 +00003322 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003323 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003324 return BinaryOperator::CreateAnd(Not, Op0);
3325 }
3326 case ICmpInst::ICMP_UGE:
3327 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003328 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003329 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
3330 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003331 return BinaryOperator::CreateOr(Not, Op1);
3332 }
3333 case ICmpInst::ICMP_SGE:
3334 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003335 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003336 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
3337 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003338 return BinaryOperator::CreateOr(Not, Op0);
3339 }
3340 }
3341 }
3342
Sanjay Patele9b2c322016-05-17 00:57:57 +00003343 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003344 return NewICmp;
3345
Chris Lattner2188e402010-01-04 07:37:31 +00003346 unsigned BitWidth = 0;
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003347 if (Ty->isIntOrIntVectorTy())
Chris Lattner2188e402010-01-04 07:37:31 +00003348 BitWidth = Ty->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003349 else // Get pointer size.
3350 BitWidth = DL.getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00003351
Chris Lattner2188e402010-01-04 07:37:31 +00003352 bool isSignBit = false;
3353
3354 // See if we are doing a comparison with a constant.
3355 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00003356 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003357
Owen Anderson1294ea72010-12-17 18:08:00 +00003358 // Match the following pattern, which is a common idiom when writing
3359 // overflow-safe integer arithmetic function. The source performs an
3360 // addition in wider type, and explicitly checks for overflow using
3361 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
3362 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00003363 //
3364 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00003365 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00003366 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003367 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00003368 // sum = a + b
3369 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00003370 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00003371 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00003372 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00003373 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00003374 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00003375 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00003376 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003377
Philip Reamesec8a8b52016-03-09 21:05:07 +00003378 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
3379 if (CI->isZero() && I.getPredicate() == ICmpInst::ICMP_SGT)
3380 if (auto *SI = dyn_cast<SelectInst>(Op0)) {
3381 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
3382 if (SPR.Flavor == SPF_SMIN) {
Philip Reames8f12eba2016-03-09 21:31:47 +00003383 if (isKnownPositive(A, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003384 return new ICmpInst(I.getPredicate(), B, CI);
Philip Reames8f12eba2016-03-09 21:31:47 +00003385 if (isKnownPositive(B, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003386 return new ICmpInst(I.getPredicate(), A, CI);
3387 }
3388 }
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00003389
Philip Reamesec8a8b52016-03-09 21:05:07 +00003390
David Majnemera0afb552015-01-14 19:26:56 +00003391 // The following transforms are only 'worth it' if the only user of the
3392 // subtraction is the icmp.
3393 if (Op0->hasOneUse()) {
3394 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
3395 if (I.isEquality() && CI->isZero() &&
3396 match(Op0, m_Sub(m_Value(A), m_Value(B))))
3397 return new ICmpInst(I.getPredicate(), A, B);
3398
3399 // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
3400 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
3401 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3402 return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
3403
3404 // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
3405 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
3406 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3407 return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
3408
3409 // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
3410 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
3411 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3412 return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
3413
3414 // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
3415 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
3416 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3417 return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
Chris Lattner2188e402010-01-04 07:37:31 +00003418 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003419
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003420 if (I.isEquality()) {
3421 ConstantInt *CI2;
3422 if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
3423 match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
David Majnemer59939ac2014-10-19 08:23:08 +00003424 // (icmp eq/ne (ashr/lshr const2, A), const1)
Sanjay Patel43395062016-07-21 18:07:40 +00003425 if (Instruction *Inst = foldICmpCstShrConst(I, Op0, A, CI, CI2))
David Majnemer2abb8182014-10-25 07:13:13 +00003426 return Inst;
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003427 }
David Majnemer59939ac2014-10-19 08:23:08 +00003428 if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
3429 // (icmp eq/ne (shl const2, A), const1)
Sanjay Patel43395062016-07-21 18:07:40 +00003430 if (Instruction *Inst = foldICmpCstShlConst(I, Op0, A, CI, CI2))
David Majnemer2abb8182014-10-25 07:13:13 +00003431 return Inst;
David Majnemer59939ac2014-10-19 08:23:08 +00003432 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003433 }
3434
Chris Lattner2188e402010-01-04 07:37:31 +00003435 // If this comparison is a normal comparison, it demands all
3436 // bits, if it is a sign bit comparison, it only demands the sign bit.
3437 bool UnusedBit;
3438 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
Balaram Makam569eaec2016-05-04 21:32:14 +00003439
3440 // Canonicalize icmp instructions based on dominating conditions.
3441 BasicBlock *Parent = I.getParent();
3442 BasicBlock *Dom = Parent->getSinglePredecessor();
3443 auto *BI = Dom ? dyn_cast<BranchInst>(Dom->getTerminator()) : nullptr;
3444 ICmpInst::Predicate Pred;
3445 BasicBlock *TrueBB, *FalseBB;
3446 ConstantInt *CI2;
3447 if (BI && match(BI, m_Br(m_ICmp(Pred, m_Specific(Op0), m_ConstantInt(CI2)),
3448 TrueBB, FalseBB)) &&
3449 TrueBB != FalseBB) {
3450 ConstantRange CR = ConstantRange::makeAllowedICmpRegion(I.getPredicate(),
3451 CI->getValue());
3452 ConstantRange DominatingCR =
3453 (Parent == TrueBB)
3454 ? ConstantRange::makeExactICmpRegion(Pred, CI2->getValue())
3455 : ConstantRange::makeExactICmpRegion(
3456 CmpInst::getInversePredicate(Pred), CI2->getValue());
3457 ConstantRange Intersection = DominatingCR.intersectWith(CR);
3458 ConstantRange Difference = DominatingCR.difference(CR);
3459 if (Intersection.isEmptySet())
3460 return replaceInstUsesWith(I, Builder->getFalse());
3461 if (Difference.isEmptySet())
3462 return replaceInstUsesWith(I, Builder->getTrue());
3463 // Canonicalizing a sign bit comparison that gets used in a branch,
3464 // pessimizes codegen by generating branch on zero instruction instead
3465 // of a test and branch. So we avoid canonicalizing in such situations
3466 // because test and branch instruction has better branch displacement
3467 // than compare and branch instruction.
3468 if (!isBranchOnSignBitCheck(I, isSignBit) && !I.isEquality()) {
3469 if (auto *AI = Intersection.getSingleElement())
3470 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Builder->getInt(*AI));
3471 if (auto *AD = Difference.getSingleElement())
3472 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Builder->getInt(*AD));
3473 }
3474 }
Chris Lattner2188e402010-01-04 07:37:31 +00003475 }
3476
3477 // See if we can fold the comparison based on range information we can get
3478 // by checking whether bits are known to be zero or one in the input.
3479 if (BitWidth != 0) {
3480 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
3481 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
3482
3483 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersond490c2d2011-01-11 00:36:45 +00003484 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner2188e402010-01-04 07:37:31 +00003485 Op0KnownZero, Op0KnownOne, 0))
3486 return &I;
3487 if (SimplifyDemandedBits(I.getOperandUse(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003488 APInt::getAllOnesValue(BitWidth), Op1KnownZero,
3489 Op1KnownOne, 0))
Chris Lattner2188e402010-01-04 07:37:31 +00003490 return &I;
3491
3492 // Given the known and unknown bits, compute a range that the LHS could be
3493 // in. Compute the Min, Max and RHS values based on the known bits. For the
3494 // EQ and NE we use unsigned values.
3495 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
3496 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
3497 if (I.isSigned()) {
3498 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3499 Op0Min, Op0Max);
3500 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3501 Op1Min, Op1Max);
3502 } else {
3503 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3504 Op0Min, Op0Max);
3505 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3506 Op1Min, Op1Max);
3507 }
3508
3509 // If Min and Max are known to be the same, then SimplifyDemandedBits
3510 // figured out that the LHS is a constant. Just constant fold this now so
3511 // that code below can assume that Min != Max.
3512 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
3513 return new ICmpInst(I.getPredicate(),
Nick Lewycky92db8e82011-03-06 03:36:19 +00003514 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003515 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
3516 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewycky92db8e82011-03-06 03:36:19 +00003517 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner2188e402010-01-04 07:37:31 +00003518
3519 // Based on the range information we know about the LHS, see if we can
Nick Lewycky6b4454192011-02-28 06:20:05 +00003520 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner2188e402010-01-04 07:37:31 +00003521 switch (I.getPredicate()) {
3522 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattnerf7e89612010-11-21 06:44:42 +00003523 case ICmpInst::ICMP_EQ: {
Chris Lattner2188e402010-01-04 07:37:31 +00003524 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003525 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003526
Chris Lattnerf7e89612010-11-21 06:44:42 +00003527 // If all bits are known zero except for one, then we know at most one
3528 // bit is set. If the comparison is against zero, then this is a check
3529 // to see if *that* bit is set.
3530 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003531 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003532 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003533 Value *LHS = nullptr;
3534 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003535 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3536 LHSC->getValue() != Op0KnownZeroInverted)
3537 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003538
Chris Lattnerf7e89612010-11-21 06:44:42 +00003539 // 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 +00003540 // then turn "((1 << x)&8) == 0" into "x != 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003541 // or turn "((1 << x)&7) == 0" into "x > 2".
Craig Topperf40110f2014-04-25 05:29:35 +00003542 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003543 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003544 APInt ValToCheck = Op0KnownZeroInverted;
3545 if (ValToCheck.isPowerOf2()) {
3546 unsigned CmpVal = ValToCheck.countTrailingZeros();
3547 return new ICmpInst(ICmpInst::ICMP_NE, X,
3548 ConstantInt::get(X->getType(), CmpVal));
3549 } else if ((++ValToCheck).isPowerOf2()) {
3550 unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
3551 return new ICmpInst(ICmpInst::ICMP_UGT, X,
3552 ConstantInt::get(X->getType(), CmpVal));
3553 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003554 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003555
Chris Lattnerf7e89612010-11-21 06:44:42 +00003556 // 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 +00003557 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattner98457102011-02-10 05:23:05 +00003558 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003559 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003560 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003561 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner98457102011-02-10 05:23:05 +00003562 ConstantInt::get(X->getType(),
3563 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003564 }
Chris Lattner2188e402010-01-04 07:37:31 +00003565 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003566 }
3567 case ICmpInst::ICMP_NE: {
Chris Lattner2188e402010-01-04 07:37:31 +00003568 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003569 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003570
Chris Lattnerf7e89612010-11-21 06:44:42 +00003571 // If all bits are known zero except for one, then we know at most one
3572 // bit is set. If the comparison is against zero, then this is a check
3573 // to see if *that* bit is set.
3574 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003575 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003576 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003577 Value *LHS = nullptr;
3578 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003579 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3580 LHSC->getValue() != Op0KnownZeroInverted)
3581 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003582
Chris Lattnerf7e89612010-11-21 06:44:42 +00003583 // 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 +00003584 // then turn "((1 << x)&8) != 0" into "x == 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003585 // or turn "((1 << x)&7) != 0" into "x < 3".
Craig Topperf40110f2014-04-25 05:29:35 +00003586 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003587 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003588 APInt ValToCheck = Op0KnownZeroInverted;
3589 if (ValToCheck.isPowerOf2()) {
3590 unsigned CmpVal = ValToCheck.countTrailingZeros();
3591 return new ICmpInst(ICmpInst::ICMP_EQ, X,
3592 ConstantInt::get(X->getType(), CmpVal));
3593 } else if ((++ValToCheck).isPowerOf2()) {
3594 unsigned CmpVal = ValToCheck.countTrailingZeros();
3595 return new ICmpInst(ICmpInst::ICMP_ULT, X,
3596 ConstantInt::get(X->getType(), CmpVal));
3597 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003598 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003599
Chris Lattnerf7e89612010-11-21 06:44:42 +00003600 // 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 +00003601 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattner98457102011-02-10 05:23:05 +00003602 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003603 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003604 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003605 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner98457102011-02-10 05:23:05 +00003606 ConstantInt::get(X->getType(),
3607 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003608 }
Chris Lattner2188e402010-01-04 07:37:31 +00003609 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003610 }
Chris Lattner2188e402010-01-04 07:37:31 +00003611 case ICmpInst::ICMP_ULT:
3612 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003613 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003614 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003615 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003616 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
3617 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3618 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3619 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
3620 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003621 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003622
3623 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
3624 if (CI->isMinValue(true))
3625 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
3626 Constant::getAllOnesValue(Op0->getType()));
3627 }
3628 break;
3629 case ICmpInst::ICMP_UGT:
3630 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003631 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003632 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003633 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003634
3635 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
3636 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3637 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3638 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
3639 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003640 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003641
3642 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
3643 if (CI->isMaxValue(true))
3644 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
3645 Constant::getNullValue(Op0->getType()));
3646 }
3647 break;
3648 case ICmpInst::ICMP_SLT:
3649 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003650 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003651 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003652 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003653 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
3654 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3655 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3656 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
3657 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003658 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003659 }
3660 break;
3661 case ICmpInst::ICMP_SGT:
3662 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003663 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003664 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003665 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003666
3667 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
3668 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3669 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3670 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
3671 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003672 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003673 }
3674 break;
3675 case ICmpInst::ICMP_SGE:
3676 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
3677 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003678 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003679 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003680 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003681 break;
3682 case ICmpInst::ICMP_SLE:
3683 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
3684 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003685 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003686 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003687 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003688 break;
3689 case ICmpInst::ICMP_UGE:
3690 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
3691 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003692 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003693 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003694 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003695 break;
3696 case ICmpInst::ICMP_ULE:
3697 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
3698 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003699 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003700 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003701 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003702 break;
3703 }
3704
3705 // Turn a signed comparison into an unsigned one if both operands
3706 // are known to have the same sign.
3707 if (I.isSigned() &&
3708 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
3709 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
3710 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
3711 }
3712
3713 // Test if the ICmpInst instruction is used exclusively by a select as
3714 // part of a minimum or maximum operation. If so, refrain from doing
3715 // any other folding. This helps out other analyses which understand
3716 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
3717 // and CodeGen. And in this case, at least one of the comparison
3718 // operands has at least one user besides the compare (the select),
3719 // which would often largely negate the benefit of folding anyway.
3720 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00003721 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00003722 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
3723 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00003724 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003725
3726 // See if we are doing a comparison between a constant and an instruction that
3727 // can be folded into the comparison.
Sanjay Patel1271bf92016-07-23 13:06:49 +00003728
Sanjay Patel1e5b2d12016-08-16 16:08:11 +00003729 if (Instruction *Res = foldICmpWithConstant(I))
3730 return Res;
Chris Lattner2188e402010-01-04 07:37:31 +00003731
Sanjay Patelab50a932016-08-02 22:38:33 +00003732 if (Instruction *Res = foldICmpEqualityWithConstant(I))
3733 return Res;
3734
Sanjay Patel1271bf92016-07-23 13:06:49 +00003735 if (Instruction *Res = foldICmpIntrinsicWithConstant(I))
3736 return Res;
3737
Chris Lattner2188e402010-01-04 07:37:31 +00003738 // Handle icmp with constant (but not simple integer constant) RHS
3739 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3740 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3741 switch (LHSI->getOpcode()) {
3742 case Instruction::GetElementPtr:
3743 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3744 if (RHSC->isNullValue() &&
3745 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3746 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3747 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3748 break;
3749 case Instruction::PHI:
3750 // Only fold icmp into the PHI if the phi and icmp are in the same
3751 // block. If in the same block, we're encouraging jump threading. If
3752 // not, we are just pessimizing the code by making an i1 phi.
3753 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003754 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003755 return NV;
3756 break;
3757 case Instruction::Select: {
3758 // If either operand of the select is a constant, we can fold the
3759 // comparison into the select arms, which will cause one to be
3760 // constant folded and the select turned into a bitwise or.
Craig Topperf40110f2014-04-25 05:29:35 +00003761 Value *Op1 = nullptr, *Op2 = nullptr;
Hans Wennborg083ca9b2015-10-06 23:24:35 +00003762 ConstantInt *CI = nullptr;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003763 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003764 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003765 CI = dyn_cast<ConstantInt>(Op1);
3766 }
3767 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003768 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003769 CI = dyn_cast<ConstantInt>(Op2);
3770 }
Chris Lattner2188e402010-01-04 07:37:31 +00003771
3772 // We only want to perform this transformation if it will not lead to
3773 // additional code. This is true if either both sides of the select
3774 // fold to a constant (in which case the icmp is replaced with a select
3775 // which will usually simplify) or this is the only user of the
3776 // select (in which case we are trading a select+icmp for a simpler
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003777 // select+icmp) or all uses of the select can be replaced based on
3778 // dominance information ("Global cases").
3779 bool Transform = false;
3780 if (Op1 && Op2)
3781 Transform = true;
3782 else if (Op1 || Op2) {
3783 // Local case
3784 if (LHSI->hasOneUse())
3785 Transform = true;
3786 // Global cases
3787 else if (CI && !CI->isZero())
3788 // When Op1 is constant try replacing select with second operand.
3789 // Otherwise Op2 is constant and try replacing select with first
3790 // operand.
3791 Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
3792 Op1 ? 2 : 1);
3793 }
3794 if (Transform) {
Chris Lattner2188e402010-01-04 07:37:31 +00003795 if (!Op1)
3796 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3797 RHSC, I.getName());
3798 if (!Op2)
3799 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3800 RHSC, I.getName());
3801 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3802 }
3803 break;
3804 }
Chris Lattner2188e402010-01-04 07:37:31 +00003805 case Instruction::IntToPtr:
3806 // icmp pred inttoptr(X), null -> icmp pred X, 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003807 if (RHSC->isNullValue() &&
3808 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
Chris Lattner2188e402010-01-04 07:37:31 +00003809 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3810 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3811 break;
3812
3813 case Instruction::Load:
3814 // Try to optimize things like "A[i] > 4" to index computations.
3815 if (GetElementPtrInst *GEP =
3816 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3817 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3818 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3819 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00003820 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Chris Lattner2188e402010-01-04 07:37:31 +00003821 return Res;
3822 }
3823 break;
3824 }
3825 }
3826
3827 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3828 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Sanjay Patel43395062016-07-21 18:07:40 +00003829 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner2188e402010-01-04 07:37:31 +00003830 return NI;
3831 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00003832 if (Instruction *NI = foldGEPICmp(GEP, Op0,
Chris Lattner2188e402010-01-04 07:37:31 +00003833 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3834 return NI;
3835
Hans Wennborgf1f36512015-10-07 00:20:07 +00003836 // Try to optimize equality comparisons against alloca-based pointers.
3837 if (Op0->getType()->isPointerTy() && I.isEquality()) {
3838 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
3839 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00003840 if (Instruction *New = foldAllocaCmp(I, Alloca, Op1))
Hans Wennborgf1f36512015-10-07 00:20:07 +00003841 return New;
3842 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00003843 if (Instruction *New = foldAllocaCmp(I, Alloca, Op0))
Hans Wennborgf1f36512015-10-07 00:20:07 +00003844 return New;
3845 }
3846
Chris Lattner2188e402010-01-04 07:37:31 +00003847 // Test to see if the operands of the icmp are casted versions of other
3848 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3849 // now.
3850 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003851 if (Op0->getType()->isPointerTy() &&
3852 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003853 // We keep moving the cast from the left operand over to the right
3854 // operand, where it can often be eliminated completely.
3855 Op0 = CI->getOperand(0);
3856
3857 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3858 // so eliminate it as well.
3859 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3860 Op1 = CI2->getOperand(0);
3861
3862 // If Op1 is a constant, we can fold the cast into the constant.
3863 if (Op0->getType() != Op1->getType()) {
3864 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3865 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3866 } else {
3867 // Otherwise, cast the RHS right before the icmp
3868 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3869 }
3870 }
3871 return new ICmpInst(I.getPredicate(), Op0, Op1);
3872 }
3873 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003874
Chris Lattner2188e402010-01-04 07:37:31 +00003875 if (isa<CastInst>(Op0)) {
3876 // Handle the special case of: icmp (cast bool to X), <cst>
3877 // This comes up when you have code like
3878 // int X = A < B;
3879 // if (X) ...
3880 // For generality, we handle any zero-extension of any operand comparison
3881 // with a constant or another cast from the same type.
3882 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00003883 if (Instruction *R = foldICmpWithCastAndCast(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003884 return R;
3885 }
Chris Lattner2188e402010-01-04 07:37:31 +00003886
Duncan Sandse5220012011-02-17 07:46:37 +00003887 // Special logic for binary operators.
3888 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3889 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3890 if (BO0 || BO1) {
3891 CmpInst::Predicate Pred = I.getPredicate();
3892 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3893 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3894 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3895 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3896 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3897 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3898 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3899 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3900 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3901
3902 // Analyze the case when either Op0 or Op1 is an add instruction.
3903 // 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 +00003904 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +00003905 if (BO0 && BO0->getOpcode() == Instruction::Add) {
3906 A = BO0->getOperand(0);
3907 B = BO0->getOperand(1);
3908 }
3909 if (BO1 && BO1->getOpcode() == Instruction::Add) {
3910 C = BO1->getOperand(0);
3911 D = BO1->getOperand(1);
3912 }
Duncan Sandse5220012011-02-17 07:46:37 +00003913
David Majnemer549f4f22014-11-01 09:09:51 +00003914 // icmp (X+cst) < 0 --> X < -cst
3915 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
3916 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
3917 if (!RHSC->isMinValue(/*isSigned=*/true))
3918 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
3919
Duncan Sandse5220012011-02-17 07:46:37 +00003920 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3921 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3922 return new ICmpInst(Pred, A == Op1 ? B : A,
3923 Constant::getNullValue(Op1->getType()));
3924
3925 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3926 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3927 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3928 C == Op0 ? D : C);
3929
Duncan Sands84653b32011-02-18 16:25:37 +00003930 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003931 if (A && C && (A == C || A == D || B == C || B == D) &&
3932 NoOp0WrapProblem && NoOp1WrapProblem &&
3933 // Try not to increase register pressure.
3934 BO0->hasOneUse() && BO1->hasOneUse()) {
3935 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003936 Value *Y, *Z;
3937 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003938 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003939 Y = B;
3940 Z = D;
3941 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003942 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003943 Y = B;
3944 Z = C;
3945 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003946 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003947 Y = A;
3948 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003949 } else {
3950 assert(B == D);
3951 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003952 Y = A;
3953 Z = C;
3954 }
Duncan Sandse5220012011-02-17 07:46:37 +00003955 return new ICmpInst(Pred, Y, Z);
3956 }
3957
David Majnemerb81cd632013-04-11 20:05:46 +00003958 // icmp slt (X + -1), Y -> icmp sle X, Y
3959 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3960 match(B, m_AllOnes()))
3961 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3962
3963 // icmp sge (X + -1), Y -> icmp sgt X, Y
3964 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3965 match(B, m_AllOnes()))
3966 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3967
3968 // icmp sle (X + 1), Y -> icmp slt X, Y
3969 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3970 match(B, m_One()))
3971 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3972
3973 // icmp sgt (X + 1), Y -> icmp sge X, Y
3974 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3975 match(B, m_One()))
3976 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3977
Michael Liaoc65d3862015-10-19 22:08:14 +00003978 // icmp sgt X, (Y + -1) -> icmp sge X, Y
3979 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3980 match(D, m_AllOnes()))
3981 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3982
3983 // icmp sle X, (Y + -1) -> icmp slt X, Y
3984 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3985 match(D, m_AllOnes()))
3986 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3987
3988 // icmp sge X, (Y + 1) -> icmp sgt X, Y
3989 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE &&
3990 match(D, m_One()))
3991 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3992
3993 // icmp slt X, (Y + 1) -> icmp sle X, Y
3994 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT &&
3995 match(D, m_One()))
3996 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3997
David Majnemerb81cd632013-04-11 20:05:46 +00003998 // if C1 has greater magnitude than C2:
3999 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
4000 // s.t. C3 = C1 - C2
4001 //
4002 // if C2 has greater magnitude than C1:
4003 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
4004 // s.t. C3 = C2 - C1
4005 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
4006 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
4007 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
4008 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
4009 const APInt &AP1 = C1->getValue();
4010 const APInt &AP2 = C2->getValue();
4011 if (AP1.isNegative() == AP2.isNegative()) {
4012 APInt AP1Abs = C1->getValue().abs();
4013 APInt AP2Abs = C2->getValue().abs();
4014 if (AP1Abs.uge(AP2Abs)) {
4015 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
4016 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
4017 return new ICmpInst(Pred, NewAdd, C);
4018 } else {
4019 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
4020 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
4021 return new ICmpInst(Pred, A, NewAdd);
4022 }
4023 }
4024 }
4025
4026
Duncan Sandse5220012011-02-17 07:46:37 +00004027 // Analyze the case when either Op0 or Op1 is a sub instruction.
4028 // 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 +00004029 A = nullptr;
4030 B = nullptr;
4031 C = nullptr;
4032 D = nullptr;
4033 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
4034 A = BO0->getOperand(0);
4035 B = BO0->getOperand(1);
4036 }
4037 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
4038 C = BO1->getOperand(0);
4039 D = BO1->getOperand(1);
4040 }
Duncan Sandse5220012011-02-17 07:46:37 +00004041
Duncan Sands84653b32011-02-18 16:25:37 +00004042 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
4043 if (A == Op1 && NoOp0WrapProblem)
4044 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
4045
4046 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
4047 if (C == Op0 && NoOp1WrapProblem)
4048 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
4049
4050 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00004051 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
4052 // Try not to increase register pressure.
4053 BO0->hasOneUse() && BO1->hasOneUse())
4054 return new ICmpInst(Pred, A, C);
4055
Duncan Sands84653b32011-02-18 16:25:37 +00004056 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
4057 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
4058 // Try not to increase register pressure.
4059 BO0->hasOneUse() && BO1->hasOneUse())
4060 return new ICmpInst(Pred, D, B);
4061
David Majnemer186c9422014-05-15 00:02:20 +00004062 // icmp (0-X) < cst --> x > -cst
4063 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
4064 Value *X;
4065 if (match(BO0, m_Neg(m_Value(X))))
4066 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
4067 if (!RHSC->isMinValue(/*isSigned=*/true))
4068 return new ICmpInst(I.getSwappedPredicate(), X,
4069 ConstantExpr::getNeg(RHSC));
4070 }
4071
Craig Topperf40110f2014-04-25 05:29:35 +00004072 BinaryOperator *SRem = nullptr;
Nick Lewyckyafc80982011-03-08 06:29:47 +00004073 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00004074 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
4075 Op1 == BO0->getOperand(1))
4076 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00004077 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00004078 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
4079 Op0 == BO1->getOperand(1))
4080 SRem = BO1;
4081 if (SRem) {
4082 // We don't check hasOneUse to avoid increasing register pressure because
4083 // the value we use is the same value this instruction was already using.
4084 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
4085 default: break;
4086 case ICmpInst::ICMP_EQ:
Sanjay Patel4b198802016-02-01 22:23:39 +00004087 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00004088 case ICmpInst::ICMP_NE:
Sanjay Patel4b198802016-02-01 22:23:39 +00004089 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00004090 case ICmpInst::ICMP_SGT:
4091 case ICmpInst::ICMP_SGE:
4092 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
4093 Constant::getAllOnesValue(SRem->getType()));
4094 case ICmpInst::ICMP_SLT:
4095 case ICmpInst::ICMP_SLE:
4096 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
4097 Constant::getNullValue(SRem->getType()));
4098 }
4099 }
4100
Duncan Sandse5220012011-02-17 07:46:37 +00004101 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
4102 BO0->hasOneUse() && BO1->hasOneUse() &&
4103 BO0->getOperand(1) == BO1->getOperand(1)) {
4104 switch (BO0->getOpcode()) {
4105 default: break;
4106 case Instruction::Add:
4107 case Instruction::Sub:
4108 case Instruction::Xor:
4109 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
4110 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4111 BO1->getOperand(0));
4112 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
4113 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4114 if (CI->getValue().isSignBit()) {
4115 ICmpInst::Predicate Pred = I.isSigned()
4116 ? I.getUnsignedPredicate()
4117 : I.getSignedPredicate();
4118 return new ICmpInst(Pred, BO0->getOperand(0),
4119 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00004120 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004121
David Majnemerf8853ae2016-02-01 17:37:56 +00004122 if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00004123 ICmpInst::Predicate Pred = I.isSigned()
4124 ? I.getUnsignedPredicate()
4125 : I.getSignedPredicate();
4126 Pred = I.getSwappedPredicate(Pred);
4127 return new ICmpInst(Pred, BO0->getOperand(0),
4128 BO1->getOperand(0));
4129 }
Chris Lattner2188e402010-01-04 07:37:31 +00004130 }
Duncan Sandse5220012011-02-17 07:46:37 +00004131 break;
4132 case Instruction::Mul:
4133 if (!I.isEquality())
4134 break;
4135
4136 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4137 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
4138 // Mask = -1 >> count-trailing-zeros(Cst).
4139 if (!CI->isZero() && !CI->isOne()) {
4140 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004141 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00004142 APInt::getLowBitsSet(AP.getBitWidth(),
4143 AP.getBitWidth() -
4144 AP.countTrailingZeros()));
4145 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
4146 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
4147 return new ICmpInst(I.getPredicate(), And1, And2);
4148 }
4149 }
4150 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00004151 case Instruction::UDiv:
4152 case Instruction::LShr:
4153 if (I.isSigned())
4154 break;
Justin Bognerb03fd122016-08-17 05:10:15 +00004155 LLVM_FALLTHROUGH;
Nick Lewycky9719a712011-03-05 05:19:11 +00004156 case Instruction::SDiv:
4157 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00004158 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00004159 break;
4160 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4161 BO1->getOperand(0));
4162 case Instruction::Shl: {
4163 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
4164 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
4165 if (!NUW && !NSW)
4166 break;
4167 if (!NSW && I.isSigned())
4168 break;
4169 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4170 BO1->getOperand(0));
4171 }
Chris Lattner2188e402010-01-04 07:37:31 +00004172 }
4173 }
Sanjoy Dasc86c1622015-08-21 22:22:37 +00004174
4175 if (BO0) {
4176 // Transform A & (L - 1) `ult` L --> L != 0
4177 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
4178 auto BitwiseAnd =
4179 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
4180
4181 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
4182 auto *Zero = Constant::getNullValue(BO0->getType());
4183 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
4184 }
4185 }
Chris Lattner2188e402010-01-04 07:37:31 +00004186 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004187
Chris Lattner2188e402010-01-04 07:37:31 +00004188 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00004189 // Transform (A & ~B) == 0 --> (A & B) != 0
4190 // and (A & ~B) != 0 --> (A & B) == 0
4191 // if A is a power of 2.
4192 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00004193 match(Op1, m_Zero()) &&
Justin Bogner99798402016-08-05 01:06:44 +00004194 isKnownToBeAPowerOfTwo(A, DL, false, 0, &AC, &I, &DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00004195 return new ICmpInst(I.getInversePredicate(),
4196 Builder->CreateAnd(A, B),
4197 Op1);
4198
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004199 // ~x < ~y --> y < x
4200 // ~x < cst --> ~cst < x
4201 if (match(Op0, m_Not(m_Value(A)))) {
4202 if (match(Op1, m_Not(m_Value(B))))
4203 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00004204 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004205 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
4206 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00004207
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004208 Instruction *AddI = nullptr;
4209 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
4210 m_Instruction(AddI))) &&
4211 isa<IntegerType>(A->getType())) {
4212 Value *Result;
4213 Constant *Overflow;
4214 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
4215 Overflow)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004216 replaceInstUsesWith(*AddI, Result);
4217 return replaceInstUsesWith(I, Overflow);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004218 }
4219 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004220
4221 // (zext a) * (zext b) --> llvm.umul.with.overflow.
4222 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4223 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
4224 return R;
4225 }
4226 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4227 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
4228 return R;
4229 }
Chris Lattner2188e402010-01-04 07:37:31 +00004230 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004231
Chris Lattner2188e402010-01-04 07:37:31 +00004232 if (I.isEquality()) {
4233 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00004234
Chris Lattner2188e402010-01-04 07:37:31 +00004235 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4236 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4237 Value *OtherVal = A == Op1 ? B : A;
4238 return new ICmpInst(I.getPredicate(), OtherVal,
4239 Constant::getNullValue(A->getType()));
4240 }
4241
4242 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4243 // A^c1 == C^c2 --> A == C^(c1^c2)
4244 ConstantInt *C1, *C2;
4245 if (match(B, m_ConstantInt(C1)) &&
4246 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00004247 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004248 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00004249 return new ICmpInst(I.getPredicate(), A, Xor);
4250 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004251
Chris Lattner2188e402010-01-04 07:37:31 +00004252 // A^B == A^D -> B == D
4253 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4254 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4255 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4256 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4257 }
4258 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004259
Chris Lattner2188e402010-01-04 07:37:31 +00004260 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4261 (A == Op0 || B == Op0)) {
4262 // A == (A^B) -> B == 0
4263 Value *OtherVal = A == Op0 ? B : A;
4264 return new ICmpInst(I.getPredicate(), OtherVal,
4265 Constant::getNullValue(A->getType()));
4266 }
4267
Chris Lattner2188e402010-01-04 07:37:31 +00004268 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00004269 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00004270 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Craig Topperf40110f2014-04-25 05:29:35 +00004271 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004272
Chris Lattner2188e402010-01-04 07:37:31 +00004273 if (A == C) {
4274 X = B; Y = D; Z = A;
4275 } else if (A == D) {
4276 X = B; Y = C; Z = A;
4277 } else if (B == C) {
4278 X = A; Y = D; Z = B;
4279 } else if (B == D) {
4280 X = A; Y = C; Z = B;
4281 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004282
Chris Lattner2188e402010-01-04 07:37:31 +00004283 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004284 Op1 = Builder->CreateXor(X, Y);
4285 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00004286 I.setOperand(0, Op1);
4287 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4288 return &I;
4289 }
4290 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004291
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004292 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00004293 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004294 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00004295 if ((Op0->hasOneUse() &&
4296 match(Op0, m_ZExt(m_Value(A))) &&
4297 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
4298 (Op1->hasOneUse() &&
4299 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
4300 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004301 APInt Pow2 = Cst1->getValue() + 1;
4302 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
4303 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
4304 return new ICmpInst(I.getPredicate(), A,
4305 Builder->CreateTrunc(B, A->getType()));
4306 }
4307
Benjamin Kramer03f3e242013-11-16 16:00:48 +00004308 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
4309 // For lshr and ashr pairs.
4310 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4311 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
4312 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4313 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
4314 unsigned TypeBits = Cst1->getBitWidth();
4315 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4316 if (ShAmt < TypeBits && ShAmt != 0) {
4317 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
4318 ? ICmpInst::ICMP_UGE
4319 : ICmpInst::ICMP_ULT;
4320 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4321 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
4322 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
4323 }
4324 }
4325
Benjamin Kramer7fa8c432015-03-26 17:12:06 +00004326 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
4327 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
4328 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
4329 unsigned TypeBits = Cst1->getBitWidth();
4330 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4331 if (ShAmt < TypeBits && ShAmt != 0) {
4332 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4333 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
4334 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
4335 I.getName() + ".mask");
4336 return new ICmpInst(I.getPredicate(), And,
4337 Constant::getNullValue(Cst1->getType()));
4338 }
4339 }
4340
Chris Lattner1b06c712011-04-26 20:18:20 +00004341 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
4342 // "icmp (and X, mask), cst"
4343 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00004344 if (Op0->hasOneUse() &&
4345 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
4346 m_ConstantInt(ShAmt))))) &&
4347 match(Op1, m_ConstantInt(Cst1)) &&
4348 // Only do this when A has multiple uses. This is most important to do
4349 // when it exposes other optimizations.
4350 !A->hasOneUse()) {
4351 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004352
Chris Lattner1b06c712011-04-26 20:18:20 +00004353 if (ShAmt < ASize) {
4354 APInt MaskV =
4355 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
4356 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004357
Chris Lattner1b06c712011-04-26 20:18:20 +00004358 APInt CmpV = Cst1->getValue().zext(ASize);
4359 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004360
Chris Lattner1b06c712011-04-26 20:18:20 +00004361 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
4362 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
4363 }
4364 }
Chris Lattner2188e402010-01-04 07:37:31 +00004365 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004366
David Majnemerc1eca5a2014-11-06 23:23:30 +00004367 // The 'cmpxchg' instruction returns an aggregate containing the old value and
4368 // an i1 which indicates whether or not we successfully did the swap.
4369 //
4370 // Replace comparisons between the old value and the expected value with the
4371 // indicator that 'cmpxchg' returns.
4372 //
4373 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
4374 // spuriously fail. In those cases, the old value may equal the expected
4375 // value but it is possible for the swap to not occur.
4376 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4377 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4378 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4379 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4380 !ACXI->isWeak())
4381 return ExtractValueInst::Create(ACXI, 1);
4382
Chris Lattner2188e402010-01-04 07:37:31 +00004383 {
4384 Value *X; ConstantInt *Cst;
4385 // icmp X+Cst, X
4386 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004387 return foldICmpAddOpConst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004388
4389 // icmp X, X+Cst
4390 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004391 return foldICmpAddOpConst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004392 }
Craig Topperf40110f2014-04-25 05:29:35 +00004393 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004394}
4395
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004396/// Fold fcmp ([us]itofp x, cst) if possible.
Sanjay Patel43395062016-07-21 18:07:40 +00004397Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
Chris Lattner2188e402010-01-04 07:37:31 +00004398 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00004399 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004400 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004401
Chris Lattner2188e402010-01-04 07:37:31 +00004402 // Get the width of the mantissa. We don't want to hack on conversions that
4403 // might lose information from the integer, e.g. "i64 -> float"
4404 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00004405 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004406
Matt Arsenault55e73122015-01-06 15:50:59 +00004407 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4408
Chris Lattner2188e402010-01-04 07:37:31 +00004409 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004410
Matt Arsenault55e73122015-01-06 15:50:59 +00004411 if (I.isEquality()) {
4412 FCmpInst::Predicate P = I.getPredicate();
4413 bool IsExact = false;
4414 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
4415 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
4416
4417 // If the floating point constant isn't an integer value, we know if we will
4418 // ever compare equal / not equal to it.
4419 if (!IsExact) {
4420 // TODO: Can never be -0.0 and other non-representable values
4421 APFloat RHSRoundInt(RHS);
4422 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
4423 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
4424 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00004425 return replaceInstUsesWith(I, Builder->getFalse());
Matt Arsenault55e73122015-01-06 15:50:59 +00004426
4427 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
Sanjay Patel4b198802016-02-01 22:23:39 +00004428 return replaceInstUsesWith(I, Builder->getTrue());
Matt Arsenault55e73122015-01-06 15:50:59 +00004429 }
4430 }
4431
4432 // TODO: If the constant is exactly representable, is it always OK to do
4433 // equality compares as integer?
4434 }
4435
Arch D. Robison8ed08542015-09-15 17:51:59 +00004436 // Check to see that the input is converted from an integer type that is small
4437 // enough that preserves all bits. TODO: check here for "known" sign bits.
4438 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4439 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00004440
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004441 // Following test does NOT adjust InputSize downwards for signed inputs,
4442 // because the most negative value still requires all the mantissa bits
Arch D. Robison8ed08542015-09-15 17:51:59 +00004443 // to distinguish it from one less than that value.
4444 if ((int)InputSize > MantissaWidth) {
4445 // Conversion would lose accuracy. Check if loss can impact comparison.
4446 int Exp = ilogb(RHS);
4447 if (Exp == APFloat::IEK_Inf) {
4448 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004449 if (MaxExponent < (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004450 // Conversion could create infinity.
4451 return nullptr;
4452 } else {
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004453 // Note that if RHS is zero or NaN, then Exp is negative
Arch D. Robison8ed08542015-09-15 17:51:59 +00004454 // and first condition is trivially false.
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004455 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004456 // Conversion could affect comparison.
4457 return nullptr;
4458 }
4459 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004460
Chris Lattner2188e402010-01-04 07:37:31 +00004461 // Otherwise, we can potentially simplify the comparison. We know that it
4462 // will always come through as an integer value and we know the constant is
4463 // not a NAN (it would have been previously simplified).
4464 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00004465
Chris Lattner2188e402010-01-04 07:37:31 +00004466 ICmpInst::Predicate Pred;
4467 switch (I.getPredicate()) {
4468 default: llvm_unreachable("Unexpected predicate!");
4469 case FCmpInst::FCMP_UEQ:
4470 case FCmpInst::FCMP_OEQ:
4471 Pred = ICmpInst::ICMP_EQ;
4472 break;
4473 case FCmpInst::FCMP_UGT:
4474 case FCmpInst::FCMP_OGT:
4475 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4476 break;
4477 case FCmpInst::FCMP_UGE:
4478 case FCmpInst::FCMP_OGE:
4479 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4480 break;
4481 case FCmpInst::FCMP_ULT:
4482 case FCmpInst::FCMP_OLT:
4483 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4484 break;
4485 case FCmpInst::FCMP_ULE:
4486 case FCmpInst::FCMP_OLE:
4487 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4488 break;
4489 case FCmpInst::FCMP_UNE:
4490 case FCmpInst::FCMP_ONE:
4491 Pred = ICmpInst::ICMP_NE;
4492 break;
4493 case FCmpInst::FCMP_ORD:
Sanjay Patel4b198802016-02-01 22:23:39 +00004494 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004495 case FCmpInst::FCMP_UNO:
Sanjay Patel4b198802016-02-01 22:23:39 +00004496 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004497 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004498
Chris Lattner2188e402010-01-04 07:37:31 +00004499 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004500
Chris Lattner2188e402010-01-04 07:37:31 +00004501 // See if the FP constant is too large for the integer. For example,
4502 // comparing an i8 to 300.0.
4503 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004504
Chris Lattner2188e402010-01-04 07:37:31 +00004505 if (!LHSUnsigned) {
4506 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4507 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004508 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004509 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4510 APFloat::rmNearestTiesToEven);
4511 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4512 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4513 Pred == ICmpInst::ICMP_SLE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004514 return replaceInstUsesWith(I, Builder->getTrue());
4515 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004516 }
4517 } else {
4518 // If the RHS value is > UnsignedMax, fold the comparison. This handles
4519 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004520 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004521 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4522 APFloat::rmNearestTiesToEven);
4523 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
4524 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
4525 Pred == ICmpInst::ICMP_ULE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004526 return replaceInstUsesWith(I, Builder->getTrue());
4527 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004528 }
4529 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004530
Chris Lattner2188e402010-01-04 07:37:31 +00004531 if (!LHSUnsigned) {
4532 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004533 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004534 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4535 APFloat::rmNearestTiesToEven);
4536 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4537 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4538 Pred == ICmpInst::ICMP_SGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004539 return replaceInstUsesWith(I, Builder->getTrue());
4540 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004541 }
Devang Patel698452b2012-02-13 23:05:18 +00004542 } else {
4543 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004544 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00004545 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
4546 APFloat::rmNearestTiesToEven);
4547 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
4548 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
4549 Pred == ICmpInst::ICMP_UGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004550 return replaceInstUsesWith(I, Builder->getTrue());
4551 return replaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00004552 }
Chris Lattner2188e402010-01-04 07:37:31 +00004553 }
4554
4555 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4556 // [0, UMAX], but it may still be fractional. See if it is fractional by
4557 // casting the FP value to the integer value and back, checking for equality.
4558 // Don't do this for zero, because -0.0 is not fractional.
4559 Constant *RHSInt = LHSUnsigned
4560 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4561 : ConstantExpr::getFPToSI(RHSC, IntTy);
4562 if (!RHS.isZero()) {
4563 bool Equal = LHSUnsigned
4564 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4565 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4566 if (!Equal) {
4567 // If we had a comparison against a fractional value, we have to adjust
4568 // the compare predicate and sometimes the value. RHSC is rounded towards
4569 // zero at this point.
4570 switch (Pred) {
4571 default: llvm_unreachable("Unexpected integer comparison!");
4572 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Sanjay Patel4b198802016-02-01 22:23:39 +00004573 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004574 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Sanjay Patel4b198802016-02-01 22:23:39 +00004575 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004576 case ICmpInst::ICMP_ULE:
4577 // (float)int <= 4.4 --> int <= 4
4578 // (float)int <= -4.4 --> false
4579 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004580 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004581 break;
4582 case ICmpInst::ICMP_SLE:
4583 // (float)int <= 4.4 --> int <= 4
4584 // (float)int <= -4.4 --> int < -4
4585 if (RHS.isNegative())
4586 Pred = ICmpInst::ICMP_SLT;
4587 break;
4588 case ICmpInst::ICMP_ULT:
4589 // (float)int < -4.4 --> false
4590 // (float)int < 4.4 --> int <= 4
4591 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004592 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004593 Pred = ICmpInst::ICMP_ULE;
4594 break;
4595 case ICmpInst::ICMP_SLT:
4596 // (float)int < -4.4 --> int < -4
4597 // (float)int < 4.4 --> int <= 4
4598 if (!RHS.isNegative())
4599 Pred = ICmpInst::ICMP_SLE;
4600 break;
4601 case ICmpInst::ICMP_UGT:
4602 // (float)int > 4.4 --> int > 4
4603 // (float)int > -4.4 --> true
4604 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004605 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004606 break;
4607 case ICmpInst::ICMP_SGT:
4608 // (float)int > 4.4 --> int > 4
4609 // (float)int > -4.4 --> int >= -4
4610 if (RHS.isNegative())
4611 Pred = ICmpInst::ICMP_SGE;
4612 break;
4613 case ICmpInst::ICMP_UGE:
4614 // (float)int >= -4.4 --> true
4615 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00004616 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004617 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004618 Pred = ICmpInst::ICMP_UGT;
4619 break;
4620 case ICmpInst::ICMP_SGE:
4621 // (float)int >= -4.4 --> int >= -4
4622 // (float)int >= 4.4 --> int > 4
4623 if (!RHS.isNegative())
4624 Pred = ICmpInst::ICMP_SGT;
4625 break;
4626 }
4627 }
4628 }
4629
4630 // Lower this FP comparison into an appropriate integer version of the
4631 // comparison.
4632 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4633}
4634
4635Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4636 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004637
Chris Lattner2188e402010-01-04 07:37:31 +00004638 /// Orders the operands of the compare so that they are listed from most
4639 /// complex to least complex. This puts constants before unary operators,
4640 /// before binary operators.
4641 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4642 I.swapOperands();
4643 Changed = true;
4644 }
4645
4646 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004647
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004648 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
Justin Bogner99798402016-08-05 01:06:44 +00004649 I.getFastMathFlags(), DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004650 return replaceInstUsesWith(I, V);
Chris Lattner2188e402010-01-04 07:37:31 +00004651
4652 // Simplify 'fcmp pred X, X'
4653 if (Op0 == Op1) {
4654 switch (I.getPredicate()) {
4655 default: llvm_unreachable("Unknown predicate!");
4656 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4657 case FCmpInst::FCMP_ULT: // True if unordered or less than
4658 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4659 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4660 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4661 I.setPredicate(FCmpInst::FCMP_UNO);
4662 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4663 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004664
Chris Lattner2188e402010-01-04 07:37:31 +00004665 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4666 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4667 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4668 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4669 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4670 I.setPredicate(FCmpInst::FCMP_ORD);
4671 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4672 return &I;
4673 }
4674 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004675
James Molloy2b21a7c2015-05-20 18:41:25 +00004676 // Test if the FCmpInst instruction is used exclusively by a select as
4677 // part of a minimum or maximum operation. If so, refrain from doing
4678 // any other folding. This helps out other analyses which understand
4679 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4680 // and CodeGen. And in this case, at least one of the comparison
4681 // operands has at least one user besides the compare (the select),
4682 // which would often largely negate the benefit of folding anyway.
4683 if (I.hasOneUse())
4684 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4685 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4686 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4687 return nullptr;
4688
Chris Lattner2188e402010-01-04 07:37:31 +00004689 // Handle fcmp with constant RHS
4690 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4691 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4692 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004693 case Instruction::FPExt: {
4694 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4695 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4696 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4697 if (!RHSF)
4698 break;
4699
4700 const fltSemantics *Sem;
4701 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004702 if (LHSExt->getSrcTy()->isHalfTy())
4703 Sem = &APFloat::IEEEhalf;
4704 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004705 Sem = &APFloat::IEEEsingle;
4706 else if (LHSExt->getSrcTy()->isDoubleTy())
4707 Sem = &APFloat::IEEEdouble;
4708 else if (LHSExt->getSrcTy()->isFP128Ty())
4709 Sem = &APFloat::IEEEquad;
4710 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
4711 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004712 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
4713 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004714 else
4715 break;
4716
4717 bool Lossy;
4718 APFloat F = RHSF->getValueAPF();
4719 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4720
Jim Grosbach24ff8342011-09-30 18:45:50 +00004721 // Avoid lossy conversions and denormals. Zero is a special case
4722 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004723 APFloat Fabs = F;
4724 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004725 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004726 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4727 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004728
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004729 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4730 ConstantFP::get(RHSC->getContext(), F));
4731 break;
4732 }
Chris Lattner2188e402010-01-04 07:37:31 +00004733 case Instruction::PHI:
4734 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4735 // block. If in the same block, we're encouraging jump threading. If
4736 // not, we are just pessimizing the code by making an i1 phi.
4737 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004738 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004739 return NV;
4740 break;
4741 case Instruction::SIToFP:
4742 case Instruction::UIToFP:
Sanjay Patel43395062016-07-21 18:07:40 +00004743 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
Chris Lattner2188e402010-01-04 07:37:31 +00004744 return NV;
4745 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004746 case Instruction::FSub: {
4747 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4748 Value *Op;
4749 if (match(LHSI, m_FNeg(m_Value(Op))))
4750 return new FCmpInst(I.getSwappedPredicate(), Op,
4751 ConstantExpr::getFNeg(RHSC));
4752 break;
4753 }
Dan Gohman94732022010-02-24 06:46:09 +00004754 case Instruction::Load:
4755 if (GetElementPtrInst *GEP =
4756 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4757 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4758 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4759 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00004760 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Dan Gohman94732022010-02-24 06:46:09 +00004761 return Res;
4762 }
4763 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004764 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004765 if (!RHSC->isNullValue())
4766 break;
4767
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004768 CallInst *CI = cast<CallInst>(LHSI);
Justin Bogner99798402016-08-05 01:06:44 +00004769 Intrinsic::ID IID = getIntrinsicForCallSite(CI, &TLI);
David Majnemer2e02ba72016-04-15 17:21:03 +00004770 if (IID != Intrinsic::fabs)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004771 break;
4772
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004773 // Various optimization for fabs compared with zero.
David Majnemer2e02ba72016-04-15 17:21:03 +00004774 switch (I.getPredicate()) {
4775 default:
4776 break;
4777 // fabs(x) < 0 --> false
4778 case FCmpInst::FCMP_OLT:
4779 llvm_unreachable("handled by SimplifyFCmpInst");
4780 // fabs(x) > 0 --> x != 0
4781 case FCmpInst::FCMP_OGT:
4782 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
4783 // fabs(x) <= 0 --> x == 0
4784 case FCmpInst::FCMP_OLE:
4785 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
4786 // fabs(x) >= 0 --> !isnan(x)
4787 case FCmpInst::FCMP_OGE:
4788 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
4789 // fabs(x) == 0 --> x == 0
4790 // fabs(x) != 0 --> x != 0
4791 case FCmpInst::FCMP_OEQ:
4792 case FCmpInst::FCMP_UEQ:
4793 case FCmpInst::FCMP_ONE:
4794 case FCmpInst::FCMP_UNE:
4795 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004796 }
4797 }
Chris Lattner2188e402010-01-04 07:37:31 +00004798 }
Chris Lattner2188e402010-01-04 07:37:31 +00004799 }
4800
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004801 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004802 Value *X, *Y;
4803 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004804 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004805
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004806 // fcmp (fpext x), (fpext y) -> fcmp x, y
4807 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4808 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4809 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4810 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4811 RHSExt->getOperand(0));
4812
Craig Topperf40110f2014-04-25 05:29:35 +00004813 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004814}