blob: 6a798f91759a1dd6f687203303a8ef2fb8f9ab8b [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/// Return true if the constant is of the form 1+0+. This is the same as
180/// lowones(~X).
Chris Lattner2188e402010-01-04 07:37:31 +0000181static bool isHighOnes(const ConstantInt *CI) {
182 return (~CI->getValue() + 1).isPowerOf2();
183}
184
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000185/// Given a signed integer type and a set of known zero and one bits, compute
186/// the maximum and minimum values that could have the specified known zero and
187/// known one bits, returning them in Min/Max.
188static void ComputeSignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
189 const APInt &KnownOne,
190 APInt &Min, APInt &Max) {
Chris Lattner2188e402010-01-04 07:37:31 +0000191 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
192 KnownZero.getBitWidth() == Min.getBitWidth() &&
193 KnownZero.getBitWidth() == Max.getBitWidth() &&
194 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
195 APInt UnknownBits = ~(KnownZero|KnownOne);
196
197 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
198 // bit if it is unknown.
199 Min = KnownOne;
200 Max = KnownOne|UnknownBits;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000201
Chris Lattner2188e402010-01-04 07:37:31 +0000202 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000203 Min.setBit(Min.getBitWidth()-1);
204 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000205 }
206}
207
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000208/// Given an unsigned integer type and a set of known zero and one bits, compute
209/// the maximum and minimum values that could have the specified known zero and
210/// known one bits, returning them in Min/Max.
Chris Lattner2188e402010-01-04 07:37:31 +0000211static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
212 const APInt &KnownOne,
213 APInt &Min, APInt &Max) {
214 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
215 KnownZero.getBitWidth() == Min.getBitWidth() &&
216 KnownZero.getBitWidth() == Max.getBitWidth() &&
217 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
218 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000219
Chris Lattner2188e402010-01-04 07:37:31 +0000220 // The minimum value is when the unknown bits are all zeros.
221 Min = KnownOne;
222 // The maximum value is when the unknown bits are all ones.
223 Max = KnownOne|UnknownBits;
224}
225
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000226/// This is called when we see this pattern:
Chris Lattner2188e402010-01-04 07:37:31 +0000227/// cmp pred (load (gep GV, ...)), cmpcst
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000228/// where GV is a global variable with a constant initializer. Try to simplify
229/// this into some simple computation that does not need the load. For example
Chris Lattner2188e402010-01-04 07:37:31 +0000230/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
231///
232/// If AndCst is non-null, then the loaded value is masked with that constant
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000233/// before doing the comparison. This handles cases like "A[i]&4 == 0".
Sanjay Patel43395062016-07-21 18:07:40 +0000234Instruction *InstCombiner::foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
235 GlobalVariable *GV,
236 CmpInst &ICI,
237 ConstantInt *AndCst) {
Chris Lattnerfe741762012-01-31 02:55:06 +0000238 Constant *Init = GV->getInitializer();
239 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
Craig Topperf40110f2014-04-25 05:29:35 +0000240 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000241
Chris Lattnerfe741762012-01-31 02:55:06 +0000242 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +0000243 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000244
Chris Lattner2188e402010-01-04 07:37:31 +0000245 // There are many forms of this optimization we can handle, for now, just do
246 // the simple index into a single-dimensional array.
247 //
248 // Require: GEP GV, 0, i {{, constant indices}}
249 if (GEP->getNumOperands() < 3 ||
250 !isa<ConstantInt>(GEP->getOperand(1)) ||
251 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
252 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000253 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000254
255 // Check that indices after the variable are constants and in-range for the
256 // type they index. Collect the indices. This is typically for arrays of
257 // structs.
258 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000259
Chris Lattnerfe741762012-01-31 02:55:06 +0000260 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000261 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
262 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000263 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000264
Chris Lattner2188e402010-01-04 07:37:31 +0000265 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000266 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000267
Chris Lattner229907c2011-07-18 04:54:35 +0000268 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000269 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000270 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000271 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000272 EltTy = ATy->getElementType();
273 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000274 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000275 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000276
Chris Lattner2188e402010-01-04 07:37:31 +0000277 LaterIndices.push_back(IdxVal);
278 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000279
Chris Lattner2188e402010-01-04 07:37:31 +0000280 enum { Overdefined = -3, Undefined = -2 };
281
282 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000283
Chris Lattner2188e402010-01-04 07:37:31 +0000284 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
285 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
286 // and 87 is the second (and last) index. FirstTrueElement is -2 when
287 // undefined, otherwise set to the first true element. SecondTrueElement is
288 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
289 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
290
291 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
292 // form "i != 47 & i != 87". Same state transitions as for true elements.
293 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000294
Chris Lattner2188e402010-01-04 07:37:31 +0000295 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
296 /// define a state machine that triggers for ranges of values that the index
297 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
298 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
299 /// index in the range (inclusive). We use -2 for undefined here because we
300 /// use relative comparisons and don't want 0-1 to match -1.
301 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000302
Chris Lattner2188e402010-01-04 07:37:31 +0000303 // MagicBitvector - This is a magic bitvector where we set a bit if the
304 // comparison is true for element 'i'. If there are 64 elements or less in
305 // the array, this will fully represent all the comparison results.
306 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000307
Chris Lattner2188e402010-01-04 07:37:31 +0000308 // Scan the array and see if one of our patterns matches.
309 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000310 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
311 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000312 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000313
Chris Lattner2188e402010-01-04 07:37:31 +0000314 // If this is indexing an array of structures, get the structure element.
315 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000316 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000317
Chris Lattner2188e402010-01-04 07:37:31 +0000318 // If the element is masked, handle it.
319 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000320
Chris Lattner2188e402010-01-04 07:37:31 +0000321 // Find out if the comparison would be true or false for the i'th element.
322 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000323 CompareRHS, DL, TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000324 // If the result is undef for this element, ignore it.
325 if (isa<UndefValue>(C)) {
326 // Extend range state machines to cover this element in case there is an
327 // undef in the middle of the range.
328 if (TrueRangeEnd == (int)i-1)
329 TrueRangeEnd = i;
330 if (FalseRangeEnd == (int)i-1)
331 FalseRangeEnd = i;
332 continue;
333 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000334
Chris Lattner2188e402010-01-04 07:37:31 +0000335 // If we can't compute the result for any of the elements, we have to give
336 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000337 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000338
Chris Lattner2188e402010-01-04 07:37:31 +0000339 // Otherwise, we know if the comparison is true or false for this element,
340 // update our state machines.
341 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000342
Chris Lattner2188e402010-01-04 07:37:31 +0000343 // State machine for single/double/range index comparison.
344 if (IsTrueForElt) {
345 // Update the TrueElement state machine.
346 if (FirstTrueElement == Undefined)
347 FirstTrueElement = TrueRangeEnd = i; // First true element.
348 else {
349 // Update double-compare state machine.
350 if (SecondTrueElement == Undefined)
351 SecondTrueElement = i;
352 else
353 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000354
Chris Lattner2188e402010-01-04 07:37:31 +0000355 // Update range state machine.
356 if (TrueRangeEnd == (int)i-1)
357 TrueRangeEnd = i;
358 else
359 TrueRangeEnd = Overdefined;
360 }
361 } else {
362 // Update the FalseElement state machine.
363 if (FirstFalseElement == Undefined)
364 FirstFalseElement = FalseRangeEnd = i; // First false element.
365 else {
366 // Update double-compare state machine.
367 if (SecondFalseElement == Undefined)
368 SecondFalseElement = i;
369 else
370 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000371
Chris Lattner2188e402010-01-04 07:37:31 +0000372 // Update range state machine.
373 if (FalseRangeEnd == (int)i-1)
374 FalseRangeEnd = i;
375 else
376 FalseRangeEnd = Overdefined;
377 }
378 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000379
Chris Lattner2188e402010-01-04 07:37:31 +0000380 // If this element is in range, update our magic bitvector.
381 if (i < 64 && IsTrueForElt)
382 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000383
Chris Lattner2188e402010-01-04 07:37:31 +0000384 // If all of our states become overdefined, bail out early. Since the
385 // predicate is expensive, only check it every 8 elements. This is only
386 // really useful for really huge arrays.
387 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
388 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
389 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000390 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000391 }
392
393 // Now that we've scanned the entire array, emit our new comparison(s). We
394 // order the state machines in complexity of the generated code.
395 Value *Idx = GEP->getOperand(2);
396
Matt Arsenault5aeae182013-08-19 21:40:31 +0000397 // If the index is larger than the pointer size of the target, truncate the
398 // index down like the GEP would do implicitly. We don't have to do this for
399 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000400 if (!GEP->isInBounds()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000401 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000402 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
403 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
404 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
405 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000406
Chris Lattner2188e402010-01-04 07:37:31 +0000407 // If the comparison is only true for one or two elements, emit direct
408 // comparisons.
409 if (SecondTrueElement != Overdefined) {
410 // None true -> false.
411 if (FirstTrueElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000412 return replaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000413
Chris Lattner2188e402010-01-04 07:37:31 +0000414 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000415
Chris Lattner2188e402010-01-04 07:37:31 +0000416 // True for one element -> 'i == 47'.
417 if (SecondTrueElement == Undefined)
418 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000419
Chris Lattner2188e402010-01-04 07:37:31 +0000420 // True for two elements -> 'i == 47 | i == 72'.
421 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
422 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
423 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
424 return BinaryOperator::CreateOr(C1, C2);
425 }
426
427 // If the comparison is only false for one or two elements, emit direct
428 // comparisons.
429 if (SecondFalseElement != Overdefined) {
430 // None false -> true.
431 if (FirstFalseElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000432 return replaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000433
Chris Lattner2188e402010-01-04 07:37:31 +0000434 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
435
436 // False for one element -> 'i != 47'.
437 if (SecondFalseElement == Undefined)
438 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000439
Chris Lattner2188e402010-01-04 07:37:31 +0000440 // False for two elements -> 'i != 47 & i != 72'.
441 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
442 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
443 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
444 return BinaryOperator::CreateAnd(C1, C2);
445 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000446
Chris Lattner2188e402010-01-04 07:37:31 +0000447 // If the comparison can be replaced with a range comparison for the elements
448 // where it is true, emit the range check.
449 if (TrueRangeEnd != Overdefined) {
450 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000451
Chris Lattner2188e402010-01-04 07:37:31 +0000452 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
453 if (FirstTrueElement) {
454 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
455 Idx = Builder->CreateAdd(Idx, Offs);
456 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000457
Chris Lattner2188e402010-01-04 07:37:31 +0000458 Value *End = ConstantInt::get(Idx->getType(),
459 TrueRangeEnd-FirstTrueElement+1);
460 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
461 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000462
Chris Lattner2188e402010-01-04 07:37:31 +0000463 // False range check.
464 if (FalseRangeEnd != Overdefined) {
465 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
466 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
467 if (FirstFalseElement) {
468 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
469 Idx = Builder->CreateAdd(Idx, Offs);
470 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000471
Chris Lattner2188e402010-01-04 07:37:31 +0000472 Value *End = ConstantInt::get(Idx->getType(),
473 FalseRangeEnd-FirstFalseElement);
474 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
475 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000476
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000477 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000478 // of this load, replace it with computation that does:
479 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000480 {
Craig Topperf40110f2014-04-25 05:29:35 +0000481 Type *Ty = nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000482
483 // Look for an appropriate type:
484 // - The type of Idx if the magic fits
485 // - The smallest fitting legal type if we have a DataLayout
486 // - Default to i32
487 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
488 Ty = Idx->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000489 else
490 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000491
Craig Topperf40110f2014-04-25 05:29:35 +0000492 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000493 Value *V = Builder->CreateIntCast(Idx, Ty, false);
494 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
495 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
496 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
497 }
Chris Lattner2188e402010-01-04 07:37:31 +0000498 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000499
Craig Topperf40110f2014-04-25 05:29:35 +0000500 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000501}
502
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000503/// Return a value that can be used to compare the *offset* implied by a GEP to
504/// zero. For example, if we have &A[i], we want to return 'i' for
505/// "icmp ne i, 0". Note that, in general, indices can be complex, and scales
506/// are involved. The above expression would also be legal to codegen as
507/// "icmp ne (i*4), 0" (assuming A is a pointer to i32).
508/// This latter form is less amenable to optimization though, and we are allowed
Chris Lattner2188e402010-01-04 07:37:31 +0000509/// to generate the first by knowing that pointer arithmetic doesn't overflow.
510///
511/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000512///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000513static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
514 const DataLayout &DL) {
Chris Lattner2188e402010-01-04 07:37:31 +0000515 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000516
Chris Lattner2188e402010-01-04 07:37:31 +0000517 // Check to see if this gep only has a single variable index. If so, and if
518 // any constant indices are a multiple of its scale, then we can compute this
519 // in terms of the scale of the variable index. For example, if the GEP
520 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
521 // because the expression will cross zero at the same point.
522 unsigned i, e = GEP->getNumOperands();
523 int64_t Offset = 0;
524 for (i = 1; i != e; ++i, ++GTI) {
525 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
526 // Compute the aggregate offset of constant indices.
527 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000528
Chris Lattner2188e402010-01-04 07:37:31 +0000529 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000530 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000531 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000532 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000533 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000534 Offset += Size*CI->getSExtValue();
535 }
536 } else {
537 // Found our variable index.
538 break;
539 }
540 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000541
Chris Lattner2188e402010-01-04 07:37:31 +0000542 // If there are no variable indices, we must have a constant offset, just
543 // evaluate it the general way.
Craig Topperf40110f2014-04-25 05:29:35 +0000544 if (i == e) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000545
Chris Lattner2188e402010-01-04 07:37:31 +0000546 Value *VariableIdx = GEP->getOperand(i);
547 // Determine the scale factor of the variable element. For example, this is
548 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000549 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000550
Chris Lattner2188e402010-01-04 07:37:31 +0000551 // Verify that there are no other variable indices. If so, emit the hard way.
552 for (++i, ++GTI; i != e; ++i, ++GTI) {
553 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000554 if (!CI) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000555
Chris Lattner2188e402010-01-04 07:37:31 +0000556 // Compute the aggregate offset of constant indices.
557 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000558
Chris Lattner2188e402010-01-04 07:37:31 +0000559 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000560 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000561 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000562 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000563 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000564 Offset += Size*CI->getSExtValue();
565 }
566 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000567
Chris Lattner2188e402010-01-04 07:37:31 +0000568 // Okay, we know we have a single variable index, which must be a
569 // pointer/array/vector index. If there is no offset, life is simple, return
570 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000571 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000572 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000573 if (Offset == 0) {
574 // Cast to intptrty in case a truncation occurs. If an extension is needed,
575 // we don't need to bother extending: the extension won't affect where the
576 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000577 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000578 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
579 }
Chris Lattner2188e402010-01-04 07:37:31 +0000580 return VariableIdx;
581 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000582
Chris Lattner2188e402010-01-04 07:37:31 +0000583 // Otherwise, there is an index. The computation we will do will be modulo
584 // the pointer size, so get it.
585 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000586
Chris Lattner2188e402010-01-04 07:37:31 +0000587 Offset &= PtrSizeMask;
588 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000589
Chris Lattner2188e402010-01-04 07:37:31 +0000590 // To do this transformation, any constant index must be a multiple of the
591 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
592 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
593 // multiple of the variable scale.
594 int64_t NewOffs = Offset / (int64_t)VariableScale;
595 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000596 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000597
Chris Lattner2188e402010-01-04 07:37:31 +0000598 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000599 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000600 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
601 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000602 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000603 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000604}
605
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000606/// Returns true if we can rewrite Start as a GEP with pointer Base
607/// and some integer offset. The nodes that need to be re-written
608/// for this transformation will be added to Explored.
609static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
610 const DataLayout &DL,
611 SetVector<Value *> &Explored) {
612 SmallVector<Value *, 16> WorkList(1, Start);
613 Explored.insert(Base);
614
615 // The following traversal gives us an order which can be used
616 // when doing the final transformation. Since in the final
617 // transformation we create the PHI replacement instructions first,
618 // we don't have to get them in any particular order.
619 //
620 // However, for other instructions we will have to traverse the
621 // operands of an instruction first, which means that we have to
622 // do a post-order traversal.
623 while (!WorkList.empty()) {
624 SetVector<PHINode *> PHIs;
625
626 while (!WorkList.empty()) {
627 if (Explored.size() >= 100)
628 return false;
629
630 Value *V = WorkList.back();
631
632 if (Explored.count(V) != 0) {
633 WorkList.pop_back();
634 continue;
635 }
636
637 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
638 !isa<GEPOperator>(V) && !isa<PHINode>(V))
639 // We've found some value that we can't explore which is different from
640 // the base. Therefore we can't do this transformation.
641 return false;
642
643 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
644 auto *CI = dyn_cast<CastInst>(V);
645 if (!CI->isNoopCast(DL))
646 return false;
647
648 if (Explored.count(CI->getOperand(0)) == 0)
649 WorkList.push_back(CI->getOperand(0));
650 }
651
652 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
653 // We're limiting the GEP to having one index. This will preserve
654 // the original pointer type. We could handle more cases in the
655 // future.
656 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
657 GEP->getType() != Start->getType())
658 return false;
659
660 if (Explored.count(GEP->getOperand(0)) == 0)
661 WorkList.push_back(GEP->getOperand(0));
662 }
663
664 if (WorkList.back() == V) {
665 WorkList.pop_back();
666 // We've finished visiting this node, mark it as such.
667 Explored.insert(V);
668 }
669
670 if (auto *PN = dyn_cast<PHINode>(V)) {
David Majnemercdf28732016-03-19 04:39:52 +0000671 // We cannot transform PHIs on unsplittable basic blocks.
672 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
673 return false;
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000674 Explored.insert(PN);
675 PHIs.insert(PN);
676 }
677 }
678
679 // Explore the PHI nodes further.
680 for (auto *PN : PHIs)
681 for (Value *Op : PN->incoming_values())
682 if (Explored.count(Op) == 0)
683 WorkList.push_back(Op);
684 }
685
686 // Make sure that we can do this. Since we can't insert GEPs in a basic
687 // block before a PHI node, we can't easily do this transformation if
688 // we have PHI node users of transformed instructions.
689 for (Value *Val : Explored) {
690 for (Value *Use : Val->uses()) {
691
692 auto *PHI = dyn_cast<PHINode>(Use);
693 auto *Inst = dyn_cast<Instruction>(Val);
694
695 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
696 Explored.count(PHI) == 0)
697 continue;
698
699 if (PHI->getParent() == Inst->getParent())
700 return false;
701 }
702 }
703 return true;
704}
705
706// Sets the appropriate insert point on Builder where we can add
707// a replacement Instruction for V (if that is possible).
708static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
709 bool Before = true) {
710 if (auto *PHI = dyn_cast<PHINode>(V)) {
711 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
712 return;
713 }
714 if (auto *I = dyn_cast<Instruction>(V)) {
715 if (!Before)
716 I = &*std::next(I->getIterator());
717 Builder.SetInsertPoint(I);
718 return;
719 }
720 if (auto *A = dyn_cast<Argument>(V)) {
721 // Set the insertion point in the entry block.
722 BasicBlock &Entry = A->getParent()->getEntryBlock();
723 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
724 return;
725 }
726 // Otherwise, this is a constant and we don't need to set a new
727 // insertion point.
728 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
729}
730
731/// Returns a re-written value of Start as an indexed GEP using Base as a
732/// pointer.
733static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
734 const DataLayout &DL,
735 SetVector<Value *> &Explored) {
736 // Perform all the substitutions. This is a bit tricky because we can
737 // have cycles in our use-def chains.
738 // 1. Create the PHI nodes without any incoming values.
739 // 2. Create all the other values.
740 // 3. Add the edges for the PHI nodes.
741 // 4. Emit GEPs to get the original pointers.
742 // 5. Remove the original instructions.
743 Type *IndexType = IntegerType::get(
744 Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType()));
745
746 DenseMap<Value *, Value *> NewInsts;
747 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
748
749 // Create the new PHI nodes, without adding any incoming values.
750 for (Value *Val : Explored) {
751 if (Val == Base)
752 continue;
753 // Create empty phi nodes. This avoids cyclic dependencies when creating
754 // the remaining instructions.
755 if (auto *PHI = dyn_cast<PHINode>(Val))
756 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
757 PHI->getName() + ".idx", PHI);
758 }
759 IRBuilder<> Builder(Base->getContext());
760
761 // Create all the other instructions.
762 for (Value *Val : Explored) {
763
764 if (NewInsts.find(Val) != NewInsts.end())
765 continue;
766
767 if (auto *CI = dyn_cast<CastInst>(Val)) {
768 NewInsts[CI] = NewInsts[CI->getOperand(0)];
769 continue;
770 }
771 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
772 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
773 : GEP->getOperand(1);
774 setInsertionPoint(Builder, GEP);
775 // Indices might need to be sign extended. GEPs will magically do
776 // this, but we need to do it ourselves here.
777 if (Index->getType()->getScalarSizeInBits() !=
778 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
779 Index = Builder.CreateSExtOrTrunc(
780 Index, NewInsts[GEP->getOperand(0)]->getType(),
781 GEP->getOperand(0)->getName() + ".sext");
782 }
783
784 auto *Op = NewInsts[GEP->getOperand(0)];
785 if (isa<ConstantInt>(Op) && dyn_cast<ConstantInt>(Op)->isZero())
786 NewInsts[GEP] = Index;
787 else
788 NewInsts[GEP] = Builder.CreateNSWAdd(
789 Op, Index, GEP->getOperand(0)->getName() + ".add");
790 continue;
791 }
792 if (isa<PHINode>(Val))
793 continue;
794
795 llvm_unreachable("Unexpected instruction type");
796 }
797
798 // Add the incoming values to the PHI nodes.
799 for (Value *Val : Explored) {
800 if (Val == Base)
801 continue;
802 // All the instructions have been created, we can now add edges to the
803 // phi nodes.
804 if (auto *PHI = dyn_cast<PHINode>(Val)) {
805 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
806 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
807 Value *NewIncoming = PHI->getIncomingValue(I);
808
809 if (NewInsts.find(NewIncoming) != NewInsts.end())
810 NewIncoming = NewInsts[NewIncoming];
811
812 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
813 }
814 }
815 }
816
817 for (Value *Val : Explored) {
818 if (Val == Base)
819 continue;
820
821 // Depending on the type, for external users we have to emit
822 // a GEP or a GEP + ptrtoint.
823 setInsertionPoint(Builder, Val, false);
824
825 // If required, create an inttoptr instruction for Base.
826 Value *NewBase = Base;
827 if (!Base->getType()->isPointerTy())
828 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
829 Start->getName() + "to.ptr");
830
831 Value *GEP = Builder.CreateInBoundsGEP(
832 Start->getType()->getPointerElementType(), NewBase,
833 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
834
835 if (!Val->getType()->isPointerTy()) {
836 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
837 Val->getName() + ".conv");
838 GEP = Cast;
839 }
840 Val->replaceAllUsesWith(GEP);
841 }
842
843 return NewInsts[Start];
844}
845
846/// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
847/// the input Value as a constant indexed GEP. Returns a pair containing
848/// the GEPs Pointer and Index.
849static std::pair<Value *, Value *>
850getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
851 Type *IndexType = IntegerType::get(V->getContext(),
852 DL.getPointerTypeSizeInBits(V->getType()));
853
854 Constant *Index = ConstantInt::getNullValue(IndexType);
855 while (true) {
856 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
857 // We accept only inbouds GEPs here to exclude the possibility of
858 // overflow.
859 if (!GEP->isInBounds())
860 break;
861 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
862 GEP->getType() == V->getType()) {
863 V = GEP->getOperand(0);
864 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
865 Index = ConstantExpr::getAdd(
866 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
867 continue;
868 }
869 break;
870 }
871 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
872 if (!CI->isNoopCast(DL))
873 break;
874 V = CI->getOperand(0);
875 continue;
876 }
877 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
878 if (!CI->isNoopCast(DL))
879 break;
880 V = CI->getOperand(0);
881 continue;
882 }
883 break;
884 }
885 return {V, Index};
886}
887
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000888/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
889/// We can look through PHIs, GEPs and casts in order to determine a common base
890/// between GEPLHS and RHS.
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000891static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
892 ICmpInst::Predicate Cond,
893 const DataLayout &DL) {
894 if (!GEPLHS->hasAllConstantIndices())
895 return nullptr;
896
897 Value *PtrBase, *Index;
898 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
899
900 // The set of nodes that will take part in this transformation.
901 SetVector<Value *> Nodes;
902
903 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
904 return nullptr;
905
906 // We know we can re-write this as
907 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
908 // Since we've only looked through inbouds GEPs we know that we
909 // can't have overflow on either side. We can therefore re-write
910 // this as:
911 // OFFSET1 cmp OFFSET2
912 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
913
914 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
915 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
916 // offset. Since Index is the offset of LHS to the base pointer, we will now
917 // compare the offsets instead of comparing the pointers.
918 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
919}
920
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000921/// Fold comparisons between a GEP instruction and something else. At this point
922/// we know that the GEP is on the LHS of the comparison.
Sanjay Patel43395062016-07-21 18:07:40 +0000923Instruction *InstCombiner::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000924 ICmpInst::Predicate Cond,
925 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000926 // Don't transform signed compares of GEPs into index compares. Even if the
927 // GEP is inbounds, the final add of the base pointer can have signed overflow
928 // and would change the result of the icmp.
929 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000930 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000931 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000932 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000933
Matt Arsenault44f60d02014-06-09 19:20:29 +0000934 // Look through bitcasts and addrspacecasts. We do not however want to remove
935 // 0 GEPs.
936 if (!isa<GetElementPtrInst>(RHS))
937 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000938
939 Value *PtrBase = GEPLHS->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000940 if (PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000941 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
942 // This transformation (ignoring the base and scales) is valid because we
943 // know pointers can't overflow since the gep is inbounds. See if we can
944 // output an optimized form.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000945 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this, DL);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000946
Chris Lattner2188e402010-01-04 07:37:31 +0000947 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000948 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000949 Offset = EmitGEPOffset(GEPLHS);
950 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
951 Constant::getNullValue(Offset->getType()));
952 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
953 // If the base pointers are different, but the indices are the same, just
954 // compare the base pointer.
955 if (PtrBase != GEPRHS->getOperand(0)) {
956 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
957 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
958 GEPRHS->getOperand(0)->getType();
959 if (IndicesTheSame)
960 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
961 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
962 IndicesTheSame = false;
963 break;
964 }
965
966 // If all indices are the same, just compare the base pointers.
967 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000968 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000969
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000970 // If we're comparing GEPs with two base pointers that only differ in type
971 // and both GEPs have only constant indices or just one use, then fold
972 // the compare with the adjusted indices.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000973 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000974 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
975 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
976 PtrBase->stripPointerCasts() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000977 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000978 Value *LOffset = EmitGEPOffset(GEPLHS);
979 Value *ROffset = EmitGEPOffset(GEPRHS);
980
981 // If we looked through an addrspacecast between different sized address
982 // spaces, the LHS and RHS pointers are different sized
983 // integers. Truncate to the smaller one.
984 Type *LHSIndexTy = LOffset->getType();
985 Type *RHSIndexTy = ROffset->getType();
986 if (LHSIndexTy != RHSIndexTy) {
987 if (LHSIndexTy->getPrimitiveSizeInBits() <
988 RHSIndexTy->getPrimitiveSizeInBits()) {
989 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
990 } else
991 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
992 }
993
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000994 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000995 LOffset, ROffset);
Sanjay Patel4b198802016-02-01 22:23:39 +0000996 return replaceInstUsesWith(I, Cmp);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000997 }
998
Chris Lattner2188e402010-01-04 07:37:31 +0000999 // Otherwise, the base pointers are different and the indices are
Silviu Barangaf29dfd32016-01-15 15:52:05 +00001000 // different. Try convert this to an indexed compare by looking through
1001 // PHIs/casts.
1002 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +00001003 }
1004
1005 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001006 if (GEPLHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +00001007 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +00001008 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +00001009
1010 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001011 if (GEPRHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +00001012 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner2188e402010-01-04 07:37:31 +00001013
Stuart Hastings66a82b92011-05-14 05:55:10 +00001014 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +00001015 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
1016 // If the GEPs only differ by one index, compare it.
1017 unsigned NumDifferences = 0; // Keep track of # differences.
1018 unsigned DiffOperand = 0; // The operand that differs.
1019 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
1020 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
1021 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
1022 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
1023 // Irreconcilable differences.
1024 NumDifferences = 2;
1025 break;
1026 } else {
1027 if (NumDifferences++) break;
1028 DiffOperand = i;
1029 }
1030 }
1031
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +00001032 if (NumDifferences == 0) // SAME GEP?
Sanjay Patel4b198802016-02-01 22:23:39 +00001033 return replaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +00001034 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +00001035
Stuart Hastings66a82b92011-05-14 05:55:10 +00001036 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +00001037 Value *LHSV = GEPLHS->getOperand(DiffOperand);
1038 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1039 // Make sure we do a signed comparison here.
1040 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
1041 }
1042 }
1043
1044 // Only lower this if the icmp is the only user of the GEP or if we expect
1045 // the result to fold to a constant!
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001046 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner2188e402010-01-04 07:37:31 +00001047 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1048 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
1049 Value *L = EmitGEPOffset(GEPLHS);
1050 Value *R = EmitGEPOffset(GEPRHS);
1051 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1052 }
1053 }
Silviu Barangaf29dfd32016-01-15 15:52:05 +00001054
1055 // Try convert this to an indexed compare by looking through PHIs/casts as a
1056 // last resort.
1057 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +00001058}
1059
Sanjay Patel43395062016-07-21 18:07:40 +00001060Instruction *InstCombiner::foldAllocaCmp(ICmpInst &ICI, AllocaInst *Alloca,
Hans Wennborgf1f36512015-10-07 00:20:07 +00001061 Value *Other) {
1062 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1063
1064 // It would be tempting to fold away comparisons between allocas and any
1065 // pointer not based on that alloca (e.g. an argument). However, even
1066 // though such pointers cannot alias, they can still compare equal.
1067 //
1068 // But LLVM doesn't specify where allocas get their memory, so if the alloca
1069 // doesn't escape we can argue that it's impossible to guess its value, and we
1070 // can therefore act as if any such guesses are wrong.
1071 //
1072 // The code below checks that the alloca doesn't escape, and that it's only
1073 // used in a comparison once (the current instruction). The
1074 // single-comparison-use condition ensures that we're trivially folding all
1075 // comparisons against the alloca consistently, and avoids the risk of
1076 // erroneously folding a comparison of the pointer with itself.
1077
1078 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1079
1080 SmallVector<Use *, 32> Worklist;
1081 for (Use &U : Alloca->uses()) {
1082 if (Worklist.size() >= MaxIter)
1083 return nullptr;
1084 Worklist.push_back(&U);
1085 }
1086
1087 unsigned NumCmps = 0;
1088 while (!Worklist.empty()) {
1089 assert(Worklist.size() <= MaxIter);
1090 Use *U = Worklist.pop_back_val();
1091 Value *V = U->getUser();
1092 --MaxIter;
1093
1094 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1095 isa<SelectInst>(V)) {
1096 // Track the uses.
1097 } else if (isa<LoadInst>(V)) {
1098 // Loading from the pointer doesn't escape it.
1099 continue;
1100 } else if (auto *SI = dyn_cast<StoreInst>(V)) {
1101 // Storing *to* the pointer is fine, but storing the pointer escapes it.
1102 if (SI->getValueOperand() == U->get())
1103 return nullptr;
1104 continue;
1105 } else if (isa<ICmpInst>(V)) {
1106 if (NumCmps++)
1107 return nullptr; // Found more than one cmp.
1108 continue;
1109 } else if (auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
1110 switch (Intrin->getIntrinsicID()) {
1111 // These intrinsics don't escape or compare the pointer. Memset is safe
1112 // because we don't allow ptrtoint. Memcpy and memmove are safe because
1113 // we don't allow stores, so src cannot point to V.
1114 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1115 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
1116 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1117 continue;
1118 default:
1119 return nullptr;
1120 }
1121 } else {
1122 return nullptr;
1123 }
1124 for (Use &U : V->uses()) {
1125 if (Worklist.size() >= MaxIter)
1126 return nullptr;
1127 Worklist.push_back(&U);
1128 }
1129 }
1130
1131 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001132 return replaceInstUsesWith(
Hans Wennborgf1f36512015-10-07 00:20:07 +00001133 ICI,
1134 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1135}
1136
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001137/// Fold "icmp pred (X+CI), X".
Sanjay Patel43395062016-07-21 18:07:40 +00001138Instruction *InstCombiner::foldICmpAddOpConst(Instruction &ICI,
1139 Value *X, ConstantInt *CI,
1140 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +00001141 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001142 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +00001143 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +00001144
Chris Lattner8c92b572010-01-08 17:48:19 +00001145 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +00001146 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
1147 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
1148 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00001149 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +00001150 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +00001151 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1152 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001153
Chris Lattner2188e402010-01-04 07:37:31 +00001154 // (X+1) >u X --> X <u (0-1) --> X != 255
1155 // (X+2) >u X --> X <u (0-2) --> X <u 254
1156 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +00001157 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +00001158 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001159
Chris Lattner2188e402010-01-04 07:37:31 +00001160 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
1161 ConstantInt *SMax = ConstantInt::get(X->getContext(),
1162 APInt::getSignedMaxValue(BitWidth));
1163
1164 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1165 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1166 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1167 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1168 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1169 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +00001170 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +00001171 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001172
Chris Lattner2188e402010-01-04 07:37:31 +00001173 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1174 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1175 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1176 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1177 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1178 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +00001179
Chris Lattner2188e402010-01-04 07:37:31 +00001180 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +00001181 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +00001182 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
1183}
1184
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001185/// Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS and CmpRHS are
1186/// both known to be integer constants.
Sanjay Patel43395062016-07-21 18:07:40 +00001187Instruction *InstCombiner::foldICmpDivConst(ICmpInst &ICI, BinaryOperator *DivI,
1188 ConstantInt *DivRHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001189 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
1190 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001191
1192 // FIXME: If the operand types don't match the type of the divide
Chris Lattner2188e402010-01-04 07:37:31 +00001193 // then don't attempt this transform. The code below doesn't have the
1194 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach129c52a2011-09-30 18:09:53 +00001195 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner2188e402010-01-04 07:37:31 +00001196 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach129c52a2011-09-30 18:09:53 +00001197 // (x /u C1) <u C2. Simply casting the operands and result won't
1198 // work. :( The if statement below tests that condition and bails
Chris Lattner98457102011-02-10 05:23:05 +00001199 // if it finds it.
Chris Lattner2188e402010-01-04 07:37:31 +00001200 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
1201 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Craig Topperf40110f2014-04-25 05:29:35 +00001202 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001203 if (DivRHS->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +00001204 return nullptr; // The ProdOV computation fails on divide by zero.
Chris Lattner2188e402010-01-04 07:37:31 +00001205 if (DivIsSigned && DivRHS->isAllOnesValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001206 return nullptr; // The overflow computation also screws up here
Chris Lattner43273af2011-02-13 08:07:21 +00001207 if (DivRHS->isOne()) {
1208 // This eliminates some funny cases with INT_MIN.
1209 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
1210 return &ICI;
1211 }
Chris Lattner2188e402010-01-04 07:37:31 +00001212
1213 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach129c52a2011-09-30 18:09:53 +00001214 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
1215 // C2 (CI). By solving for X we can turn this into a range check
1216 // instead of computing a divide.
Chris Lattner2188e402010-01-04 07:37:31 +00001217 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
1218
1219 // Determine if the product overflows by seeing if the product is
1220 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach129c52a2011-09-30 18:09:53 +00001221 // as in the LHS instruction that we're folding.
Chris Lattner2188e402010-01-04 07:37:31 +00001222 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
1223 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
1224
1225 // Get the ICmp opcode
1226 ICmpInst::Predicate Pred = ICI.getPredicate();
1227
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001228 // If the division is known to be exact, then there is no remainder from the
1229 // divide, so the covered range size is unit, otherwise it is the divisor.
Chris Lattner98457102011-02-10 05:23:05 +00001230 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001231
Chris Lattner2188e402010-01-04 07:37:31 +00001232 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach129c52a2011-09-30 18:09:53 +00001233 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner2188e402010-01-04 07:37:31 +00001234 // Compute this interval based on the constants involved and the signedness of
1235 // the compare/divide. This computes a half-open interval, keeping track of
1236 // whether either value in the interval overflows. After analysis each
1237 // overflow variable is set to 0 if it's corresponding bound variable is valid
1238 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
1239 int LoOverflow = 0, HiOverflow = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001240 Constant *LoBound = nullptr, *HiBound = nullptr;
Chris Lattner98457102011-02-10 05:23:05 +00001241
Chris Lattner2188e402010-01-04 07:37:31 +00001242 if (!DivIsSigned) { // udiv
1243 // e.g. X/5 op 3 --> [15, 20)
1244 LoBound = Prod;
1245 HiOverflow = LoOverflow = ProdOV;
Chris Lattner98457102011-02-10 05:23:05 +00001246 if (!HiOverflow) {
1247 // If this is not an exact divide, then many values in the range collapse
1248 // to the same result value.
1249 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
1250 }
Chris Lattner2188e402010-01-04 07:37:31 +00001251 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
1252 if (CmpRHSV == 0) { // (X / pos) op 0
1253 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner98457102011-02-10 05:23:05 +00001254 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
1255 HiBound = RangeSize;
Chris Lattner2188e402010-01-04 07:37:31 +00001256 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
1257 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
1258 HiOverflow = LoOverflow = ProdOV;
1259 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001260 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +00001261 } else { // (X / pos) op neg
1262 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
1263 HiBound = AddOne(Prod);
1264 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
1265 if (!LoOverflow) {
Chris Lattner98457102011-02-10 05:23:05 +00001266 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001267 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattner98457102011-02-10 05:23:05 +00001268 }
Chris Lattner2188e402010-01-04 07:37:31 +00001269 }
Chris Lattnerb1a15122011-07-15 06:08:15 +00001270 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattner98457102011-02-10 05:23:05 +00001271 if (DivI->isExact())
1272 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001273 if (CmpRHSV == 0) { // (X / neg) op 0
1274 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner98457102011-02-10 05:23:05 +00001275 LoBound = AddOne(RangeSize);
1276 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001277 if (HiBound == DivRHS) { // -INTMIN = INTMIN
1278 HiOverflow = 1; // [INTMIN+1, overflow)
Craig Topperf40110f2014-04-25 05:29:35 +00001279 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
Chris Lattner2188e402010-01-04 07:37:31 +00001280 }
1281 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
1282 // e.g. X/-5 op 3 --> [-19, -14)
1283 HiBound = AddOne(Prod);
1284 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
1285 if (!LoOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001286 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner2188e402010-01-04 07:37:31 +00001287 } else { // (X / neg) op neg
1288 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
1289 LoOverflow = HiOverflow = ProdOV;
1290 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001291 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +00001292 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001293
Chris Lattner2188e402010-01-04 07:37:31 +00001294 // Dividing by a negative swaps the condition. LT <-> GT
1295 Pred = ICmpInst::getSwappedPredicate(Pred);
1296 }
1297
1298 Value *X = DivI->getOperand(0);
1299 switch (Pred) {
1300 default: llvm_unreachable("Unhandled icmp opcode!");
1301 case ICmpInst::ICMP_EQ:
1302 if (LoOverflow && HiOverflow)
Sanjay Patel4b198802016-02-01 22:23:39 +00001303 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner067459c2010-03-05 08:46:26 +00001304 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001305 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1306 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +00001307 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001308 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1309 ICmpInst::ICMP_ULT, X, HiBound);
Sanjay Patel4b198802016-02-01 22:23:39 +00001310 return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
Chris Lattner98457102011-02-10 05:23:05 +00001311 DivIsSigned, true));
Chris Lattner2188e402010-01-04 07:37:31 +00001312 case ICmpInst::ICMP_NE:
1313 if (LoOverflow && HiOverflow)
Sanjay Patel4b198802016-02-01 22:23:39 +00001314 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner067459c2010-03-05 08:46:26 +00001315 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001316 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1317 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +00001318 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001319 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1320 ICmpInst::ICMP_UGE, X, HiBound);
Sanjay Patel4b198802016-02-01 22:23:39 +00001321 return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
Chris Lattner067459c2010-03-05 08:46:26 +00001322 DivIsSigned, false));
Chris Lattner2188e402010-01-04 07:37:31 +00001323 case ICmpInst::ICMP_ULT:
1324 case ICmpInst::ICMP_SLT:
1325 if (LoOverflow == +1) // Low bound is greater than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001326 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001327 if (LoOverflow == -1) // Low bound is less than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001328 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001329 return new ICmpInst(Pred, X, LoBound);
1330 case ICmpInst::ICMP_UGT:
1331 case ICmpInst::ICMP_SGT:
1332 if (HiOverflow == +1) // High bound greater than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001333 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner98457102011-02-10 05:23:05 +00001334 if (HiOverflow == -1) // High bound less than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001335 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001336 if (Pred == ICmpInst::ICMP_UGT)
1337 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +00001338 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner2188e402010-01-04 07:37:31 +00001339 }
1340}
1341
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001342/// Handle "icmp(([al]shr X, cst1), cst2)".
Sanjay Patel43395062016-07-21 18:07:40 +00001343Instruction *InstCombiner::foldICmpShrConst(ICmpInst &ICI, BinaryOperator *Shr,
1344 ConstantInt *ShAmt) {
Chris Lattnerd369f572011-02-13 07:43:07 +00001345 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001346
Chris Lattnerd369f572011-02-13 07:43:07 +00001347 // Check that the shift amount is in range. If not, don't perform
1348 // undefined shifts. When the shift is visited it will be
1349 // simplified.
1350 uint32_t TypeBits = CmpRHSV.getBitWidth();
1351 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner43273af2011-02-13 08:07:21 +00001352 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001353 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001354
Chris Lattner43273af2011-02-13 08:07:21 +00001355 if (!ICI.isEquality()) {
1356 // If we have an unsigned comparison and an ashr, we can't simplify this.
1357 // Similarly for signed comparisons with lshr.
1358 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
Craig Topperf40110f2014-04-25 05:29:35 +00001359 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001360
Eli Friedman865866e2011-05-25 23:26:20 +00001361 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
1362 // by a power of 2. Since we already have logic to simplify these,
1363 // transform to div and then simplify the resultant comparison.
Chris Lattner43273af2011-02-13 08:07:21 +00001364 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedman865866e2011-05-25 23:26:20 +00001365 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Craig Topperf40110f2014-04-25 05:29:35 +00001366 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001367
Chris Lattner43273af2011-02-13 08:07:21 +00001368 // Revisit the shift (to delete it).
1369 Worklist.Add(Shr);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001370
Chris Lattner43273af2011-02-13 08:07:21 +00001371 Constant *DivCst =
1372 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001373
Chris Lattner43273af2011-02-13 08:07:21 +00001374 Value *Tmp =
1375 Shr->getOpcode() == Instruction::AShr ?
1376 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
1377 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001378
Chris Lattner43273af2011-02-13 08:07:21 +00001379 ICI.setOperand(0, Tmp);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001380
Chris Lattner43273af2011-02-13 08:07:21 +00001381 // If the builder folded the binop, just return it.
1382 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
Craig Topperf40110f2014-04-25 05:29:35 +00001383 if (!TheDiv)
Chris Lattner43273af2011-02-13 08:07:21 +00001384 return &ICI;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001385
Chris Lattner43273af2011-02-13 08:07:21 +00001386 // Otherwise, fold this div/compare.
1387 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1388 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001389
Sanjay Patel43395062016-07-21 18:07:40 +00001390 Instruction *Res = foldICmpDivConst(ICI, TheDiv, cast<ConstantInt>(DivCst));
Chris Lattner43273af2011-02-13 08:07:21 +00001391 assert(Res && "This div/cst should have folded!");
1392 return Res;
1393 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001394
Chris Lattnerd369f572011-02-13 07:43:07 +00001395 // If we are comparing against bits always shifted out, the
1396 // comparison cannot succeed.
1397 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszakbddea112013-06-06 20:18:46 +00001398 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattnerd369f572011-02-13 07:43:07 +00001399 if (Shr->getOpcode() == Instruction::LShr)
1400 Comp = Comp.lshr(ShAmtVal);
1401 else
1402 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001403
Chris Lattnerd369f572011-02-13 07:43:07 +00001404 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1405 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001406 Constant *Cst = Builder->getInt1(IsICMP_NE);
Sanjay Patel4b198802016-02-01 22:23:39 +00001407 return replaceInstUsesWith(ICI, Cst);
Chris Lattnerd369f572011-02-13 07:43:07 +00001408 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001409
Chris Lattnerd369f572011-02-13 07:43:07 +00001410 // Otherwise, check to see if the bits shifted out are known to be zero.
1411 // If so, we can compare against the unshifted value:
1412 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattner9bd7fdf2011-02-13 18:30:09 +00001413 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattnerd369f572011-02-13 07:43:07 +00001414 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001415
Chris Lattnerd369f572011-02-13 07:43:07 +00001416 if (Shr->hasOneUse()) {
1417 // Otherwise strength reduce the shift into an and.
1418 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszakbddea112013-06-06 20:18:46 +00001419 Constant *Mask = Builder->getInt(Val);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001420
Chris Lattnerd369f572011-02-13 07:43:07 +00001421 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1422 Mask, Shr->getName()+".mask");
1423 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1424 }
Craig Topperf40110f2014-04-25 05:29:35 +00001425 return nullptr;
Chris Lattnerd369f572011-02-13 07:43:07 +00001426}
1427
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001428/// Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001429/// (icmp eq/ne A, Log2(const2/const1)) ->
1430/// (icmp eq/ne A, Log2(const2) - Log2(const1)).
Sanjay Patel43395062016-07-21 18:07:40 +00001431Instruction *InstCombiner::foldICmpCstShrConst(ICmpInst &I, Value *Op, Value *A,
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001432 ConstantInt *CI1,
1433 ConstantInt *CI2) {
1434 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1435
1436 auto getConstant = [&I, this](bool IsTrue) {
1437 if (I.getPredicate() == I.ICMP_NE)
1438 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001439 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001440 };
1441
1442 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1443 if (I.getPredicate() == I.ICMP_NE)
1444 Pred = CmpInst::getInversePredicate(Pred);
1445 return new ICmpInst(Pred, LHS, RHS);
1446 };
1447
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001448 const APInt &AP1 = CI1->getValue();
1449 const APInt &AP2 = CI2->getValue();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001450
David Majnemer2abb8182014-10-25 07:13:13 +00001451 // Don't bother doing any work for cases which InstSimplify handles.
1452 if (AP2 == 0)
1453 return nullptr;
1454 bool IsAShr = isa<AShrOperator>(Op);
1455 if (IsAShr) {
1456 if (AP2.isAllOnesValue())
1457 return nullptr;
1458 if (AP2.isNegative() != AP1.isNegative())
1459 return nullptr;
1460 if (AP2.sgt(AP1))
1461 return nullptr;
1462 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001463
David Majnemerd2056022014-10-21 19:51:55 +00001464 if (!AP1)
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001465 // 'A' must be large enough to shift out the highest set bit.
1466 return getICmp(I.ICMP_UGT, A,
1467 ConstantInt::get(A->getType(), AP2.logBase2()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001468
David Majnemerd2056022014-10-21 19:51:55 +00001469 if (AP1 == AP2)
1470 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001471
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001472 int Shift;
David Majnemerd2056022014-10-21 19:51:55 +00001473 if (IsAShr && AP1.isNegative())
David Majnemere5977eb2015-09-19 00:48:26 +00001474 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001475 else
David Majnemere5977eb2015-09-19 00:48:26 +00001476 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001477
David Majnemerd2056022014-10-21 19:51:55 +00001478 if (Shift > 0) {
David Majnemere5977eb2015-09-19 00:48:26 +00001479 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1480 // There are multiple solutions if we are comparing against -1 and the LHS
David Majnemer47ce0b82015-09-19 00:48:31 +00001481 // of the ashr is not a power of two.
David Majnemere5977eb2015-09-19 00:48:26 +00001482 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1483 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
David Majnemerd2056022014-10-21 19:51:55 +00001484 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
David Majnemere5977eb2015-09-19 00:48:26 +00001485 } else if (AP1 == AP2.lshr(Shift)) {
1486 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1487 }
David Majnemerd2056022014-10-21 19:51:55 +00001488 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001489 // Shifting const2 will never be equal to const1.
1490 return getConstant(false);
1491}
Chris Lattner2188e402010-01-04 07:37:31 +00001492
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001493/// Handle "(icmp eq/ne (shl const2, A), const1)" ->
David Majnemer59939ac2014-10-19 08:23:08 +00001494/// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)).
Sanjay Patel43395062016-07-21 18:07:40 +00001495Instruction *InstCombiner::foldICmpCstShlConst(ICmpInst &I, Value *Op, Value *A,
1496 ConstantInt *CI1,
1497 ConstantInt *CI2) {
David Majnemer59939ac2014-10-19 08:23:08 +00001498 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1499
1500 auto getConstant = [&I, this](bool IsTrue) {
1501 if (I.getPredicate() == I.ICMP_NE)
1502 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001503 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
David Majnemer59939ac2014-10-19 08:23:08 +00001504 };
1505
1506 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1507 if (I.getPredicate() == I.ICMP_NE)
1508 Pred = CmpInst::getInversePredicate(Pred);
1509 return new ICmpInst(Pred, LHS, RHS);
1510 };
1511
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001512 const APInt &AP1 = CI1->getValue();
1513 const APInt &AP2 = CI2->getValue();
David Majnemer59939ac2014-10-19 08:23:08 +00001514
David Majnemer2abb8182014-10-25 07:13:13 +00001515 // Don't bother doing any work for cases which InstSimplify handles.
1516 if (AP2 == 0)
1517 return nullptr;
David Majnemer59939ac2014-10-19 08:23:08 +00001518
1519 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1520
1521 if (!AP1 && AP2TrailingZeros != 0)
1522 return getICmp(I.ICMP_UGE, A,
1523 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1524
1525 if (AP1 == AP2)
1526 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1527
1528 // Get the distance between the lowest bits that are set.
1529 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1530
1531 if (Shift > 0 && AP2.shl(Shift) == AP1)
1532 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1533
1534 // Shifting const2 will never be equal to const1.
1535 return getConstant(false);
1536}
1537
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001538/// Handle "icmp (instr, intcst)".
Sanjay Patel43395062016-07-21 18:07:40 +00001539Instruction *InstCombiner::foldICmpWithConstant(ICmpInst &ICI,
1540 Instruction *LHSI,
1541 ConstantInt *RHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001542 const APInt &RHSV = RHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001543
Chris Lattner2188e402010-01-04 07:37:31 +00001544 switch (LHSI->getOpcode()) {
1545 case Instruction::Trunc:
Sanjoy Dase5f48892015-09-16 20:41:29 +00001546 if (RHS->isOne() && RHSV.getBitWidth() > 1) {
1547 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1548 Value *V = nullptr;
1549 if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1550 match(LHSI->getOperand(0), m_Signum(m_Value(V))))
1551 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1552 ConstantInt::get(V->getType(), 1));
1553 }
Chris Lattner2188e402010-01-04 07:37:31 +00001554 if (ICI.isEquality() && LHSI->hasOneUse()) {
1555 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1556 // of the high bits truncated out of x are known.
1557 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1558 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner2188e402010-01-04 07:37:31 +00001559 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001560 computeKnownBits(LHSI->getOperand(0), KnownZero, KnownOne, 0, &ICI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001561
Chris Lattner2188e402010-01-04 07:37:31 +00001562 // If all the high bits are known, we can do this xform.
1563 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1564 // Pull in the high bits from known-ones set.
Jay Foad583abbc2010-12-07 08:25:19 +00001565 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedmane0a64d82012-05-11 01:32:59 +00001566 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner2188e402010-01-04 07:37:31 +00001567 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001568 Builder->getInt(NewRHS));
Chris Lattner2188e402010-01-04 07:37:31 +00001569 }
1570 }
1571 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001572
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001573 case Instruction::Xor: // (icmp pred (xor X, XorCst), CI)
1574 if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001575 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1576 // fold the xor.
1577 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1578 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1579 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001580
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001581 // If the sign bit of the XorCst is not set, there is no change to
Chris Lattner2188e402010-01-04 07:37:31 +00001582 // the operation, just stop using the Xor.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001583 if (!XorCst->isNegative()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001584 ICI.setOperand(0, CompareVal);
1585 Worklist.Add(LHSI);
1586 return &ICI;
1587 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001588
Chris Lattner2188e402010-01-04 07:37:31 +00001589 // Was the old condition true if the operand is positive?
1590 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001591
Chris Lattner2188e402010-01-04 07:37:31 +00001592 // If so, the new one isn't.
1593 isTrueIfPositive ^= true;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001594
Chris Lattner2188e402010-01-04 07:37:31 +00001595 if (isTrueIfPositive)
1596 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1597 SubOne(RHS));
1598 else
1599 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1600 AddOne(RHS));
1601 }
1602
1603 if (LHSI->hasOneUse()) {
1604 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001605 if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1606 const APInt &SignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001607 ICmpInst::Predicate Pred = ICI.isSigned()
1608 ? ICI.getUnsignedPredicate()
1609 : ICI.getSignedPredicate();
1610 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001611 Builder->getInt(RHSV ^ SignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001612 }
1613
1614 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001615 if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1616 const APInt &NotSignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001617 ICmpInst::Predicate Pred = ICI.isSigned()
1618 ? ICI.getUnsignedPredicate()
1619 : ICI.getSignedPredicate();
1620 Pred = ICI.getSwappedPredicate(Pred);
1621 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001622 Builder->getInt(RHSV ^ NotSignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001623 }
1624 }
David Majnemer72d76272013-07-09 09:20:58 +00001625
1626 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1627 // iff -C is a power of 2
1628 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001629 XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1630 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
David Majnemer72d76272013-07-09 09:20:58 +00001631
1632 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1633 // iff -C is a power of 2
1634 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001635 XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1636 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001637 }
1638 break;
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001639 case Instruction::And: // (icmp pred (and X, AndCst), RHS)
Chris Lattner2188e402010-01-04 07:37:31 +00001640 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1641 LHSI->getOperand(0)->hasOneUse()) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001642 ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001643
Chris Lattner2188e402010-01-04 07:37:31 +00001644 // If the LHS is an AND of a truncating cast, we can widen the
1645 // and/compare to be the input width without changing the value
1646 // produced, eliminating a cast.
1647 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1648 // We can do this transformation if either the AND constant does not
Jim Grosbach129c52a2011-09-30 18:09:53 +00001649 // have its sign bit set or if it is an equality comparison.
Chris Lattner2188e402010-01-04 07:37:31 +00001650 // Extending a relational comparison when we're checking the sign
1651 // bit would not work.
Benjamin Kramer35159c12011-06-12 22:47:53 +00001652 if (ICI.isEquality() ||
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001653 (!AndCst->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer35159c12011-06-12 22:47:53 +00001654 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001655 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001656 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
Benjamin Kramer35159c12011-06-12 22:47:53 +00001657 NewAnd->takeName(LHSI);
Chris Lattner2188e402010-01-04 07:37:31 +00001658 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer35159c12011-06-12 22:47:53 +00001659 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner2188e402010-01-04 07:37:31 +00001660 }
1661 }
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001662
1663 // If the LHS is an AND of a zext, and we have an equality compare, we can
1664 // shrink the and/compare to the smaller type, eliminating the cast.
1665 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattner229907c2011-07-18 04:54:35 +00001666 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001667 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1668 // should fold the icmp to true/false in that case.
1669 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1670 Value *NewAnd =
1671 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001672 ConstantExpr::getTrunc(AndCst, Ty));
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001673 NewAnd->takeName(LHSI);
1674 return new ICmpInst(ICI.getPredicate(), NewAnd,
1675 ConstantExpr::getTrunc(RHS, Ty));
1676 }
1677 }
1678
Chris Lattner2188e402010-01-04 07:37:31 +00001679 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1680 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1681 // happens a LOT in code produced by the C front-end, for bitfield
1682 // access.
1683 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1684 if (Shift && !Shift->isShift())
Craig Topperf40110f2014-04-25 05:29:35 +00001685 Shift = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001686
Chris Lattner2188e402010-01-04 07:37:31 +00001687 ConstantInt *ShAmt;
Craig Topperf40110f2014-04-25 05:29:35 +00001688 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001689
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001690 // This seemingly simple opportunity to fold away a shift turns out to
1691 // be rather complicated. See PR17827
1692 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
Chris Lattner2188e402010-01-04 07:37:31 +00001693 if (ShAmt) {
Kay Tiong Khoo5389f742013-12-02 18:43:59 +00001694 bool CanFold = false;
1695 unsigned ShiftOpcode = Shift->getOpcode();
1696 if (ShiftOpcode == Instruction::AShr) {
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001697 // There may be some constraints that make this possible,
1698 // but nothing simple has been discovered yet.
1699 CanFold = false;
1700 } else if (ShiftOpcode == Instruction::Shl) {
1701 // For a left shift, we can fold if the comparison is not signed.
1702 // We can also fold a signed comparison if the mask value and
1703 // comparison value are not negative. These constraints may not be
1704 // obvious, but we can prove that they are correct using an SMT
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001705 // solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001706 if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
Chris Lattner2188e402010-01-04 07:37:31 +00001707 CanFold = true;
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001708 } else if (ShiftOpcode == Instruction::LShr) {
1709 // For a logical right shift, we can fold if the comparison is not
1710 // signed. We can also fold a signed comparison if the shifted mask
1711 // value and the shifted comparison value are not negative.
1712 // These constraints may not be obvious, but we can prove that they
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001713 // are correct using an SMT solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001714 if (!ICI.isSigned())
1715 CanFold = true;
1716 else {
1717 ConstantInt *ShiftedAndCst =
1718 cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1719 ConstantInt *ShiftedRHSCst =
1720 cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1721
1722 if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1723 CanFold = true;
1724 }
Chris Lattner2188e402010-01-04 07:37:31 +00001725 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001726
Chris Lattner2188e402010-01-04 07:37:31 +00001727 if (CanFold) {
1728 Constant *NewCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001729 if (ShiftOpcode == Instruction::Shl)
Chris Lattner2188e402010-01-04 07:37:31 +00001730 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1731 else
1732 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001733
Chris Lattner2188e402010-01-04 07:37:31 +00001734 // Check to see if we are shifting out any of the bits being
1735 // compared.
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001736 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001737 // If we shifted bits out, the fold is not going to work out.
1738 // As a special case, check to see if this means that the
1739 // result is always true or false now.
1740 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00001741 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001742 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Sanjay Patel4b198802016-02-01 22:23:39 +00001743 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001744 } else {
1745 ICI.setOperand(1, NewCst);
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001746 Constant *NewAndCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001747 if (ShiftOpcode == Instruction::Shl)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001748 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
Chris Lattner2188e402010-01-04 07:37:31 +00001749 else
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001750 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1751 LHSI->setOperand(1, NewAndCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001752 LHSI->setOperand(0, Shift->getOperand(0));
1753 Worklist.Add(Shift); // Shift is dead.
1754 return &ICI;
1755 }
1756 }
1757 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001758
Chris Lattner2188e402010-01-04 07:37:31 +00001759 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1760 // preferable because it allows the C<<Y expression to be hoisted out
1761 // of a loop if Y is invariant and X is not.
1762 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1763 ICI.isEquality() && !Shift->isArithmeticShift() &&
1764 !isa<Constant>(Shift->getOperand(0))) {
1765 // Compute C << Y.
1766 Value *NS;
1767 if (Shift->getOpcode() == Instruction::LShr) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001768 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001769 } else {
1770 // Insert a logical shift.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001771 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001772 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001773
Chris Lattner2188e402010-01-04 07:37:31 +00001774 // Compute X & (C << Y).
Jim Grosbach129c52a2011-09-30 18:09:53 +00001775 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001776 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001777
Chris Lattner2188e402010-01-04 07:37:31 +00001778 ICI.setOperand(0, NewAnd);
1779 return &ICI;
1780 }
Paul Redmond5917f4c2012-12-19 19:47:13 +00001781
David Majnemer0ffccf72014-08-24 09:10:57 +00001782 // (icmp pred (and (or (lshr X, Y), X), 1), 0) -->
1783 // (icmp pred (and X, (or (shl 1, Y), 1), 0))
1784 //
1785 // iff pred isn't signed
1786 {
1787 Value *X, *Y, *LShr;
1788 if (!ICI.isSigned() && RHSV == 0) {
1789 if (match(LHSI->getOperand(1), m_One())) {
1790 Constant *One = cast<Constant>(LHSI->getOperand(1));
1791 Value *Or = LHSI->getOperand(0);
1792 if (match(Or, m_Or(m_Value(LShr), m_Value(X))) &&
1793 match(LShr, m_LShr(m_Specific(X), m_Value(Y)))) {
1794 unsigned UsesRemoved = 0;
1795 if (LHSI->hasOneUse())
1796 ++UsesRemoved;
1797 if (Or->hasOneUse())
1798 ++UsesRemoved;
1799 if (LShr->hasOneUse())
1800 ++UsesRemoved;
1801 Value *NewOr = nullptr;
1802 // Compute X & ((1 << Y) | 1)
1803 if (auto *C = dyn_cast<Constant>(Y)) {
1804 if (UsesRemoved >= 1)
1805 NewOr =
1806 ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1807 } else {
1808 if (UsesRemoved >= 3)
1809 NewOr = Builder->CreateOr(Builder->CreateShl(One, Y,
1810 LShr->getName(),
1811 /*HasNUW=*/true),
1812 One, Or->getName());
1813 }
1814 if (NewOr) {
1815 Value *NewAnd = Builder->CreateAnd(X, NewOr, LHSI->getName());
1816 ICI.setOperand(0, NewAnd);
1817 return &ICI;
1818 }
1819 }
1820 }
1821 }
1822 }
1823
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001824 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1825 // bit set in (X & AndCst) will produce a result greater than RHSV.
Paul Redmond5917f4c2012-12-19 19:47:13 +00001826 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001827 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1828 if ((NTZ < AndCst->getBitWidth()) &&
1829 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
Paul Redmond5917f4c2012-12-19 19:47:13 +00001830 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1831 Constant::getNullValue(RHS->getType()));
1832 }
Chris Lattner2188e402010-01-04 07:37:31 +00001833 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001834
Chris Lattner2188e402010-01-04 07:37:31 +00001835 // Try to optimize things like "A[i]&42 == 0" to index computations.
1836 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1837 if (GetElementPtrInst *GEP =
1838 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1839 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1840 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1841 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1842 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
Sanjay Patel43395062016-07-21 18:07:40 +00001843 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
Chris Lattner2188e402010-01-04 07:37:31 +00001844 return Res;
1845 }
1846 }
David Majnemer414d4e52013-07-09 08:09:32 +00001847
1848 // X & -C == -C -> X > u ~C
1849 // X & -C != -C -> X <= u ~C
1850 // iff C is a power of 2
1851 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1852 return new ICmpInst(
1853 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1854 : ICmpInst::ICMP_ULE,
1855 LHSI->getOperand(0), SubOne(RHS));
David Majnemerdfa3b092015-08-16 07:09:17 +00001856
1857 // (icmp eq (and %A, C), 0) -> (icmp sgt (trunc %A), -1)
1858 // iff C is a power of 2
1859 if (ICI.isEquality() && LHSI->hasOneUse() && match(RHS, m_Zero())) {
1860 if (auto *CI = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1861 const APInt &AI = CI->getValue();
1862 int32_t ExactLogBase2 = AI.exactLogBase2();
1863 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1864 Type *NTy = IntegerType::get(ICI.getContext(), ExactLogBase2 + 1);
1865 Value *Trunc = Builder->CreateTrunc(LHSI->getOperand(0), NTy);
1866 return new ICmpInst(ICI.getPredicate() == ICmpInst::ICMP_EQ
1867 ? ICmpInst::ICMP_SGE
1868 : ICmpInst::ICMP_SLT,
1869 Trunc, Constant::getNullValue(NTy));
1870 }
1871 }
1872 }
Chris Lattner2188e402010-01-04 07:37:31 +00001873 break;
1874
1875 case Instruction::Or: {
Sanjoy Dase5f48892015-09-16 20:41:29 +00001876 if (RHS->isOne()) {
1877 // icmp slt signum(V) 1 --> icmp slt V, 1
1878 Value *V = nullptr;
1879 if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1880 match(LHSI, m_Signum(m_Value(V))))
1881 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1882 ConstantInt::get(V->getType(), 1));
1883 }
1884
Chris Lattner2188e402010-01-04 07:37:31 +00001885 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1886 break;
1887 Value *P, *Q;
1888 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1889 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1890 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner2188e402010-01-04 07:37:31 +00001891 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1892 Constant::getNullValue(P->getType()));
1893 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1894 Constant::getNullValue(Q->getType()));
1895 Instruction *Op;
1896 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1897 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1898 else
1899 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1900 return Op;
1901 }
1902 break;
1903 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001904
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001905 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1906 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1907 if (!Val) break;
1908
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001909 // If this is a signed comparison to 0 and the mul is sign preserving,
1910 // use the mul LHS operand instead.
1911 ICmpInst::Predicate pred = ICI.getPredicate();
1912 if (isSignTest(pred, RHS) && !Val->isZero() &&
1913 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1914 return new ICmpInst(Val->isNegative() ?
1915 ICmpInst::getSwappedPredicate(pred) : pred,
1916 LHSI->getOperand(0),
1917 Constant::getNullValue(RHS->getType()));
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001918
1919 break;
1920 }
1921
Chris Lattner2188e402010-01-04 07:37:31 +00001922 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
Chris Lattner2188e402010-01-04 07:37:31 +00001923 uint32_t TypeBits = RHSV.getBitWidth();
David Majnemerb889e402013-06-28 23:42:03 +00001924 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1925 if (!ShAmt) {
1926 Value *X;
1927 // (1 << X) pred P2 -> X pred Log2(P2)
1928 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1929 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1930 ICmpInst::Predicate Pred = ICI.getPredicate();
1931 if (ICI.isUnsigned()) {
1932 if (!RHSVIsPowerOf2) {
1933 // (1 << X) < 30 -> X <= 4
1934 // (1 << X) <= 30 -> X <= 4
1935 // (1 << X) >= 30 -> X > 4
1936 // (1 << X) > 30 -> X > 4
1937 if (Pred == ICmpInst::ICMP_ULT)
1938 Pred = ICmpInst::ICMP_ULE;
1939 else if (Pred == ICmpInst::ICMP_UGE)
1940 Pred = ICmpInst::ICMP_UGT;
1941 }
1942 unsigned RHSLog2 = RHSV.logBase2();
1943
1944 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
David Majnemerb889e402013-06-28 23:42:03 +00001945 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1946 if (RHSLog2 == TypeBits-1) {
1947 if (Pred == ICmpInst::ICMP_UGE)
1948 Pred = ICmpInst::ICMP_EQ;
David Majnemerb889e402013-06-28 23:42:03 +00001949 else if (Pred == ICmpInst::ICMP_ULT)
1950 Pred = ICmpInst::ICMP_NE;
1951 }
1952
1953 return new ICmpInst(Pred, X,
1954 ConstantInt::get(RHS->getType(), RHSLog2));
1955 } else if (ICI.isSigned()) {
1956 if (RHSV.isAllOnesValue()) {
1957 // (1 << X) <= -1 -> X == 31
1958 if (Pred == ICmpInst::ICMP_SLE)
1959 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1960 ConstantInt::get(RHS->getType(), TypeBits-1));
1961
1962 // (1 << X) > -1 -> X != 31
1963 if (Pred == ICmpInst::ICMP_SGT)
1964 return new ICmpInst(ICmpInst::ICMP_NE, X,
1965 ConstantInt::get(RHS->getType(), TypeBits-1));
1966 } else if (!RHSV) {
1967 // (1 << X) < 0 -> X == 31
1968 // (1 << X) <= 0 -> X == 31
1969 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1970 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1971 ConstantInt::get(RHS->getType(), TypeBits-1));
1972
1973 // (1 << X) >= 0 -> X != 31
1974 // (1 << X) > 0 -> X != 31
1975 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1976 return new ICmpInst(ICmpInst::ICMP_NE, X,
1977 ConstantInt::get(RHS->getType(), TypeBits-1));
1978 }
1979 } else if (ICI.isEquality()) {
1980 if (RHSVIsPowerOf2)
1981 return new ICmpInst(
1982 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
David Majnemerb889e402013-06-28 23:42:03 +00001983 }
1984 }
1985 break;
1986 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001987
Chris Lattner2188e402010-01-04 07:37:31 +00001988 // Check that the shift amount is in range. If not, don't perform
1989 // undefined shifts. When the shift is visited it will be
1990 // simplified.
1991 if (ShAmt->uge(TypeBits))
1992 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001993
Chris Lattner2188e402010-01-04 07:37:31 +00001994 if (ICI.isEquality()) {
1995 // If we are comparing against bits always shifted out, the
1996 // comparison cannot succeed.
1997 Constant *Comp =
1998 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1999 ShAmt);
2000 if (Comp != RHS) {// Comparing against a bit that we know is zero.
2001 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00002002 Constant *Cst = Builder->getInt1(IsICMP_NE);
Sanjay Patel4b198802016-02-01 22:23:39 +00002003 return replaceInstUsesWith(ICI, Cst);
Chris Lattner2188e402010-01-04 07:37:31 +00002004 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002005
Chris Lattner98457102011-02-10 05:23:05 +00002006 // If the shift is NUW, then it is just shifting out zeros, no need for an
2007 // AND.
2008 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
2009 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2010 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002011
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002012 // If the shift is NSW and we compare to 0, then it is just shifting out
2013 // sign bits, no need for an AND either.
2014 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
2015 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2016 ConstantExpr::getLShr(RHS, ShAmt));
2017
Chris Lattner2188e402010-01-04 07:37:31 +00002018 if (LHSI->hasOneUse()) {
2019 // Otherwise strength reduce the shift into an and.
2020 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Jakub Staszakbddea112013-06-06 20:18:46 +00002021 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
2022 TypeBits - ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002023
Chris Lattner2188e402010-01-04 07:37:31 +00002024 Value *And =
2025 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
2026 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner98457102011-02-10 05:23:05 +00002027 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner2188e402010-01-04 07:37:31 +00002028 }
2029 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002030
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002031 // If this is a signed comparison to 0 and the shift is sign preserving,
2032 // use the shift LHS operand instead.
2033 ICmpInst::Predicate pred = ICI.getPredicate();
2034 if (isSignTest(pred, RHS) &&
2035 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
2036 return new ICmpInst(pred,
2037 LHSI->getOperand(0),
2038 Constant::getNullValue(RHS->getType()));
2039
Chris Lattner2188e402010-01-04 07:37:31 +00002040 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2041 bool TrueIfSigned = false;
2042 if (LHSI->hasOneUse() &&
2043 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
2044 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattner43273af2011-02-13 08:07:21 +00002045 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach129c52a2011-09-30 18:09:53 +00002046 APInt::getOneBitSet(TypeBits,
Chris Lattner43273af2011-02-13 08:07:21 +00002047 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002048 Value *And =
2049 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
2050 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2051 And, Constant::getNullValue(And->getType()));
2052 }
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002053
2054 // Transform (icmp pred iM (shl iM %v, N), CI)
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00002055 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
2056 // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002057 // This enables to get rid of the shift in favor of a trunc which can be
2058 // free on the target. It has the additional benefit of comparing to a
2059 // smaller constant, which will be target friendly.
2060 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00002061 if (LHSI->hasOneUse() &&
2062 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002063 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
2064 Constant *NCI = ConstantExpr::getTrunc(
2065 ConstantExpr::getAShr(RHS,
2066 ConstantInt::get(RHS->getType(), Amt)),
2067 NTy);
2068 return new ICmpInst(ICI.getPredicate(),
2069 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaison1fd843e2013-02-15 15:18:17 +00002070 NCI);
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002071 }
2072
Chris Lattner2188e402010-01-04 07:37:31 +00002073 break;
2074 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002075
Chris Lattner2188e402010-01-04 07:37:31 +00002076 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewycky174a7052011-02-28 08:31:40 +00002077 case Instruction::AShr: {
2078 // Handle equality comparisons of shift-by-constant.
2079 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
2080 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Sanjay Patel43395062016-07-21 18:07:40 +00002081 if (Instruction *Res = foldICmpShrConst(ICI, BO, ShAmt))
Chris Lattnerd369f572011-02-13 07:43:07 +00002082 return Res;
Nick Lewycky174a7052011-02-28 08:31:40 +00002083 }
2084
2085 // Handle exact shr's.
2086 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
2087 if (RHSV.isMinValue())
2088 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
2089 }
Chris Lattner2188e402010-01-04 07:37:31 +00002090 break;
Nick Lewycky174a7052011-02-28 08:31:40 +00002091 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002092
Chris Lattner2188e402010-01-04 07:37:31 +00002093 case Instruction::UDiv:
Chad Rosier4e6cda22016-05-10 20:22:09 +00002094 if (ConstantInt *DivLHS = dyn_cast<ConstantInt>(LHSI->getOperand(0))) {
2095 Value *X = LHSI->getOperand(1);
Benjamin Kramer46e38f32016-06-08 10:01:20 +00002096 const APInt &C1 = RHS->getValue();
2097 const APInt &C2 = DivLHS->getValue();
Chad Rosier4e6cda22016-05-10 20:22:09 +00002098 assert(C2 != 0 && "udiv 0, X should have been simplified already.");
2099 // (icmp ugt (udiv C2, X), C1) -> (icmp ule X, C2/(C1+1))
2100 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
2101 assert(!C1.isMaxValue() &&
2102 "icmp ugt X, UINT_MAX should have been simplified already.");
2103 return new ICmpInst(ICmpInst::ICMP_ULE, X,
2104 ConstantInt::get(X->getType(), C2.udiv(C1 + 1)));
2105 }
2106 // (icmp ult (udiv C2, X), C1) -> (icmp ugt X, C2/C1)
2107 if (ICI.getPredicate() == ICmpInst::ICMP_ULT) {
2108 assert(C1 != 0 && "icmp ult X, 0 should have been simplified already.");
2109 return new ICmpInst(ICmpInst::ICMP_UGT, X,
2110 ConstantInt::get(X->getType(), C2.udiv(C1)));
2111 }
2112 }
2113 // fall-through
2114 case Instruction::SDiv:
Chris Lattner2188e402010-01-04 07:37:31 +00002115 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach129c52a2011-09-30 18:09:53 +00002116 // Fold this div into the comparison, producing a range check.
2117 // Determine, based on the divide type, what the range is being
2118 // checked. If there is an overflow on the low or high side, remember
Chris Lattner2188e402010-01-04 07:37:31 +00002119 // it, otherwise compute the range [low, hi) bounding the new value.
2120 // See: InsertRangeTest above for the kinds of replacements possible.
2121 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
Sanjay Patel43395062016-07-21 18:07:40 +00002122 if (Instruction *R = foldICmpDivConst(ICI, cast<BinaryOperator>(LHSI),
Chris Lattner2188e402010-01-04 07:37:31 +00002123 DivRHS))
2124 return R;
2125 break;
2126
David Majnemerf2a9a512013-07-09 07:50:59 +00002127 case Instruction::Sub: {
2128 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
2129 if (!LHSC) break;
2130 const APInt &LHSV = LHSC->getValue();
2131
2132 // C1-X <u C2 -> (X|(C2-1)) == C1
2133 // iff C1 & (C2-1) == C2-1
2134 // C2 is a power of 2
2135 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
2136 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
2137 return new ICmpInst(ICmpInst::ICMP_EQ,
2138 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
2139 LHSC);
2140
David Majnemereeed73b2013-07-09 09:24:35 +00002141 // C1-X >u C2 -> (X|C2) != C1
David Majnemerf2a9a512013-07-09 07:50:59 +00002142 // iff C1 & C2 == C2
2143 // C2+1 is a power of 2
2144 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
2145 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
2146 return new ICmpInst(ICmpInst::ICMP_NE,
2147 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
2148 break;
2149 }
2150
Chris Lattner2188e402010-01-04 07:37:31 +00002151 case Instruction::Add:
2152 // Fold: icmp pred (add X, C1), C2
2153 if (!ICI.isEquality()) {
2154 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
2155 if (!LHSC) break;
2156 const APInt &LHSV = LHSC->getValue();
2157
2158 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
2159 .subtract(LHSV);
2160
2161 if (ICI.isSigned()) {
2162 if (CR.getLower().isSignBit()) {
2163 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002164 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00002165 } else if (CR.getUpper().isSignBit()) {
2166 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002167 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00002168 }
2169 } else {
2170 if (CR.getLower().isMinValue()) {
2171 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002172 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00002173 } else if (CR.getUpper().isMinValue()) {
2174 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002175 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00002176 }
2177 }
David Majnemerfa90a0b2013-07-08 11:53:08 +00002178
David Majnemerbafa5372013-07-09 07:58:32 +00002179 // X-C1 <u C2 -> (X & -C2) == C1
2180 // iff C1 & (C2-1) == 0
2181 // C2 is a power of 2
David Majnemerfa90a0b2013-07-08 11:53:08 +00002182 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
David Majnemerbafa5372013-07-09 07:58:32 +00002183 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
David Majnemerfa90a0b2013-07-08 11:53:08 +00002184 return new ICmpInst(ICmpInst::ICMP_EQ,
2185 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
2186 ConstantExpr::getNeg(LHSC));
David Majnemerbafa5372013-07-09 07:58:32 +00002187
David Majnemereeed73b2013-07-09 09:24:35 +00002188 // X-C1 >u C2 -> (X & ~C2) != C1
David Majnemerbafa5372013-07-09 07:58:32 +00002189 // iff C1 & C2 == 0
2190 // C2+1 is a power of 2
2191 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
2192 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
2193 return new ICmpInst(ICmpInst::ICMP_NE,
2194 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
2195 ConstantExpr::getNeg(LHSC));
Chris Lattner2188e402010-01-04 07:37:31 +00002196 }
2197 break;
2198 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002199
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002200 return nullptr;
2201}
Jim Grosbach129c52a2011-09-30 18:09:53 +00002202
Sanjay Patelab50a932016-08-02 22:38:33 +00002203/// Simplify icmp_eq and icmp_ne instructions with binary operator LHS and
2204/// integer constant RHS.
2205Instruction *InstCombiner::foldICmpEqualityWithConstant(ICmpInst &ICI) {
Sanjay Patelab50a932016-08-02 22:38:33 +00002206 BinaryOperator *BO;
Sanjay Patel43aeb002016-08-03 18:59:03 +00002207 const APInt *RHSV;
2208 // FIXME: Some of these folds could work with arbitrary constants, but this
2209 // match is limited to scalars and vector splat constants.
Sanjay Patelab50a932016-08-02 22:38:33 +00002210 if (!ICI.isEquality() || !match(ICI.getOperand(0), m_BinOp(BO)) ||
Sanjay Patel43aeb002016-08-03 18:59:03 +00002211 !match(ICI.getOperand(1), m_APInt(RHSV)))
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002212 return nullptr;
2213
Sanjay Patel43aeb002016-08-03 18:59:03 +00002214 Constant *RHS = cast<Constant>(ICI.getOperand(1));
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002215 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002216 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002217
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002218 switch (BO->getOpcode()) {
2219 case Instruction::SRem:
2220 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Sanjay Patel2e9675f2016-08-03 19:48:40 +00002221 if (*RHSV == 0 && BO->hasOneUse()) {
2222 const APInt *BOC;
2223 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002224 Value *NewRem = Builder->CreateURem(BOp0, BOp1, BO->getName());
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002225 return new ICmpInst(ICI.getPredicate(), NewRem,
2226 Constant::getNullValue(BO->getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002227 }
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002228 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002229 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002230 case Instruction::Add: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002231 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
Sanjay Patel00a324e2016-08-03 22:08:44 +00002232 const APInt *BOC;
2233 if (match(BOp1, m_APInt(BOC))) {
2234 if (BO->hasOneUse()) {
2235 Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1));
2236 return new ICmpInst(ICI.getPredicate(), BOp0, SubC);
2237 }
Sanjay Patel43aeb002016-08-03 18:59:03 +00002238 } else if (*RHSV == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002239 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2240 // efficiently invertible, or if the add has just this one use.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002241 if (Value *NegVal = dyn_castNegVal(BOp1))
2242 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
2243 if (Value *NegVal = dyn_castNegVal(BOp0))
2244 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
2245 if (BO->hasOneUse()) {
2246 Value *Neg = Builder->CreateNeg(BOp1);
2247 Neg->takeName(BO);
2248 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
2249 }
2250 }
2251 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002252 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002253 case Instruction::Xor:
2254 if (BO->hasOneUse()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002255 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002256 // For the xor case, we can xor two constants together, eliminating
2257 // the explicit xor.
Sanjay Patel51a767c2016-08-03 17:23:08 +00002258 return new ICmpInst(ICI.getPredicate(), BOp0,
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002259 ConstantExpr::getXor(RHS, BOC));
Sanjay Patel43aeb002016-08-03 18:59:03 +00002260 } else if (*RHSV == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002261 // Replace ((xor A, B) != 0) with (A != B)
Sanjay Patel51a767c2016-08-03 17:23:08 +00002262 return new ICmpInst(ICI.getPredicate(), BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002263 }
2264 }
2265 break;
2266 case Instruction::Sub:
2267 if (BO->hasOneUse()) {
Sanjay Patel43aeb002016-08-03 18:59:03 +00002268 // FIXME: Vectors are excluded by ConstantInt.
Sanjay Patel51a767c2016-08-03 17:23:08 +00002269 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BOp0)) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002270 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
Sanjay Patel51a767c2016-08-03 17:23:08 +00002271 return new ICmpInst(ICI.getPredicate(), BOp1,
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002272 ConstantExpr::getSub(BOp0C, RHS));
Sanjay Patel43aeb002016-08-03 18:59:03 +00002273 } else if (*RHSV == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002274 // Replace ((sub A, B) != 0) with (A != B)
Sanjay Patel51a767c2016-08-03 17:23:08 +00002275 return new ICmpInst(ICI.getPredicate(), BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002276 }
2277 }
2278 break;
2279 case Instruction::Or:
2280 // If bits are being or'd in that are not present in the constant we
2281 // are comparing against, then the comparison could never succeed!
Sanjay Patel43aeb002016-08-03 18:59:03 +00002282 // FIXME: Vectors are excluded by ConstantInt.
Sanjay Patel51a767c2016-08-03 17:23:08 +00002283 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BOp1)) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002284 Constant *NotCI = ConstantExpr::getNot(RHS);
2285 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
2286 return replaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
2287
2288 // Comparing if all bits outside of a constant mask are set?
2289 // Replace (X | C) == -1 with (X & ~C) == ~C.
2290 // This removes the -1 constant.
2291 if (BO->hasOneUse() && RHS->isAllOnesValue()) {
2292 Constant *NotBOC = ConstantExpr::getNot(BOC);
Sanjay Patel51a767c2016-08-03 17:23:08 +00002293 Value *And = Builder->CreateAnd(BOp0, NotBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002294 return new ICmpInst(ICI.getPredicate(), And, NotBOC);
2295 }
2296 }
2297 break;
2298
2299 case Instruction::And:
Sanjay Patel43aeb002016-08-03 18:59:03 +00002300 // FIXME: Vectors are excluded by ConstantInt.
Sanjay Patel51a767c2016-08-03 17:23:08 +00002301 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BOp1)) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002302 // If bits are being compared against that are and'd out, then the
2303 // comparison can never succeed!
Sanjay Patel43aeb002016-08-03 18:59:03 +00002304 if ((*RHSV & ~BOC->getValue()) != 0)
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002305 return replaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
2306
2307 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Sanjay Patel43aeb002016-08-03 18:59:03 +00002308 if (RHS == BOC && RHSV->isPowerOf2())
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002309 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
Sanjay Patelab50a932016-08-02 22:38:33 +00002310 BO, Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002311
2312 // Don't perform the following transforms if the AND has multiple uses
2313 if (!BO->hasOneUse())
2314 break;
2315
2316 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
2317 if (BOC->getValue().isSignBit()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002318 Constant *Zero = Constant::getNullValue(BOp0->getType());
2319 ICmpInst::Predicate Pred =
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002320 isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002321 return new ICmpInst(Pred, BOp0, Zero);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002322 }
2323
2324 // ((X & ~7) == 0) --> X < 8
Sanjay Patel43aeb002016-08-03 18:59:03 +00002325 if (*RHSV == 0 && isHighOnes(BOC)) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002326 Constant *NegX = ConstantExpr::getNeg(BOC);
Sanjay Patel51a767c2016-08-03 17:23:08 +00002327 ICmpInst::Predicate Pred =
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002328 isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002329 return new ICmpInst(Pred, BOp0, NegX);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002330 }
2331 }
2332 break;
2333 case Instruction::Mul:
Sanjay Patel43aeb002016-08-03 18:59:03 +00002334 if (*RHSV == 0 && BO->hasNoSignedWrap()) {
2335 // FIXME: Vectors are excluded by ConstantInt.
Sanjay Patel51a767c2016-08-03 17:23:08 +00002336 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BOp1)) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002337 // The trivial case (mul X, 0) is handled by InstSimplify
2338 // General case : (mul X, C) != 0 iff X != 0
2339 // (mul X, C) == 0 iff X == 0
2340 if (!BOC->isZero())
Sanjay Patel51a767c2016-08-03 17:23:08 +00002341 return new ICmpInst(ICI.getPredicate(), BOp0,
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002342 Constant::getNullValue(RHS->getType()));
2343 }
2344 }
2345 break;
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002346 case Instruction::UDiv:
Sanjay Patel43aeb002016-08-03 18:59:03 +00002347 if (*RHSV == 0) {
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002348 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
2349 ICmpInst::Predicate Pred =
2350 isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002351 return new ICmpInst(Pred, BOp1, BOp0);
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002352 }
2353 break;
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002354 default:
2355 break;
2356 }
2357 return nullptr;
2358}
2359
Sanjay Patel1271bf92016-07-23 13:06:49 +00002360Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &ICI) {
2361 IntrinsicInst *II = dyn_cast<IntrinsicInst>(ICI.getOperand(0));
2362 const APInt *Op1C;
2363 if (!II || !ICI.isEquality() || !match(ICI.getOperand(1), m_APInt(Op1C)))
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002364 return nullptr;
2365
2366 // Handle icmp {eq|ne} <intrinsic>, intcst.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002367 switch (II->getIntrinsicID()) {
2368 case Intrinsic::bswap:
2369 Worklist.Add(II);
2370 ICI.setOperand(0, II->getArgOperand(0));
Sanjay Patel1271bf92016-07-23 13:06:49 +00002371 ICI.setOperand(1, Builder->getInt(Op1C->byteSwap()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002372 return &ICI;
2373 case Intrinsic::ctlz:
2374 case Intrinsic::cttz:
Amaury Sechet6bea6742016-08-04 05:27:20 +00002375 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
Sanjay Patel1271bf92016-07-23 13:06:49 +00002376 if (*Op1C == Op1C->getBitWidth()) {
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002377 Worklist.Add(II);
2378 ICI.setOperand(0, II->getArgOperand(0));
Sanjay Patel1271bf92016-07-23 13:06:49 +00002379 ICI.setOperand(1, ConstantInt::getNullValue(II->getType()));
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002380 return &ICI;
Chris Lattner2188e402010-01-04 07:37:31 +00002381 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002382 break;
Amaury Sechet6bea6742016-08-04 05:27:20 +00002383 case Intrinsic::ctpop: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002384 // popcount(A) == 0 -> A == 0 and likewise for !=
Amaury Sechet6bea6742016-08-04 05:27:20 +00002385 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
2386 bool IsZero = *Op1C == 0;
2387 if (IsZero || *Op1C == Op1C->getBitWidth()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002388 Worklist.Add(II);
2389 ICI.setOperand(0, II->getArgOperand(0));
Amaury Sechet6bea6742016-08-04 05:27:20 +00002390 auto *NewOp = IsZero
2391 ? ConstantInt::getNullValue(II->getType())
2392 : ConstantInt::getAllOnesValue(II->getType());
2393 ICI.setOperand(1, NewOp);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002394 return &ICI;
2395 }
Amaury Sechet6bea6742016-08-04 05:27:20 +00002396 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002397 break;
2398 default:
2399 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002400 }
Craig Topperf40110f2014-04-25 05:29:35 +00002401 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002402}
2403
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002404/// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so
2405/// far.
Sanjay Patel43395062016-07-21 18:07:40 +00002406Instruction *InstCombiner::foldICmpWithCastAndCast(ICmpInst &ICmp) {
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002407 const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00002408 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002409 Type *SrcTy = LHSCIOp->getType();
2410 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002411 Value *RHSCIOp;
2412
Jim Grosbach129c52a2011-09-30 18:09:53 +00002413 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00002414 // integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002415 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
2416 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002417 Value *RHSOp = nullptr;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002418 if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
Michael Liaod266b922015-02-13 04:51:26 +00002419 Value *RHSCIOp = RHSC->getOperand(0);
2420 if (RHSCIOp->getType()->getPointerAddressSpace() ==
2421 LHSCIOp->getType()->getPointerAddressSpace()) {
2422 RHSOp = RHSC->getOperand(0);
2423 // If the pointer types don't match, insert a bitcast.
2424 if (LHSCIOp->getType() != RHSOp->getType())
2425 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
2426 }
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002427 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002428 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002429 }
Chris Lattner2188e402010-01-04 07:37:31 +00002430
2431 if (RHSOp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002432 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002433 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002434
Chris Lattner2188e402010-01-04 07:37:31 +00002435 // The code below only handles extension cast instructions, so far.
2436 // Enforce this.
2437 if (LHSCI->getOpcode() != Instruction::ZExt &&
2438 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002439 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002440
2441 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002442 bool isSignedCmp = ICmp.isSigned();
Chris Lattner2188e402010-01-04 07:37:31 +00002443
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002444 if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002445 // Not an extension from the same type?
2446 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002447 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00002448 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002449
Chris Lattner2188e402010-01-04 07:37:31 +00002450 // If the signedness of the two casts doesn't agree (i.e. one is a sext
2451 // and the other is a zext), then we can't handle this.
2452 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00002453 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002454
2455 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002456 if (ICmp.isEquality())
2457 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002458
2459 // A signed comparison of sign extended values simplifies into a
2460 // signed comparison.
2461 if (isSignedCmp && isSignedExt)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002462 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002463
2464 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002465 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002466 }
2467
Sanjay Patel4c204232016-06-04 20:39:22 +00002468 // If we aren't dealing with a constant on the RHS, exit early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002469 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
2470 if (!C)
Craig Topperf40110f2014-04-25 05:29:35 +00002471 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002472
2473 // Compute the constant that would happen if we truncated to SrcTy then
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002474 // re-extended to DestTy.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002475 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002476 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattner2188e402010-01-04 07:37:31 +00002477
2478 // If the re-extended constant didn't change...
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002479 if (Res2 == C) {
Chris Lattner2188e402010-01-04 07:37:31 +00002480 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002481 if (ICmp.isEquality())
2482 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002483
2484 // A signed comparison of sign extended values simplifies into a
2485 // signed comparison.
2486 if (isSignedExt && isSignedCmp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002487 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002488
2489 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002490 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002491 }
2492
Sanjay Patel6a333c32016-06-06 16:56:57 +00002493 // The re-extended constant changed, partly changed (in the case of a vector),
2494 // or could not be determined to be equal (in the case of a constant
2495 // expression), so the constant cannot be represented in the shorter type.
2496 // Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002497 // All the cases that fold to true or false will have already been handled
2498 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00002499
Sanjay Patel6a333c32016-06-06 16:56:57 +00002500 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
Craig Topperf40110f2014-04-25 05:29:35 +00002501 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002502
2503 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
2504 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002505
2506 // We're performing an unsigned comp with a sign extended value.
2507 // This is true if the input is >= 0. [aka >s -1]
2508 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002509 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00002510
2511 // Finally, return the value computed.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002512 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
2513 return replaceInstUsesWith(ICmp, Result);
Chris Lattner2188e402010-01-04 07:37:31 +00002514
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002515 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00002516 return BinaryOperator::CreateNot(Result);
2517}
2518
Sanjay Patel5f0217f2016-06-05 16:46:18 +00002519/// The caller has matched a pattern of the form:
Chris Lattneree61c1d2010-12-19 17:52:50 +00002520/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00002521/// If this is of the form:
2522/// sum = a + b
2523/// if (sum+128 >u 255)
2524/// Then replace it with llvm.sadd.with.overflow.i8.
2525///
Chris Lattneree61c1d2010-12-19 17:52:50 +00002526static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2527 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00002528 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00002529 // The transformation we're trying to do here is to transform this into an
2530 // llvm.sadd.with.overflow. To do this, we have to replace the original add
2531 // with a narrower add, and discard the add-with-constant that is part of the
2532 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00002533
Chris Lattnerf29562d2010-12-19 17:59:02 +00002534 // In order to eliminate the add-with-constant, the compare can be its only
2535 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00002536 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00002537 if (!AddWithCst->hasOneUse()) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002538
Chris Lattnerc56c8452010-12-19 18:22:06 +00002539 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
Craig Topperf40110f2014-04-25 05:29:35 +00002540 if (!CI2->getValue().isPowerOf2()) return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002541 unsigned NewWidth = CI2->getValue().countTrailingZeros();
Craig Topperf40110f2014-04-25 05:29:35 +00002542 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002543
Chris Lattnerc56c8452010-12-19 18:22:06 +00002544 // The width of the new add formed is 1 more than the bias.
2545 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002546
Chris Lattnerc56c8452010-12-19 18:22:06 +00002547 // Check to see that CI1 is an all-ones value with NewWidth bits.
2548 if (CI1->getBitWidth() == NewWidth ||
2549 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
Craig Topperf40110f2014-04-25 05:29:35 +00002550 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002551
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002552 // This is only really a signed overflow check if the inputs have been
2553 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2554 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2555 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
Hal Finkel60db0582014-09-07 18:57:58 +00002556 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2557 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
Craig Topperf40110f2014-04-25 05:29:35 +00002558 return nullptr;
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002559
Jim Grosbach129c52a2011-09-30 18:09:53 +00002560 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00002561 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2562 // and truncates that discard the high bits of the add. Verify that this is
2563 // the case.
2564 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00002565 for (User *U : OrigAdd->users()) {
2566 if (U == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002567
Chris Lattnerc56c8452010-12-19 18:22:06 +00002568 // Only accept truncates for now. We would really like a nice recursive
2569 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2570 // chain to see which bits of a value are actually demanded. If the
2571 // original add had another add which was then immediately truncated, we
2572 // could still do the transformation.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002573 TruncInst *TI = dyn_cast<TruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00002574 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2575 return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002576 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002577
Chris Lattneree61c1d2010-12-19 17:52:50 +00002578 // If the pattern matches, truncate the inputs to the narrower type and
2579 // use the sadd_with_overflow intrinsic to efficiently compute both the
2580 // result and the overflow bit.
Jay Foadb804a2b2011-07-12 14:06:48 +00002581 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002582 Value *F = Intrinsic::getDeclaration(I.getModule(),
2583 Intrinsic::sadd_with_overflow, NewType);
Chris Lattner79874562010-12-19 18:35:09 +00002584
Chris Lattnerce2995a2010-12-19 18:38:44 +00002585 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002586
Chris Lattner79874562010-12-19 18:35:09 +00002587 // Put the new code above the original add, in case there are any uses of the
2588 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002589 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002590
Chris Lattner79874562010-12-19 18:35:09 +00002591 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2592 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
David Blaikieff6409d2015-05-18 22:13:54 +00002593 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
Chris Lattner79874562010-12-19 18:35:09 +00002594 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2595 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002596
Chris Lattneree61c1d2010-12-19 17:52:50 +00002597 // The inner add was the result of the narrow add, zero extended to the
2598 // wider type. Replace it with the result computed by the intrinsic.
Sanjay Patel4b198802016-02-01 22:23:39 +00002599 IC.replaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002600
Chris Lattner79874562010-12-19 18:35:09 +00002601 // The original icmp gets replaced with the overflow value.
2602 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00002603}
Chris Lattner2188e402010-01-04 07:37:31 +00002604
Sanjoy Dasb0984472015-04-08 04:27:22 +00002605bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
2606 Value *RHS, Instruction &OrigI,
2607 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00002608 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
2609 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002610
2611 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
2612 Result = OpResult;
2613 Overflow = OverflowVal;
2614 if (ReuseName)
2615 Result->takeName(&OrigI);
2616 return true;
2617 };
2618
Sanjoy Das6f5dca72015-08-28 19:09:31 +00002619 // If the overflow check was an add followed by a compare, the insertion point
2620 // may be pointing to the compare. We want to insert the new instructions
2621 // before the add in case there are uses of the add between the add and the
2622 // compare.
2623 Builder->SetInsertPoint(&OrigI);
2624
Sanjoy Dasb0984472015-04-08 04:27:22 +00002625 switch (OCF) {
2626 case OCF_INVALID:
2627 llvm_unreachable("bad overflow check kind!");
2628
2629 case OCF_UNSIGNED_ADD: {
2630 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
2631 if (OR == OverflowResult::NeverOverflows)
2632 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
2633 true);
2634
2635 if (OR == OverflowResult::AlwaysOverflows)
2636 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
2637 }
2638 // FALL THROUGH uadd into sadd
2639 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002640 // X + 0 -> {X, false}
2641 if (match(RHS, m_Zero()))
2642 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002643
2644 // We can strength reduce this signed add into a regular add if we can prove
2645 // that it will never overflow.
2646 if (OCF == OCF_SIGNED_ADD)
2647 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
2648 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
2649 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00002650 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002651 }
2652
2653 case OCF_UNSIGNED_SUB:
2654 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002655 // X - 0 -> {X, false}
2656 if (match(RHS, m_Zero()))
2657 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002658
2659 if (OCF == OCF_SIGNED_SUB) {
2660 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
2661 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
2662 true);
2663 } else {
2664 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
2665 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
2666 true);
2667 }
2668 break;
2669 }
2670
2671 case OCF_UNSIGNED_MUL: {
2672 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
2673 if (OR == OverflowResult::NeverOverflows)
2674 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
2675 true);
2676 if (OR == OverflowResult::AlwaysOverflows)
2677 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
2678 } // FALL THROUGH
2679 case OCF_SIGNED_MUL:
2680 // X * undef -> undef
2681 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00002682 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002683
David Majnemer27e89ba2015-05-21 23:04:21 +00002684 // X * 0 -> {0, false}
2685 if (match(RHS, m_Zero()))
2686 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002687
David Majnemer27e89ba2015-05-21 23:04:21 +00002688 // X * 1 -> {X, false}
2689 if (match(RHS, m_One()))
2690 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002691
2692 if (OCF == OCF_SIGNED_MUL)
2693 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
2694 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
2695 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00002696 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002697 }
2698
2699 return false;
2700}
2701
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002702/// \brief Recognize and process idiom involving test for multiplication
2703/// overflow.
2704///
2705/// The caller has matched a pattern of the form:
2706/// I = cmp u (mul(zext A, zext B), V
2707/// The function checks if this is a test for overflow and if so replaces
2708/// multiplication with call to 'mul.with.overflow' intrinsic.
2709///
2710/// \param I Compare instruction.
2711/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2712/// the compare instruction. Must be of integer type.
2713/// \param OtherVal The other argument of compare instruction.
2714/// \returns Instruction which must replace the compare instruction, NULL if no
2715/// replacement required.
2716static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2717 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00002718 // Don't bother doing this transformation for pointers, don't do it for
2719 // vectors.
2720 if (!isa<IntegerType>(MulVal->getType()))
2721 return nullptr;
2722
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002723 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2724 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00002725 auto *MulInstr = dyn_cast<Instruction>(MulVal);
2726 if (!MulInstr)
2727 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002728 assert(MulInstr->getOpcode() == Instruction::Mul);
2729
David Majnemer634ca232014-11-01 23:46:05 +00002730 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
2731 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002732 assert(LHS->getOpcode() == Instruction::ZExt);
2733 assert(RHS->getOpcode() == Instruction::ZExt);
2734 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2735
2736 // Calculate type and width of the result produced by mul.with.overflow.
2737 Type *TyA = A->getType(), *TyB = B->getType();
2738 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2739 WidthB = TyB->getPrimitiveSizeInBits();
2740 unsigned MulWidth;
2741 Type *MulType;
2742 if (WidthB > WidthA) {
2743 MulWidth = WidthB;
2744 MulType = TyB;
2745 } else {
2746 MulWidth = WidthA;
2747 MulType = TyA;
2748 }
2749
2750 // In order to replace the original mul with a narrower mul.with.overflow,
2751 // all uses must ignore upper bits of the product. The number of used low
2752 // bits must be not greater than the width of mul.with.overflow.
2753 if (MulVal->hasNUsesOrMore(2))
2754 for (User *U : MulVal->users()) {
2755 if (U == &I)
2756 continue;
2757 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2758 // Check if truncation ignores bits above MulWidth.
2759 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2760 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002761 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002762 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2763 // Check if AND ignores bits above MulWidth.
2764 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00002765 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002766 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2767 const APInt &CVal = CI->getValue();
2768 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002769 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002770 }
2771 } else {
2772 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00002773 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002774 }
2775 }
2776
2777 // Recognize patterns
2778 switch (I.getPredicate()) {
2779 case ICmpInst::ICMP_EQ:
2780 case ICmpInst::ICMP_NE:
2781 // Recognize pattern:
2782 // mulval = mul(zext A, zext B)
2783 // cmp eq/neq mulval, zext trunc mulval
2784 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2785 if (Zext->hasOneUse()) {
2786 Value *ZextArg = Zext->getOperand(0);
2787 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2788 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2789 break; //Recognized
2790 }
2791
2792 // Recognize pattern:
2793 // mulval = mul(zext A, zext B)
2794 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2795 ConstantInt *CI;
2796 Value *ValToMask;
2797 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2798 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00002799 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002800 const APInt &CVal = CI->getValue() + 1;
2801 if (CVal.isPowerOf2()) {
2802 unsigned MaskWidth = CVal.logBase2();
2803 if (MaskWidth == MulWidth)
2804 break; // Recognized
2805 }
2806 }
Craig Topperf40110f2014-04-25 05:29:35 +00002807 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002808
2809 case ICmpInst::ICMP_UGT:
2810 // Recognize pattern:
2811 // mulval = mul(zext A, zext B)
2812 // cmp ugt mulval, max
2813 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2814 APInt MaxVal = APInt::getMaxValue(MulWidth);
2815 MaxVal = MaxVal.zext(CI->getBitWidth());
2816 if (MaxVal.eq(CI->getValue()))
2817 break; // Recognized
2818 }
Craig Topperf40110f2014-04-25 05:29:35 +00002819 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002820
2821 case ICmpInst::ICMP_UGE:
2822 // Recognize pattern:
2823 // mulval = mul(zext A, zext B)
2824 // cmp uge mulval, max+1
2825 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2826 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2827 if (MaxVal.eq(CI->getValue()))
2828 break; // Recognized
2829 }
Craig Topperf40110f2014-04-25 05:29:35 +00002830 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002831
2832 case ICmpInst::ICMP_ULE:
2833 // Recognize pattern:
2834 // mulval = mul(zext A, zext B)
2835 // cmp ule mulval, max
2836 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2837 APInt MaxVal = APInt::getMaxValue(MulWidth);
2838 MaxVal = MaxVal.zext(CI->getBitWidth());
2839 if (MaxVal.eq(CI->getValue()))
2840 break; // Recognized
2841 }
Craig Topperf40110f2014-04-25 05:29:35 +00002842 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002843
2844 case ICmpInst::ICMP_ULT:
2845 // Recognize pattern:
2846 // mulval = mul(zext A, zext B)
2847 // cmp ule mulval, max + 1
2848 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002849 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002850 if (MaxVal.eq(CI->getValue()))
2851 break; // Recognized
2852 }
Craig Topperf40110f2014-04-25 05:29:35 +00002853 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002854
2855 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002856 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002857 }
2858
2859 InstCombiner::BuilderTy *Builder = IC.Builder;
2860 Builder->SetInsertPoint(MulInstr);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002861
2862 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2863 Value *MulA = A, *MulB = B;
2864 if (WidthA < MulWidth)
2865 MulA = Builder->CreateZExt(A, MulType);
2866 if (WidthB < MulWidth)
2867 MulB = Builder->CreateZExt(B, MulType);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002868 Value *F = Intrinsic::getDeclaration(I.getModule(),
2869 Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00002870 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002871 IC.Worklist.Add(MulInstr);
2872
2873 // If there are uses of mul result other than the comparison, we know that
2874 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002875 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002876 if (MulVal->hasNUsesOrMore(2)) {
2877 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2878 for (User *U : MulVal->users()) {
2879 if (U == &I || U == OtherVal)
2880 continue;
2881 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2882 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
Sanjay Patel4b198802016-02-01 22:23:39 +00002883 IC.replaceInstUsesWith(*TI, Mul);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002884 else
2885 TI->setOperand(0, Mul);
2886 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2887 assert(BO->getOpcode() == Instruction::And);
2888 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2889 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2890 APInt ShortMask = CI->getValue().trunc(MulWidth);
2891 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2892 Instruction *Zext =
2893 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2894 IC.Worklist.Add(Zext);
Sanjay Patel4b198802016-02-01 22:23:39 +00002895 IC.replaceInstUsesWith(*BO, Zext);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002896 } else {
2897 llvm_unreachable("Unexpected Binary operation");
2898 }
2899 IC.Worklist.Add(cast<Instruction>(U));
2900 }
2901 }
2902 if (isa<Instruction>(OtherVal))
2903 IC.Worklist.Add(cast<Instruction>(OtherVal));
2904
2905 // The original icmp gets replaced with the overflow value, maybe inverted
2906 // depending on predicate.
2907 bool Inverse = false;
2908 switch (I.getPredicate()) {
2909 case ICmpInst::ICMP_NE:
2910 break;
2911 case ICmpInst::ICMP_EQ:
2912 Inverse = true;
2913 break;
2914 case ICmpInst::ICMP_UGT:
2915 case ICmpInst::ICMP_UGE:
2916 if (I.getOperand(0) == MulVal)
2917 break;
2918 Inverse = true;
2919 break;
2920 case ICmpInst::ICMP_ULT:
2921 case ICmpInst::ICMP_ULE:
2922 if (I.getOperand(1) == MulVal)
2923 break;
2924 Inverse = true;
2925 break;
2926 default:
2927 llvm_unreachable("Unexpected predicate");
2928 }
2929 if (Inverse) {
2930 Value *Res = Builder->CreateExtractValue(Call, 1);
2931 return BinaryOperator::CreateNot(Res);
2932 }
2933
2934 return ExtractValueInst::Create(Call, 1);
2935}
2936
Sanjay Patel5f0217f2016-06-05 16:46:18 +00002937/// When performing a comparison against a constant, it is possible that not all
2938/// the bits in the LHS are demanded. This helper method computes the mask that
2939/// IS demanded.
Owen Andersond490c2d2011-01-11 00:36:45 +00002940static APInt DemandedBitsLHSMask(ICmpInst &I,
2941 unsigned BitWidth, bool isSignCheck) {
2942 if (isSignCheck)
2943 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002944
Owen Andersond490c2d2011-01-11 00:36:45 +00002945 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2946 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00002947 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002948
Owen Andersond490c2d2011-01-11 00:36:45 +00002949 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002950 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00002951 // correspond to the trailing ones of the comparand. The value of these
2952 // bits doesn't impact the outcome of the comparison, because any value
2953 // greater than the RHS must differ in a bit higher than these due to carry.
2954 case ICmpInst::ICMP_UGT: {
2955 unsigned trailingOnes = RHS.countTrailingOnes();
2956 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2957 return ~lowBitsSet;
2958 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002959
Owen Andersond490c2d2011-01-11 00:36:45 +00002960 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2961 // Any value less than the RHS must differ in a higher bit because of carries.
2962 case ICmpInst::ICMP_ULT: {
2963 unsigned trailingZeros = RHS.countTrailingZeros();
2964 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2965 return ~lowBitsSet;
2966 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002967
Owen Andersond490c2d2011-01-11 00:36:45 +00002968 default:
2969 return APInt::getAllOnesValue(BitWidth);
2970 }
Owen Andersond490c2d2011-01-11 00:36:45 +00002971}
Chris Lattner2188e402010-01-04 07:37:31 +00002972
Quentin Colombet5ab55552013-09-09 20:56:48 +00002973/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2974/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00002975/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00002976/// as subtract operands and their positions in those instructions.
2977/// The rational is that several architectures use the same instruction for
2978/// both subtract and cmp, thus it is better if the order of those operands
2979/// match.
2980/// \return true if Op0 and Op1 should be swapped.
2981static bool swapMayExposeCSEOpportunities(const Value * Op0,
2982 const Value * Op1) {
2983 // Filter out pointer value as those cannot appears directly in subtract.
2984 // FIXME: we may want to go through inttoptrs or bitcasts.
2985 if (Op0->getType()->isPointerTy())
2986 return false;
2987 // Count every uses of both Op0 and Op1 in a subtract.
2988 // Each time Op0 is the first operand, count -1: swapping is bad, the
2989 // subtract has already the same layout as the compare.
2990 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00002991 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002992 // At the end, if the benefit is greater than 0, Op0 should come second to
2993 // expose more CSE opportunities.
2994 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002995 for (const User *U : Op0->users()) {
2996 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002997 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2998 continue;
2999 // If Op0 is the first argument, this is not beneficial to swap the
3000 // arguments.
3001 int LocalSwapBenefits = -1;
3002 unsigned Op1Idx = 1;
3003 if (BinOp->getOperand(Op1Idx) == Op0) {
3004 Op1Idx = 0;
3005 LocalSwapBenefits = 1;
3006 }
3007 if (BinOp->getOperand(Op1Idx) != Op1)
3008 continue;
3009 GlobalSwapBenefits += LocalSwapBenefits;
3010 }
3011 return GlobalSwapBenefits > 0;
3012}
3013
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003014/// \brief Check that one use is in the same block as the definition and all
3015/// other uses are in blocks dominated by a given block
3016///
3017/// \param DI Definition
3018/// \param UI Use
3019/// \param DB Block that must dominate all uses of \p DI outside
3020/// the parent block
3021/// \return true when \p UI is the only use of \p DI in the parent block
3022/// and all other uses of \p DI are in blocks dominated by \p DB.
3023///
3024bool InstCombiner::dominatesAllUses(const Instruction *DI,
3025 const Instruction *UI,
3026 const BasicBlock *DB) const {
3027 assert(DI && UI && "Instruction not defined\n");
3028 // ignore incomplete definitions
3029 if (!DI->getParent())
3030 return false;
3031 // DI and UI must be in the same block
3032 if (DI->getParent() != UI->getParent())
3033 return false;
3034 // Protect from self-referencing blocks
3035 if (DI->getParent() == DB)
3036 return false;
3037 // DominatorTree available?
3038 if (!DT)
3039 return false;
3040 for (const User *U : DI->users()) {
3041 auto *Usr = cast<Instruction>(U);
3042 if (Usr != UI && !DT->dominates(DB, Usr->getParent()))
3043 return false;
3044 }
3045 return true;
3046}
3047
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003048/// Return true when the instruction sequence within a block is select-cmp-br.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003049static bool isChainSelectCmpBranch(const SelectInst *SI) {
3050 const BasicBlock *BB = SI->getParent();
3051 if (!BB)
3052 return false;
3053 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
3054 if (!BI || BI->getNumSuccessors() != 2)
3055 return false;
3056 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
3057 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
3058 return false;
3059 return true;
3060}
3061
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003062/// \brief True when a select result is replaced by one of its operands
3063/// in select-icmp sequence. This will eventually result in the elimination
3064/// of the select.
3065///
3066/// \param SI Select instruction
3067/// \param Icmp Compare instruction
3068/// \param SIOpd Operand that replaces the select
3069///
3070/// Notes:
3071/// - The replacement is global and requires dominator information
3072/// - The caller is responsible for the actual replacement
3073///
3074/// Example:
3075///
3076/// entry:
3077/// %4 = select i1 %3, %C* %0, %C* null
3078/// %5 = icmp eq %C* %4, null
3079/// br i1 %5, label %9, label %7
3080/// ...
3081/// ; <label>:7 ; preds = %entry
3082/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
3083/// ...
3084///
3085/// can be transformed to
3086///
3087/// %5 = icmp eq %C* %0, null
3088/// %6 = select i1 %3, i1 %5, i1 true
3089/// br i1 %6, label %9, label %7
3090/// ...
3091/// ; <label>:7 ; preds = %entry
3092/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
3093///
3094/// Similar when the first operand of the select is a constant or/and
3095/// the compare is for not equal rather than equal.
3096///
3097/// NOTE: The function is only called when the select and compare constants
3098/// are equal, the optimization can work only for EQ predicates. This is not a
3099/// major restriction since a NE compare should be 'normalized' to an equal
3100/// compare, which usually happens in the combiner and test case
3101/// select-cmp-br.ll
3102/// checks for it.
3103bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
3104 const ICmpInst *Icmp,
3105 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00003106 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003107 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
3108 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
3109 // The check for the unique predecessor is not the best that can be
3110 // done. But it protects efficiently against cases like when SI's
3111 // home block has two successors, Succ and Succ1, and Succ1 predecessor
3112 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
3113 // replaced can be reached on either path. So the uniqueness check
3114 // guarantees that the path all uses of SI (outside SI's parent) are on
3115 // is disjoint from all other paths out of SI. But that information
3116 // is more expensive to compute, and the trade-off here is in favor
3117 // of compile-time.
3118 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
3119 NumSel++;
3120 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
3121 return true;
3122 }
3123 }
3124 return false;
3125}
3126
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003127/// If we have an icmp le or icmp ge instruction with a constant operand, turn
3128/// it into the appropriate icmp lt or icmp gt instruction. This transform
3129/// allows them to be folded in visitICmpInst.
Sanjay Patele9b2c322016-05-17 00:57:57 +00003130static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
3131 ICmpInst::Predicate Pred = I.getPredicate();
3132 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE &&
3133 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE)
3134 return nullptr;
3135
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003136 Value *Op0 = I.getOperand(0);
3137 Value *Op1 = I.getOperand(1);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003138 auto *Op1C = dyn_cast<Constant>(Op1);
3139 if (!Op1C)
3140 return nullptr;
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003141
Sanjay Patele9b2c322016-05-17 00:57:57 +00003142 // Check if the constant operand can be safely incremented/decremented without
3143 // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled
3144 // the edge cases for us, so we just assert on them. For vectors, we must
3145 // handle the edge cases.
3146 Type *Op1Type = Op1->getType();
3147 bool IsSigned = I.isSigned();
3148 bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE);
Sanjay Patel18254932016-05-17 01:12:31 +00003149 auto *CI = dyn_cast<ConstantInt>(Op1C);
3150 if (CI) {
Sanjay Patele9b2c322016-05-17 00:57:57 +00003151 // A <= MAX -> TRUE ; A >= MIN -> TRUE
3152 assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned));
3153 } else if (Op1Type->isVectorTy()) {
Sanjay Patelb79ab272016-05-13 15:10:46 +00003154 // TODO? If the edge cases for vectors were guaranteed to be handled as they
Sanjay Patele9b2c322016-05-17 00:57:57 +00003155 // are for scalar, we could remove the min/max checks. However, to do that,
3156 // we would have to use insertelement/shufflevector to replace edge values.
3157 unsigned NumElts = Op1Type->getVectorNumElements();
3158 for (unsigned i = 0; i != NumElts; ++i) {
3159 Constant *Elt = Op1C->getAggregateElement(i);
Benjamin Kramerca9a0fe2016-05-17 12:08:55 +00003160 if (!Elt)
3161 return nullptr;
3162
Sanjay Patele9b2c322016-05-17 00:57:57 +00003163 if (isa<UndefValue>(Elt))
3164 continue;
3165 // Bail out if we can't determine if this constant is min/max or if we
3166 // know that this constant is min/max.
3167 auto *CI = dyn_cast<ConstantInt>(Elt);
3168 if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned)))
3169 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003170 }
Sanjay Patele9b2c322016-05-17 00:57:57 +00003171 } else {
3172 // ConstantExpr?
3173 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003174 }
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003175
Sanjay Patele9b2c322016-05-17 00:57:57 +00003176 // Increment or decrement the constant and set the new comparison predicate:
3177 // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT
Sanjay Patel22b01fe2016-05-17 20:20:40 +00003178 Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003179 CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT;
3180 NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred;
3181 return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne));
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003182}
3183
Chris Lattner2188e402010-01-04 07:37:31 +00003184Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
3185 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00003186 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003187 unsigned Op0Cplxity = getComplexity(Op0);
3188 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003189
Chris Lattner2188e402010-01-04 07:37:31 +00003190 /// Orders the operands of the compare so that they are listed from most
3191 /// complex to least complex. This puts constants before unary operators,
3192 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003193 if (Op0Cplxity < Op1Cplxity ||
Sanjay Patel4c204232016-06-04 20:39:22 +00003194 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003195 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00003196 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003197 Changed = true;
3198 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003199
Jingyue Wu5e34ce32015-06-25 20:14:47 +00003200 if (Value *V =
3201 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00003202 return replaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003203
Pete Cooperbc5c5242011-12-01 03:58:40 +00003204 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00003205 // ie, abs(val) != 0 -> val != 0
Sanjay Patel4c204232016-06-04 20:39:22 +00003206 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003207 Value *Cond, *SelectTrue, *SelectFalse;
3208 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00003209 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003210 if (Value *V = dyn_castNegVal(SelectTrue)) {
3211 if (V == SelectFalse)
3212 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
3213 }
3214 else if (Value *V = dyn_castNegVal(SelectFalse)) {
3215 if (V == SelectTrue)
3216 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00003217 }
3218 }
3219 }
3220
Chris Lattner229907c2011-07-18 04:54:35 +00003221 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00003222
3223 // icmp's with boolean values can always be turned into bitwise operations
Sanjay Patela6fbc822016-06-05 17:49:45 +00003224 if (Ty->getScalarType()->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00003225 switch (I.getPredicate()) {
3226 default: llvm_unreachable("Invalid icmp instruction!");
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003227 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
3228 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003229 return BinaryOperator::CreateNot(Xor);
3230 }
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003231 case ICmpInst::ICMP_NE: // icmp ne i1 A, B -> A^B
Chris Lattner2188e402010-01-04 07:37:31 +00003232 return BinaryOperator::CreateXor(Op0, Op1);
3233
3234 case ICmpInst::ICMP_UGT:
3235 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
3236 // FALL THROUGH
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003237 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
3238 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003239 return BinaryOperator::CreateAnd(Not, Op1);
3240 }
3241 case ICmpInst::ICMP_SGT:
3242 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
3243 // FALL THROUGH
3244 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003245 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003246 return BinaryOperator::CreateAnd(Not, Op0);
3247 }
3248 case ICmpInst::ICMP_UGE:
3249 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
3250 // FALL THROUGH
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003251 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
3252 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003253 return BinaryOperator::CreateOr(Not, Op1);
3254 }
3255 case ICmpInst::ICMP_SGE:
3256 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
3257 // FALL THROUGH
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003258 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
3259 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003260 return BinaryOperator::CreateOr(Not, Op0);
3261 }
3262 }
3263 }
3264
Sanjay Patele9b2c322016-05-17 00:57:57 +00003265 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003266 return NewICmp;
3267
Chris Lattner2188e402010-01-04 07:37:31 +00003268 unsigned BitWidth = 0;
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003269 if (Ty->isIntOrIntVectorTy())
Chris Lattner2188e402010-01-04 07:37:31 +00003270 BitWidth = Ty->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003271 else // Get pointer size.
3272 BitWidth = DL.getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00003273
Chris Lattner2188e402010-01-04 07:37:31 +00003274 bool isSignBit = false;
3275
3276 // See if we are doing a comparison with a constant.
3277 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00003278 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003279
Owen Anderson1294ea72010-12-17 18:08:00 +00003280 // Match the following pattern, which is a common idiom when writing
3281 // overflow-safe integer arithmetic function. The source performs an
3282 // addition in wider type, and explicitly checks for overflow using
3283 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
3284 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00003285 //
3286 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00003287 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00003288 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003289 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00003290 // sum = a + b
3291 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00003292 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00003293 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00003294 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00003295 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00003296 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00003297 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00003298 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003299
Philip Reamesec8a8b52016-03-09 21:05:07 +00003300 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
3301 if (CI->isZero() && I.getPredicate() == ICmpInst::ICMP_SGT)
3302 if (auto *SI = dyn_cast<SelectInst>(Op0)) {
3303 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
3304 if (SPR.Flavor == SPF_SMIN) {
Philip Reames8f12eba2016-03-09 21:31:47 +00003305 if (isKnownPositive(A, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003306 return new ICmpInst(I.getPredicate(), B, CI);
Philip Reames8f12eba2016-03-09 21:31:47 +00003307 if (isKnownPositive(B, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003308 return new ICmpInst(I.getPredicate(), A, CI);
3309 }
3310 }
3311
3312
David Majnemera0afb552015-01-14 19:26:56 +00003313 // The following transforms are only 'worth it' if the only user of the
3314 // subtraction is the icmp.
3315 if (Op0->hasOneUse()) {
3316 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
3317 if (I.isEquality() && CI->isZero() &&
3318 match(Op0, m_Sub(m_Value(A), m_Value(B))))
3319 return new ICmpInst(I.getPredicate(), A, B);
3320
3321 // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
3322 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
3323 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3324 return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
3325
3326 // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
3327 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
3328 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3329 return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
3330
3331 // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
3332 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
3333 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3334 return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
3335
3336 // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
3337 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
3338 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3339 return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
Chris Lattner2188e402010-01-04 07:37:31 +00003340 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003341
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003342 if (I.isEquality()) {
3343 ConstantInt *CI2;
3344 if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
3345 match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
David Majnemer59939ac2014-10-19 08:23:08 +00003346 // (icmp eq/ne (ashr/lshr const2, A), const1)
Sanjay Patel43395062016-07-21 18:07:40 +00003347 if (Instruction *Inst = foldICmpCstShrConst(I, Op0, A, CI, CI2))
David Majnemer2abb8182014-10-25 07:13:13 +00003348 return Inst;
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003349 }
David Majnemer59939ac2014-10-19 08:23:08 +00003350 if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
3351 // (icmp eq/ne (shl const2, A), const1)
Sanjay Patel43395062016-07-21 18:07:40 +00003352 if (Instruction *Inst = foldICmpCstShlConst(I, Op0, A, CI, CI2))
David Majnemer2abb8182014-10-25 07:13:13 +00003353 return Inst;
David Majnemer59939ac2014-10-19 08:23:08 +00003354 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003355 }
3356
Chris Lattner2188e402010-01-04 07:37:31 +00003357 // If this comparison is a normal comparison, it demands all
3358 // bits, if it is a sign bit comparison, it only demands the sign bit.
3359 bool UnusedBit;
3360 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
Balaram Makam569eaec2016-05-04 21:32:14 +00003361
3362 // Canonicalize icmp instructions based on dominating conditions.
3363 BasicBlock *Parent = I.getParent();
3364 BasicBlock *Dom = Parent->getSinglePredecessor();
3365 auto *BI = Dom ? dyn_cast<BranchInst>(Dom->getTerminator()) : nullptr;
3366 ICmpInst::Predicate Pred;
3367 BasicBlock *TrueBB, *FalseBB;
3368 ConstantInt *CI2;
3369 if (BI && match(BI, m_Br(m_ICmp(Pred, m_Specific(Op0), m_ConstantInt(CI2)),
3370 TrueBB, FalseBB)) &&
3371 TrueBB != FalseBB) {
3372 ConstantRange CR = ConstantRange::makeAllowedICmpRegion(I.getPredicate(),
3373 CI->getValue());
3374 ConstantRange DominatingCR =
3375 (Parent == TrueBB)
3376 ? ConstantRange::makeExactICmpRegion(Pred, CI2->getValue())
3377 : ConstantRange::makeExactICmpRegion(
3378 CmpInst::getInversePredicate(Pred), CI2->getValue());
3379 ConstantRange Intersection = DominatingCR.intersectWith(CR);
3380 ConstantRange Difference = DominatingCR.difference(CR);
3381 if (Intersection.isEmptySet())
3382 return replaceInstUsesWith(I, Builder->getFalse());
3383 if (Difference.isEmptySet())
3384 return replaceInstUsesWith(I, Builder->getTrue());
3385 // Canonicalizing a sign bit comparison that gets used in a branch,
3386 // pessimizes codegen by generating branch on zero instruction instead
3387 // of a test and branch. So we avoid canonicalizing in such situations
3388 // because test and branch instruction has better branch displacement
3389 // than compare and branch instruction.
3390 if (!isBranchOnSignBitCheck(I, isSignBit) && !I.isEquality()) {
3391 if (auto *AI = Intersection.getSingleElement())
3392 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Builder->getInt(*AI));
3393 if (auto *AD = Difference.getSingleElement())
3394 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Builder->getInt(*AD));
3395 }
3396 }
Chris Lattner2188e402010-01-04 07:37:31 +00003397 }
3398
3399 // See if we can fold the comparison based on range information we can get
3400 // by checking whether bits are known to be zero or one in the input.
3401 if (BitWidth != 0) {
3402 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
3403 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
3404
3405 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersond490c2d2011-01-11 00:36:45 +00003406 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner2188e402010-01-04 07:37:31 +00003407 Op0KnownZero, Op0KnownOne, 0))
3408 return &I;
3409 if (SimplifyDemandedBits(I.getOperandUse(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003410 APInt::getAllOnesValue(BitWidth), Op1KnownZero,
3411 Op1KnownOne, 0))
Chris Lattner2188e402010-01-04 07:37:31 +00003412 return &I;
3413
3414 // Given the known and unknown bits, compute a range that the LHS could be
3415 // in. Compute the Min, Max and RHS values based on the known bits. For the
3416 // EQ and NE we use unsigned values.
3417 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
3418 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
3419 if (I.isSigned()) {
3420 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3421 Op0Min, Op0Max);
3422 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3423 Op1Min, Op1Max);
3424 } else {
3425 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3426 Op0Min, Op0Max);
3427 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3428 Op1Min, Op1Max);
3429 }
3430
3431 // If Min and Max are known to be the same, then SimplifyDemandedBits
3432 // figured out that the LHS is a constant. Just constant fold this now so
3433 // that code below can assume that Min != Max.
3434 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
3435 return new ICmpInst(I.getPredicate(),
Nick Lewycky92db8e82011-03-06 03:36:19 +00003436 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003437 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
3438 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewycky92db8e82011-03-06 03:36:19 +00003439 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner2188e402010-01-04 07:37:31 +00003440
3441 // Based on the range information we know about the LHS, see if we can
Nick Lewycky6b4454192011-02-28 06:20:05 +00003442 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner2188e402010-01-04 07:37:31 +00003443 switch (I.getPredicate()) {
3444 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattnerf7e89612010-11-21 06:44:42 +00003445 case ICmpInst::ICMP_EQ: {
Chris Lattner2188e402010-01-04 07:37:31 +00003446 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003447 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003448
Chris Lattnerf7e89612010-11-21 06:44:42 +00003449 // If all bits are known zero except for one, then we know at most one
3450 // bit is set. If the comparison is against zero, then this is a check
3451 // to see if *that* bit is set.
3452 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003453 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003454 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003455 Value *LHS = nullptr;
3456 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003457 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3458 LHSC->getValue() != Op0KnownZeroInverted)
3459 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003460
Chris Lattnerf7e89612010-11-21 06:44:42 +00003461 // 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 +00003462 // then turn "((1 << x)&8) == 0" into "x != 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003463 // or turn "((1 << x)&7) == 0" into "x > 2".
Craig Topperf40110f2014-04-25 05:29:35 +00003464 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003465 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003466 APInt ValToCheck = Op0KnownZeroInverted;
3467 if (ValToCheck.isPowerOf2()) {
3468 unsigned CmpVal = ValToCheck.countTrailingZeros();
3469 return new ICmpInst(ICmpInst::ICMP_NE, X,
3470 ConstantInt::get(X->getType(), CmpVal));
3471 } else if ((++ValToCheck).isPowerOf2()) {
3472 unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
3473 return new ICmpInst(ICmpInst::ICMP_UGT, X,
3474 ConstantInt::get(X->getType(), CmpVal));
3475 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003476 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003477
Chris Lattnerf7e89612010-11-21 06:44:42 +00003478 // 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 +00003479 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattner98457102011-02-10 05:23:05 +00003480 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003481 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003482 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003483 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner98457102011-02-10 05:23:05 +00003484 ConstantInt::get(X->getType(),
3485 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003486 }
Chris Lattner2188e402010-01-04 07:37:31 +00003487 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003488 }
3489 case ICmpInst::ICMP_NE: {
Chris Lattner2188e402010-01-04 07:37:31 +00003490 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003491 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003492
Chris Lattnerf7e89612010-11-21 06:44:42 +00003493 // If all bits are known zero except for one, then we know at most one
3494 // bit is set. If the comparison is against zero, then this is a check
3495 // to see if *that* bit is set.
3496 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003497 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003498 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003499 Value *LHS = nullptr;
3500 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003501 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3502 LHSC->getValue() != Op0KnownZeroInverted)
3503 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003504
Chris Lattnerf7e89612010-11-21 06:44:42 +00003505 // 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 +00003506 // then turn "((1 << x)&8) != 0" into "x == 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003507 // or turn "((1 << x)&7) != 0" into "x < 3".
Craig Topperf40110f2014-04-25 05:29:35 +00003508 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003509 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003510 APInt ValToCheck = Op0KnownZeroInverted;
3511 if (ValToCheck.isPowerOf2()) {
3512 unsigned CmpVal = ValToCheck.countTrailingZeros();
3513 return new ICmpInst(ICmpInst::ICMP_EQ, X,
3514 ConstantInt::get(X->getType(), CmpVal));
3515 } else if ((++ValToCheck).isPowerOf2()) {
3516 unsigned CmpVal = ValToCheck.countTrailingZeros();
3517 return new ICmpInst(ICmpInst::ICMP_ULT, X,
3518 ConstantInt::get(X->getType(), CmpVal));
3519 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003520 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003521
Chris Lattnerf7e89612010-11-21 06:44:42 +00003522 // 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 +00003523 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattner98457102011-02-10 05:23:05 +00003524 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003525 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003526 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003527 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner98457102011-02-10 05:23:05 +00003528 ConstantInt::get(X->getType(),
3529 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003530 }
Chris Lattner2188e402010-01-04 07:37:31 +00003531 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003532 }
Chris Lattner2188e402010-01-04 07:37:31 +00003533 case ICmpInst::ICMP_ULT:
3534 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003535 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003536 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003537 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003538 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
3539 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3540 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3541 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
3542 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003543 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003544
3545 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
3546 if (CI->isMinValue(true))
3547 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
3548 Constant::getAllOnesValue(Op0->getType()));
3549 }
3550 break;
3551 case ICmpInst::ICMP_UGT:
3552 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003553 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003554 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003555 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003556
3557 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
3558 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3559 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3560 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
3561 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003562 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003563
3564 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
3565 if (CI->isMaxValue(true))
3566 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
3567 Constant::getNullValue(Op0->getType()));
3568 }
3569 break;
3570 case ICmpInst::ICMP_SLT:
3571 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003572 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003573 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003574 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003575 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
3576 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3577 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3578 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
3579 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003580 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003581 }
3582 break;
3583 case ICmpInst::ICMP_SGT:
3584 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003585 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003586 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003587 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003588
3589 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
3590 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3591 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3592 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
3593 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003594 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003595 }
3596 break;
3597 case ICmpInst::ICMP_SGE:
3598 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
3599 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003600 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003601 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003602 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003603 break;
3604 case ICmpInst::ICMP_SLE:
3605 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
3606 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003607 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003608 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003609 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003610 break;
3611 case ICmpInst::ICMP_UGE:
3612 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
3613 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003614 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003615 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003616 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003617 break;
3618 case ICmpInst::ICMP_ULE:
3619 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
3620 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003621 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003622 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003623 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003624 break;
3625 }
3626
3627 // Turn a signed comparison into an unsigned one if both operands
3628 // are known to have the same sign.
3629 if (I.isSigned() &&
3630 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
3631 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
3632 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
3633 }
3634
3635 // Test if the ICmpInst instruction is used exclusively by a select as
3636 // part of a minimum or maximum operation. If so, refrain from doing
3637 // any other folding. This helps out other analyses which understand
3638 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
3639 // and CodeGen. And in this case, at least one of the comparison
3640 // operands has at least one user besides the compare (the select),
3641 // which would often largely negate the benefit of folding anyway.
3642 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00003643 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00003644 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
3645 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00003646 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003647
3648 // See if we are doing a comparison between a constant and an instruction that
3649 // can be folded into the comparison.
Sanjay Patel1271bf92016-07-23 13:06:49 +00003650
3651 // FIXME: Use m_APInt instead of dyn_cast<ConstantInt> to allow these
3652 // transforms for vectors.
3653
Chris Lattner2188e402010-01-04 07:37:31 +00003654 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003655 // Since the RHS is a ConstantInt (CI), if the left hand side is an
3656 // instruction, see if that instruction also has constants so that the
3657 // instruction can be folded into the icmp
Sanjay Patelab50a932016-08-02 22:38:33 +00003658 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Sanjay Patel43395062016-07-21 18:07:40 +00003659 if (Instruction *Res = foldICmpWithConstant(I, LHSI, CI))
Chris Lattner2188e402010-01-04 07:37:31 +00003660 return Res;
3661 }
3662
Sanjay Patelab50a932016-08-02 22:38:33 +00003663 if (Instruction *Res = foldICmpEqualityWithConstant(I))
3664 return Res;
3665
Sanjay Patel1271bf92016-07-23 13:06:49 +00003666 if (Instruction *Res = foldICmpIntrinsicWithConstant(I))
3667 return Res;
3668
Chris Lattner2188e402010-01-04 07:37:31 +00003669 // Handle icmp with constant (but not simple integer constant) RHS
3670 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3671 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3672 switch (LHSI->getOpcode()) {
3673 case Instruction::GetElementPtr:
3674 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3675 if (RHSC->isNullValue() &&
3676 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3677 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3678 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3679 break;
3680 case Instruction::PHI:
3681 // Only fold icmp into the PHI if the phi and icmp are in the same
3682 // block. If in the same block, we're encouraging jump threading. If
3683 // not, we are just pessimizing the code by making an i1 phi.
3684 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003685 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003686 return NV;
3687 break;
3688 case Instruction::Select: {
3689 // If either operand of the select is a constant, we can fold the
3690 // comparison into the select arms, which will cause one to be
3691 // constant folded and the select turned into a bitwise or.
Craig Topperf40110f2014-04-25 05:29:35 +00003692 Value *Op1 = nullptr, *Op2 = nullptr;
Hans Wennborg083ca9b2015-10-06 23:24:35 +00003693 ConstantInt *CI = nullptr;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003694 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003695 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003696 CI = dyn_cast<ConstantInt>(Op1);
3697 }
3698 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003699 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003700 CI = dyn_cast<ConstantInt>(Op2);
3701 }
Chris Lattner2188e402010-01-04 07:37:31 +00003702
3703 // We only want to perform this transformation if it will not lead to
3704 // additional code. This is true if either both sides of the select
3705 // fold to a constant (in which case the icmp is replaced with a select
3706 // which will usually simplify) or this is the only user of the
3707 // select (in which case we are trading a select+icmp for a simpler
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003708 // select+icmp) or all uses of the select can be replaced based on
3709 // dominance information ("Global cases").
3710 bool Transform = false;
3711 if (Op1 && Op2)
3712 Transform = true;
3713 else if (Op1 || Op2) {
3714 // Local case
3715 if (LHSI->hasOneUse())
3716 Transform = true;
3717 // Global cases
3718 else if (CI && !CI->isZero())
3719 // When Op1 is constant try replacing select with second operand.
3720 // Otherwise Op2 is constant and try replacing select with first
3721 // operand.
3722 Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
3723 Op1 ? 2 : 1);
3724 }
3725 if (Transform) {
Chris Lattner2188e402010-01-04 07:37:31 +00003726 if (!Op1)
3727 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3728 RHSC, I.getName());
3729 if (!Op2)
3730 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3731 RHSC, I.getName());
3732 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3733 }
3734 break;
3735 }
Chris Lattner2188e402010-01-04 07:37:31 +00003736 case Instruction::IntToPtr:
3737 // icmp pred inttoptr(X), null -> icmp pred X, 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003738 if (RHSC->isNullValue() &&
3739 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
Chris Lattner2188e402010-01-04 07:37:31 +00003740 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3741 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3742 break;
3743
3744 case Instruction::Load:
3745 // Try to optimize things like "A[i] > 4" to index computations.
3746 if (GetElementPtrInst *GEP =
3747 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3748 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3749 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3750 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00003751 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Chris Lattner2188e402010-01-04 07:37:31 +00003752 return Res;
3753 }
3754 break;
3755 }
3756 }
3757
3758 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3759 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Sanjay Patel43395062016-07-21 18:07:40 +00003760 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner2188e402010-01-04 07:37:31 +00003761 return NI;
3762 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00003763 if (Instruction *NI = foldGEPICmp(GEP, Op0,
Chris Lattner2188e402010-01-04 07:37:31 +00003764 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3765 return NI;
3766
Hans Wennborgf1f36512015-10-07 00:20:07 +00003767 // Try to optimize equality comparisons against alloca-based pointers.
3768 if (Op0->getType()->isPointerTy() && I.isEquality()) {
3769 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
3770 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00003771 if (Instruction *New = foldAllocaCmp(I, Alloca, Op1))
Hans Wennborgf1f36512015-10-07 00:20:07 +00003772 return New;
3773 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00003774 if (Instruction *New = foldAllocaCmp(I, Alloca, Op0))
Hans Wennborgf1f36512015-10-07 00:20:07 +00003775 return New;
3776 }
3777
Chris Lattner2188e402010-01-04 07:37:31 +00003778 // Test to see if the operands of the icmp are casted versions of other
3779 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3780 // now.
3781 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003782 if (Op0->getType()->isPointerTy() &&
3783 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003784 // We keep moving the cast from the left operand over to the right
3785 // operand, where it can often be eliminated completely.
3786 Op0 = CI->getOperand(0);
3787
3788 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3789 // so eliminate it as well.
3790 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3791 Op1 = CI2->getOperand(0);
3792
3793 // If Op1 is a constant, we can fold the cast into the constant.
3794 if (Op0->getType() != Op1->getType()) {
3795 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3796 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3797 } else {
3798 // Otherwise, cast the RHS right before the icmp
3799 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3800 }
3801 }
3802 return new ICmpInst(I.getPredicate(), Op0, Op1);
3803 }
3804 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003805
Chris Lattner2188e402010-01-04 07:37:31 +00003806 if (isa<CastInst>(Op0)) {
3807 // Handle the special case of: icmp (cast bool to X), <cst>
3808 // This comes up when you have code like
3809 // int X = A < B;
3810 // if (X) ...
3811 // For generality, we handle any zero-extension of any operand comparison
3812 // with a constant or another cast from the same type.
3813 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00003814 if (Instruction *R = foldICmpWithCastAndCast(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003815 return R;
3816 }
Chris Lattner2188e402010-01-04 07:37:31 +00003817
Duncan Sandse5220012011-02-17 07:46:37 +00003818 // Special logic for binary operators.
3819 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3820 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3821 if (BO0 || BO1) {
3822 CmpInst::Predicate Pred = I.getPredicate();
3823 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3824 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3825 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3826 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3827 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3828 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3829 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3830 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3831 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3832
3833 // Analyze the case when either Op0 or Op1 is an add instruction.
3834 // 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 +00003835 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +00003836 if (BO0 && BO0->getOpcode() == Instruction::Add) {
3837 A = BO0->getOperand(0);
3838 B = BO0->getOperand(1);
3839 }
3840 if (BO1 && BO1->getOpcode() == Instruction::Add) {
3841 C = BO1->getOperand(0);
3842 D = BO1->getOperand(1);
3843 }
Duncan Sandse5220012011-02-17 07:46:37 +00003844
David Majnemer549f4f22014-11-01 09:09:51 +00003845 // icmp (X+cst) < 0 --> X < -cst
3846 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
3847 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
3848 if (!RHSC->isMinValue(/*isSigned=*/true))
3849 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
3850
Duncan Sandse5220012011-02-17 07:46:37 +00003851 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3852 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3853 return new ICmpInst(Pred, A == Op1 ? B : A,
3854 Constant::getNullValue(Op1->getType()));
3855
3856 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3857 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3858 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3859 C == Op0 ? D : C);
3860
Duncan Sands84653b32011-02-18 16:25:37 +00003861 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003862 if (A && C && (A == C || A == D || B == C || B == D) &&
3863 NoOp0WrapProblem && NoOp1WrapProblem &&
3864 // Try not to increase register pressure.
3865 BO0->hasOneUse() && BO1->hasOneUse()) {
3866 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003867 Value *Y, *Z;
3868 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003869 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003870 Y = B;
3871 Z = D;
3872 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003873 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003874 Y = B;
3875 Z = C;
3876 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003877 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003878 Y = A;
3879 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003880 } else {
3881 assert(B == D);
3882 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003883 Y = A;
3884 Z = C;
3885 }
Duncan Sandse5220012011-02-17 07:46:37 +00003886 return new ICmpInst(Pred, Y, Z);
3887 }
3888
David Majnemerb81cd632013-04-11 20:05:46 +00003889 // icmp slt (X + -1), Y -> icmp sle X, Y
3890 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3891 match(B, m_AllOnes()))
3892 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3893
3894 // icmp sge (X + -1), Y -> icmp sgt X, Y
3895 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3896 match(B, m_AllOnes()))
3897 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3898
3899 // icmp sle (X + 1), Y -> icmp slt X, Y
3900 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3901 match(B, m_One()))
3902 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3903
3904 // icmp sgt (X + 1), Y -> icmp sge X, Y
3905 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3906 match(B, m_One()))
3907 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3908
Michael Liaoc65d3862015-10-19 22:08:14 +00003909 // icmp sgt X, (Y + -1) -> icmp sge X, Y
3910 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3911 match(D, m_AllOnes()))
3912 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3913
3914 // icmp sle X, (Y + -1) -> icmp slt X, Y
3915 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3916 match(D, m_AllOnes()))
3917 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3918
3919 // icmp sge X, (Y + 1) -> icmp sgt X, Y
3920 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE &&
3921 match(D, m_One()))
3922 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3923
3924 // icmp slt X, (Y + 1) -> icmp sle X, Y
3925 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT &&
3926 match(D, m_One()))
3927 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3928
David Majnemerb81cd632013-04-11 20:05:46 +00003929 // if C1 has greater magnitude than C2:
3930 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3931 // s.t. C3 = C1 - C2
3932 //
3933 // if C2 has greater magnitude than C1:
3934 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3935 // s.t. C3 = C2 - C1
3936 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3937 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3938 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3939 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3940 const APInt &AP1 = C1->getValue();
3941 const APInt &AP2 = C2->getValue();
3942 if (AP1.isNegative() == AP2.isNegative()) {
3943 APInt AP1Abs = C1->getValue().abs();
3944 APInt AP2Abs = C2->getValue().abs();
3945 if (AP1Abs.uge(AP2Abs)) {
3946 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
3947 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
3948 return new ICmpInst(Pred, NewAdd, C);
3949 } else {
3950 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
3951 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
3952 return new ICmpInst(Pred, A, NewAdd);
3953 }
3954 }
3955 }
3956
3957
Duncan Sandse5220012011-02-17 07:46:37 +00003958 // Analyze the case when either Op0 or Op1 is a sub instruction.
3959 // 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 +00003960 A = nullptr;
3961 B = nullptr;
3962 C = nullptr;
3963 D = nullptr;
3964 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
3965 A = BO0->getOperand(0);
3966 B = BO0->getOperand(1);
3967 }
3968 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3969 C = BO1->getOperand(0);
3970 D = BO1->getOperand(1);
3971 }
Duncan Sandse5220012011-02-17 07:46:37 +00003972
Duncan Sands84653b32011-02-18 16:25:37 +00003973 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3974 if (A == Op1 && NoOp0WrapProblem)
3975 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3976
3977 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
3978 if (C == Op0 && NoOp1WrapProblem)
3979 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3980
3981 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003982 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
3983 // Try not to increase register pressure.
3984 BO0->hasOneUse() && BO1->hasOneUse())
3985 return new ICmpInst(Pred, A, C);
3986
Duncan Sands84653b32011-02-18 16:25:37 +00003987 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
3988 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3989 // Try not to increase register pressure.
3990 BO0->hasOneUse() && BO1->hasOneUse())
3991 return new ICmpInst(Pred, D, B);
3992
David Majnemer186c9422014-05-15 00:02:20 +00003993 // icmp (0-X) < cst --> x > -cst
3994 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3995 Value *X;
3996 if (match(BO0, m_Neg(m_Value(X))))
3997 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
3998 if (!RHSC->isMinValue(/*isSigned=*/true))
3999 return new ICmpInst(I.getSwappedPredicate(), X,
4000 ConstantExpr::getNeg(RHSC));
4001 }
4002
Craig Topperf40110f2014-04-25 05:29:35 +00004003 BinaryOperator *SRem = nullptr;
Nick Lewyckyafc80982011-03-08 06:29:47 +00004004 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00004005 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
4006 Op1 == BO0->getOperand(1))
4007 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00004008 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00004009 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
4010 Op0 == BO1->getOperand(1))
4011 SRem = BO1;
4012 if (SRem) {
4013 // We don't check hasOneUse to avoid increasing register pressure because
4014 // the value we use is the same value this instruction was already using.
4015 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
4016 default: break;
4017 case ICmpInst::ICMP_EQ:
Sanjay Patel4b198802016-02-01 22:23:39 +00004018 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00004019 case ICmpInst::ICMP_NE:
Sanjay Patel4b198802016-02-01 22:23:39 +00004020 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00004021 case ICmpInst::ICMP_SGT:
4022 case ICmpInst::ICMP_SGE:
4023 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
4024 Constant::getAllOnesValue(SRem->getType()));
4025 case ICmpInst::ICMP_SLT:
4026 case ICmpInst::ICMP_SLE:
4027 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
4028 Constant::getNullValue(SRem->getType()));
4029 }
4030 }
4031
Duncan Sandse5220012011-02-17 07:46:37 +00004032 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
4033 BO0->hasOneUse() && BO1->hasOneUse() &&
4034 BO0->getOperand(1) == BO1->getOperand(1)) {
4035 switch (BO0->getOpcode()) {
4036 default: break;
4037 case Instruction::Add:
4038 case Instruction::Sub:
4039 case Instruction::Xor:
4040 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
4041 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4042 BO1->getOperand(0));
4043 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
4044 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4045 if (CI->getValue().isSignBit()) {
4046 ICmpInst::Predicate Pred = I.isSigned()
4047 ? I.getUnsignedPredicate()
4048 : I.getSignedPredicate();
4049 return new ICmpInst(Pred, BO0->getOperand(0),
4050 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00004051 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004052
David Majnemerf8853ae2016-02-01 17:37:56 +00004053 if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00004054 ICmpInst::Predicate Pred = I.isSigned()
4055 ? I.getUnsignedPredicate()
4056 : I.getSignedPredicate();
4057 Pred = I.getSwappedPredicate(Pred);
4058 return new ICmpInst(Pred, BO0->getOperand(0),
4059 BO1->getOperand(0));
4060 }
Chris Lattner2188e402010-01-04 07:37:31 +00004061 }
Duncan Sandse5220012011-02-17 07:46:37 +00004062 break;
4063 case Instruction::Mul:
4064 if (!I.isEquality())
4065 break;
4066
4067 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4068 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
4069 // Mask = -1 >> count-trailing-zeros(Cst).
4070 if (!CI->isZero() && !CI->isOne()) {
4071 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004072 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00004073 APInt::getLowBitsSet(AP.getBitWidth(),
4074 AP.getBitWidth() -
4075 AP.countTrailingZeros()));
4076 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
4077 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
4078 return new ICmpInst(I.getPredicate(), And1, And2);
4079 }
4080 }
4081 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00004082 case Instruction::UDiv:
4083 case Instruction::LShr:
4084 if (I.isSigned())
4085 break;
4086 // fall-through
4087 case Instruction::SDiv:
4088 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00004089 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00004090 break;
4091 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4092 BO1->getOperand(0));
4093 case Instruction::Shl: {
4094 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
4095 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
4096 if (!NUW && !NSW)
4097 break;
4098 if (!NSW && I.isSigned())
4099 break;
4100 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4101 BO1->getOperand(0));
4102 }
Chris Lattner2188e402010-01-04 07:37:31 +00004103 }
4104 }
Sanjoy Dasc86c1622015-08-21 22:22:37 +00004105
4106 if (BO0) {
4107 // Transform A & (L - 1) `ult` L --> L != 0
4108 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
4109 auto BitwiseAnd =
4110 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
4111
4112 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
4113 auto *Zero = Constant::getNullValue(BO0->getType());
4114 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
4115 }
4116 }
Chris Lattner2188e402010-01-04 07:37:31 +00004117 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004118
Chris Lattner2188e402010-01-04 07:37:31 +00004119 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00004120 // Transform (A & ~B) == 0 --> (A & B) != 0
4121 // and (A & ~B) != 0 --> (A & B) == 0
4122 // if A is a power of 2.
4123 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00004124 match(Op1, m_Zero()) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004125 isKnownToBeAPowerOfTwo(A, DL, false, 0, AC, &I, DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00004126 return new ICmpInst(I.getInversePredicate(),
4127 Builder->CreateAnd(A, B),
4128 Op1);
4129
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004130 // ~x < ~y --> y < x
4131 // ~x < cst --> ~cst < x
4132 if (match(Op0, m_Not(m_Value(A)))) {
4133 if (match(Op1, m_Not(m_Value(B))))
4134 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00004135 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004136 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
4137 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00004138
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004139 Instruction *AddI = nullptr;
4140 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
4141 m_Instruction(AddI))) &&
4142 isa<IntegerType>(A->getType())) {
4143 Value *Result;
4144 Constant *Overflow;
4145 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
4146 Overflow)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004147 replaceInstUsesWith(*AddI, Result);
4148 return replaceInstUsesWith(I, Overflow);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004149 }
4150 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004151
4152 // (zext a) * (zext b) --> llvm.umul.with.overflow.
4153 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4154 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
4155 return R;
4156 }
4157 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4158 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
4159 return R;
4160 }
Chris Lattner2188e402010-01-04 07:37:31 +00004161 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004162
Chris Lattner2188e402010-01-04 07:37:31 +00004163 if (I.isEquality()) {
4164 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00004165
Chris Lattner2188e402010-01-04 07:37:31 +00004166 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4167 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4168 Value *OtherVal = A == Op1 ? B : A;
4169 return new ICmpInst(I.getPredicate(), OtherVal,
4170 Constant::getNullValue(A->getType()));
4171 }
4172
4173 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4174 // A^c1 == C^c2 --> A == C^(c1^c2)
4175 ConstantInt *C1, *C2;
4176 if (match(B, m_ConstantInt(C1)) &&
4177 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00004178 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004179 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00004180 return new ICmpInst(I.getPredicate(), A, Xor);
4181 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004182
Chris Lattner2188e402010-01-04 07:37:31 +00004183 // A^B == A^D -> B == D
4184 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4185 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4186 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4187 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4188 }
4189 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004190
Chris Lattner2188e402010-01-04 07:37:31 +00004191 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4192 (A == Op0 || B == Op0)) {
4193 // A == (A^B) -> B == 0
4194 Value *OtherVal = A == Op0 ? B : A;
4195 return new ICmpInst(I.getPredicate(), OtherVal,
4196 Constant::getNullValue(A->getType()));
4197 }
4198
Chris Lattner2188e402010-01-04 07:37:31 +00004199 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00004200 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00004201 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Craig Topperf40110f2014-04-25 05:29:35 +00004202 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004203
Chris Lattner2188e402010-01-04 07:37:31 +00004204 if (A == C) {
4205 X = B; Y = D; Z = A;
4206 } else if (A == D) {
4207 X = B; Y = C; Z = A;
4208 } else if (B == C) {
4209 X = A; Y = D; Z = B;
4210 } else if (B == D) {
4211 X = A; Y = C; Z = B;
4212 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004213
Chris Lattner2188e402010-01-04 07:37:31 +00004214 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004215 Op1 = Builder->CreateXor(X, Y);
4216 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00004217 I.setOperand(0, Op1);
4218 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4219 return &I;
4220 }
4221 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004222
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004223 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00004224 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004225 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00004226 if ((Op0->hasOneUse() &&
4227 match(Op0, m_ZExt(m_Value(A))) &&
4228 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
4229 (Op1->hasOneUse() &&
4230 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
4231 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004232 APInt Pow2 = Cst1->getValue() + 1;
4233 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
4234 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
4235 return new ICmpInst(I.getPredicate(), A,
4236 Builder->CreateTrunc(B, A->getType()));
4237 }
4238
Benjamin Kramer03f3e242013-11-16 16:00:48 +00004239 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
4240 // For lshr and ashr pairs.
4241 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4242 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
4243 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4244 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
4245 unsigned TypeBits = Cst1->getBitWidth();
4246 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4247 if (ShAmt < TypeBits && ShAmt != 0) {
4248 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
4249 ? ICmpInst::ICMP_UGE
4250 : ICmpInst::ICMP_ULT;
4251 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4252 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
4253 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
4254 }
4255 }
4256
Benjamin Kramer7fa8c432015-03-26 17:12:06 +00004257 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
4258 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
4259 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
4260 unsigned TypeBits = Cst1->getBitWidth();
4261 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4262 if (ShAmt < TypeBits && ShAmt != 0) {
4263 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4264 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
4265 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
4266 I.getName() + ".mask");
4267 return new ICmpInst(I.getPredicate(), And,
4268 Constant::getNullValue(Cst1->getType()));
4269 }
4270 }
4271
Chris Lattner1b06c712011-04-26 20:18:20 +00004272 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
4273 // "icmp (and X, mask), cst"
4274 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00004275 if (Op0->hasOneUse() &&
4276 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
4277 m_ConstantInt(ShAmt))))) &&
4278 match(Op1, m_ConstantInt(Cst1)) &&
4279 // Only do this when A has multiple uses. This is most important to do
4280 // when it exposes other optimizations.
4281 !A->hasOneUse()) {
4282 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004283
Chris Lattner1b06c712011-04-26 20:18:20 +00004284 if (ShAmt < ASize) {
4285 APInt MaskV =
4286 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
4287 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004288
Chris Lattner1b06c712011-04-26 20:18:20 +00004289 APInt CmpV = Cst1->getValue().zext(ASize);
4290 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004291
Chris Lattner1b06c712011-04-26 20:18:20 +00004292 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
4293 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
4294 }
4295 }
Chris Lattner2188e402010-01-04 07:37:31 +00004296 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004297
David Majnemerc1eca5a2014-11-06 23:23:30 +00004298 // The 'cmpxchg' instruction returns an aggregate containing the old value and
4299 // an i1 which indicates whether or not we successfully did the swap.
4300 //
4301 // Replace comparisons between the old value and the expected value with the
4302 // indicator that 'cmpxchg' returns.
4303 //
4304 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
4305 // spuriously fail. In those cases, the old value may equal the expected
4306 // value but it is possible for the swap to not occur.
4307 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4308 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4309 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4310 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4311 !ACXI->isWeak())
4312 return ExtractValueInst::Create(ACXI, 1);
4313
Chris Lattner2188e402010-01-04 07:37:31 +00004314 {
4315 Value *X; ConstantInt *Cst;
4316 // icmp X+Cst, X
4317 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004318 return foldICmpAddOpConst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004319
4320 // icmp X, X+Cst
4321 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004322 return foldICmpAddOpConst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004323 }
Craig Topperf40110f2014-04-25 05:29:35 +00004324 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004325}
4326
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004327/// Fold fcmp ([us]itofp x, cst) if possible.
Sanjay Patel43395062016-07-21 18:07:40 +00004328Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
Chris Lattner2188e402010-01-04 07:37:31 +00004329 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00004330 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004331 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004332
Chris Lattner2188e402010-01-04 07:37:31 +00004333 // Get the width of the mantissa. We don't want to hack on conversions that
4334 // might lose information from the integer, e.g. "i64 -> float"
4335 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00004336 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004337
Matt Arsenault55e73122015-01-06 15:50:59 +00004338 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4339
Chris Lattner2188e402010-01-04 07:37:31 +00004340 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004341
Matt Arsenault55e73122015-01-06 15:50:59 +00004342 if (I.isEquality()) {
4343 FCmpInst::Predicate P = I.getPredicate();
4344 bool IsExact = false;
4345 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
4346 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
4347
4348 // If the floating point constant isn't an integer value, we know if we will
4349 // ever compare equal / not equal to it.
4350 if (!IsExact) {
4351 // TODO: Can never be -0.0 and other non-representable values
4352 APFloat RHSRoundInt(RHS);
4353 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
4354 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
4355 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00004356 return replaceInstUsesWith(I, Builder->getFalse());
Matt Arsenault55e73122015-01-06 15:50:59 +00004357
4358 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
Sanjay Patel4b198802016-02-01 22:23:39 +00004359 return replaceInstUsesWith(I, Builder->getTrue());
Matt Arsenault55e73122015-01-06 15:50:59 +00004360 }
4361 }
4362
4363 // TODO: If the constant is exactly representable, is it always OK to do
4364 // equality compares as integer?
4365 }
4366
Arch D. Robison8ed08542015-09-15 17:51:59 +00004367 // Check to see that the input is converted from an integer type that is small
4368 // enough that preserves all bits. TODO: check here for "known" sign bits.
4369 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4370 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00004371
Arch D. Robison8ed08542015-09-15 17:51:59 +00004372 // Following test does NOT adjust InputSize downwards for signed inputs,
4373 // because the most negative value still requires all the mantissa bits
4374 // to distinguish it from one less than that value.
4375 if ((int)InputSize > MantissaWidth) {
4376 // Conversion would lose accuracy. Check if loss can impact comparison.
4377 int Exp = ilogb(RHS);
4378 if (Exp == APFloat::IEK_Inf) {
4379 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
4380 if (MaxExponent < (int)InputSize - !LHSUnsigned)
4381 // Conversion could create infinity.
4382 return nullptr;
4383 } else {
4384 // Note that if RHS is zero or NaN, then Exp is negative
4385 // and first condition is trivially false.
4386 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
4387 // Conversion could affect comparison.
4388 return nullptr;
4389 }
4390 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004391
Chris Lattner2188e402010-01-04 07:37:31 +00004392 // Otherwise, we can potentially simplify the comparison. We know that it
4393 // will always come through as an integer value and we know the constant is
4394 // not a NAN (it would have been previously simplified).
4395 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00004396
Chris Lattner2188e402010-01-04 07:37:31 +00004397 ICmpInst::Predicate Pred;
4398 switch (I.getPredicate()) {
4399 default: llvm_unreachable("Unexpected predicate!");
4400 case FCmpInst::FCMP_UEQ:
4401 case FCmpInst::FCMP_OEQ:
4402 Pred = ICmpInst::ICMP_EQ;
4403 break;
4404 case FCmpInst::FCMP_UGT:
4405 case FCmpInst::FCMP_OGT:
4406 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4407 break;
4408 case FCmpInst::FCMP_UGE:
4409 case FCmpInst::FCMP_OGE:
4410 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4411 break;
4412 case FCmpInst::FCMP_ULT:
4413 case FCmpInst::FCMP_OLT:
4414 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4415 break;
4416 case FCmpInst::FCMP_ULE:
4417 case FCmpInst::FCMP_OLE:
4418 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4419 break;
4420 case FCmpInst::FCMP_UNE:
4421 case FCmpInst::FCMP_ONE:
4422 Pred = ICmpInst::ICMP_NE;
4423 break;
4424 case FCmpInst::FCMP_ORD:
Sanjay Patel4b198802016-02-01 22:23:39 +00004425 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004426 case FCmpInst::FCMP_UNO:
Sanjay Patel4b198802016-02-01 22:23:39 +00004427 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004428 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004429
Chris Lattner2188e402010-01-04 07:37:31 +00004430 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004431
Chris Lattner2188e402010-01-04 07:37:31 +00004432 // See if the FP constant is too large for the integer. For example,
4433 // comparing an i8 to 300.0.
4434 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004435
Chris Lattner2188e402010-01-04 07:37:31 +00004436 if (!LHSUnsigned) {
4437 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4438 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004439 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004440 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4441 APFloat::rmNearestTiesToEven);
4442 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4443 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4444 Pred == ICmpInst::ICMP_SLE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004445 return replaceInstUsesWith(I, Builder->getTrue());
4446 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004447 }
4448 } else {
4449 // If the RHS value is > UnsignedMax, fold the comparison. This handles
4450 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004451 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004452 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4453 APFloat::rmNearestTiesToEven);
4454 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
4455 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
4456 Pred == ICmpInst::ICMP_ULE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004457 return replaceInstUsesWith(I, Builder->getTrue());
4458 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004459 }
4460 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004461
Chris Lattner2188e402010-01-04 07:37:31 +00004462 if (!LHSUnsigned) {
4463 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004464 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004465 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4466 APFloat::rmNearestTiesToEven);
4467 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4468 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4469 Pred == ICmpInst::ICMP_SGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004470 return replaceInstUsesWith(I, Builder->getTrue());
4471 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004472 }
Devang Patel698452b2012-02-13 23:05:18 +00004473 } else {
4474 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004475 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00004476 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
4477 APFloat::rmNearestTiesToEven);
4478 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
4479 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
4480 Pred == ICmpInst::ICMP_UGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004481 return replaceInstUsesWith(I, Builder->getTrue());
4482 return replaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00004483 }
Chris Lattner2188e402010-01-04 07:37:31 +00004484 }
4485
4486 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4487 // [0, UMAX], but it may still be fractional. See if it is fractional by
4488 // casting the FP value to the integer value and back, checking for equality.
4489 // Don't do this for zero, because -0.0 is not fractional.
4490 Constant *RHSInt = LHSUnsigned
4491 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4492 : ConstantExpr::getFPToSI(RHSC, IntTy);
4493 if (!RHS.isZero()) {
4494 bool Equal = LHSUnsigned
4495 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4496 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4497 if (!Equal) {
4498 // If we had a comparison against a fractional value, we have to adjust
4499 // the compare predicate and sometimes the value. RHSC is rounded towards
4500 // zero at this point.
4501 switch (Pred) {
4502 default: llvm_unreachable("Unexpected integer comparison!");
4503 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Sanjay Patel4b198802016-02-01 22:23:39 +00004504 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004505 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Sanjay Patel4b198802016-02-01 22:23:39 +00004506 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004507 case ICmpInst::ICMP_ULE:
4508 // (float)int <= 4.4 --> int <= 4
4509 // (float)int <= -4.4 --> false
4510 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004511 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004512 break;
4513 case ICmpInst::ICMP_SLE:
4514 // (float)int <= 4.4 --> int <= 4
4515 // (float)int <= -4.4 --> int < -4
4516 if (RHS.isNegative())
4517 Pred = ICmpInst::ICMP_SLT;
4518 break;
4519 case ICmpInst::ICMP_ULT:
4520 // (float)int < -4.4 --> false
4521 // (float)int < 4.4 --> int <= 4
4522 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004523 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004524 Pred = ICmpInst::ICMP_ULE;
4525 break;
4526 case ICmpInst::ICMP_SLT:
4527 // (float)int < -4.4 --> int < -4
4528 // (float)int < 4.4 --> int <= 4
4529 if (!RHS.isNegative())
4530 Pred = ICmpInst::ICMP_SLE;
4531 break;
4532 case ICmpInst::ICMP_UGT:
4533 // (float)int > 4.4 --> int > 4
4534 // (float)int > -4.4 --> true
4535 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004536 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004537 break;
4538 case ICmpInst::ICMP_SGT:
4539 // (float)int > 4.4 --> int > 4
4540 // (float)int > -4.4 --> int >= -4
4541 if (RHS.isNegative())
4542 Pred = ICmpInst::ICMP_SGE;
4543 break;
4544 case ICmpInst::ICMP_UGE:
4545 // (float)int >= -4.4 --> true
4546 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00004547 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004548 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004549 Pred = ICmpInst::ICMP_UGT;
4550 break;
4551 case ICmpInst::ICMP_SGE:
4552 // (float)int >= -4.4 --> int >= -4
4553 // (float)int >= 4.4 --> int > 4
4554 if (!RHS.isNegative())
4555 Pred = ICmpInst::ICMP_SGT;
4556 break;
4557 }
4558 }
4559 }
4560
4561 // Lower this FP comparison into an appropriate integer version of the
4562 // comparison.
4563 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4564}
4565
4566Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4567 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004568
Chris Lattner2188e402010-01-04 07:37:31 +00004569 /// Orders the operands of the compare so that they are listed from most
4570 /// complex to least complex. This puts constants before unary operators,
4571 /// before binary operators.
4572 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4573 I.swapOperands();
4574 Changed = true;
4575 }
4576
4577 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004578
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004579 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
4580 I.getFastMathFlags(), DL, TLI, DT, AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004581 return replaceInstUsesWith(I, V);
Chris Lattner2188e402010-01-04 07:37:31 +00004582
4583 // Simplify 'fcmp pred X, X'
4584 if (Op0 == Op1) {
4585 switch (I.getPredicate()) {
4586 default: llvm_unreachable("Unknown predicate!");
4587 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4588 case FCmpInst::FCMP_ULT: // True if unordered or less than
4589 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4590 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4591 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4592 I.setPredicate(FCmpInst::FCMP_UNO);
4593 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4594 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004595
Chris Lattner2188e402010-01-04 07:37:31 +00004596 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4597 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4598 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4599 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4600 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4601 I.setPredicate(FCmpInst::FCMP_ORD);
4602 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4603 return &I;
4604 }
4605 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004606
James Molloy2b21a7c2015-05-20 18:41:25 +00004607 // Test if the FCmpInst instruction is used exclusively by a select as
4608 // part of a minimum or maximum operation. If so, refrain from doing
4609 // any other folding. This helps out other analyses which understand
4610 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4611 // and CodeGen. And in this case, at least one of the comparison
4612 // operands has at least one user besides the compare (the select),
4613 // which would often largely negate the benefit of folding anyway.
4614 if (I.hasOneUse())
4615 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4616 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4617 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4618 return nullptr;
4619
Chris Lattner2188e402010-01-04 07:37:31 +00004620 // Handle fcmp with constant RHS
4621 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4622 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4623 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004624 case Instruction::FPExt: {
4625 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4626 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4627 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4628 if (!RHSF)
4629 break;
4630
4631 const fltSemantics *Sem;
4632 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004633 if (LHSExt->getSrcTy()->isHalfTy())
4634 Sem = &APFloat::IEEEhalf;
4635 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004636 Sem = &APFloat::IEEEsingle;
4637 else if (LHSExt->getSrcTy()->isDoubleTy())
4638 Sem = &APFloat::IEEEdouble;
4639 else if (LHSExt->getSrcTy()->isFP128Ty())
4640 Sem = &APFloat::IEEEquad;
4641 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
4642 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004643 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
4644 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004645 else
4646 break;
4647
4648 bool Lossy;
4649 APFloat F = RHSF->getValueAPF();
4650 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4651
Jim Grosbach24ff8342011-09-30 18:45:50 +00004652 // Avoid lossy conversions and denormals. Zero is a special case
4653 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004654 APFloat Fabs = F;
4655 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004656 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004657 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4658 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004659
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004660 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4661 ConstantFP::get(RHSC->getContext(), F));
4662 break;
4663 }
Chris Lattner2188e402010-01-04 07:37:31 +00004664 case Instruction::PHI:
4665 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4666 // block. If in the same block, we're encouraging jump threading. If
4667 // not, we are just pessimizing the code by making an i1 phi.
4668 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004669 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004670 return NV;
4671 break;
4672 case Instruction::SIToFP:
4673 case Instruction::UIToFP:
Sanjay Patel43395062016-07-21 18:07:40 +00004674 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
Chris Lattner2188e402010-01-04 07:37:31 +00004675 return NV;
4676 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004677 case Instruction::FSub: {
4678 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4679 Value *Op;
4680 if (match(LHSI, m_FNeg(m_Value(Op))))
4681 return new FCmpInst(I.getSwappedPredicate(), Op,
4682 ConstantExpr::getFNeg(RHSC));
4683 break;
4684 }
Dan Gohman94732022010-02-24 06:46:09 +00004685 case Instruction::Load:
4686 if (GetElementPtrInst *GEP =
4687 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4688 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4689 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4690 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00004691 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Dan Gohman94732022010-02-24 06:46:09 +00004692 return Res;
4693 }
4694 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004695 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004696 if (!RHSC->isNullValue())
4697 break;
4698
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004699 CallInst *CI = cast<CallInst>(LHSI);
David Majnemerb4b27232016-04-19 19:10:21 +00004700 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer2e02ba72016-04-15 17:21:03 +00004701 if (IID != Intrinsic::fabs)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004702 break;
4703
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004704 // Various optimization for fabs compared with zero.
David Majnemer2e02ba72016-04-15 17:21:03 +00004705 switch (I.getPredicate()) {
4706 default:
4707 break;
4708 // fabs(x) < 0 --> false
4709 case FCmpInst::FCMP_OLT:
4710 llvm_unreachable("handled by SimplifyFCmpInst");
4711 // fabs(x) > 0 --> x != 0
4712 case FCmpInst::FCMP_OGT:
4713 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
4714 // fabs(x) <= 0 --> x == 0
4715 case FCmpInst::FCMP_OLE:
4716 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
4717 // fabs(x) >= 0 --> !isnan(x)
4718 case FCmpInst::FCMP_OGE:
4719 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
4720 // fabs(x) == 0 --> x == 0
4721 // fabs(x) != 0 --> x != 0
4722 case FCmpInst::FCMP_OEQ:
4723 case FCmpInst::FCMP_UEQ:
4724 case FCmpInst::FCMP_ONE:
4725 case FCmpInst::FCMP_UNE:
4726 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004727 }
4728 }
Chris Lattner2188e402010-01-04 07:37:31 +00004729 }
Chris Lattner2188e402010-01-04 07:37:31 +00004730 }
4731
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004732 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004733 Value *X, *Y;
4734 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004735 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004736
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004737 // fcmp (fpext x), (fpext y) -> fcmp x, y
4738 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4739 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4740 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4741 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4742 RHSExt->getOperand(0));
4743
Craig Topperf40110f2014-04-25 05:29:35 +00004744 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004745}