blob: cb9c7e5b893bccc56850d50d9c3b1a2ed5f7d978 [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".
Chris Lattner2188e402010-01-04 07:37:31 +0000234Instruction *InstCombiner::
235FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
236 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattnerfe741762012-01-31 02:55:06 +0000237 Constant *Init = GV->getInitializer();
238 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
Craig Topperf40110f2014-04-25 05:29:35 +0000239 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000240
Chris Lattnerfe741762012-01-31 02:55:06 +0000241 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +0000242 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000243
Chris Lattner2188e402010-01-04 07:37:31 +0000244 // There are many forms of this optimization we can handle, for now, just do
245 // the simple index into a single-dimensional array.
246 //
247 // Require: GEP GV, 0, i {{, constant indices}}
248 if (GEP->getNumOperands() < 3 ||
249 !isa<ConstantInt>(GEP->getOperand(1)) ||
250 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
251 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000252 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000253
254 // Check that indices after the variable are constants and in-range for the
255 // type they index. Collect the indices. This is typically for arrays of
256 // structs.
257 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000258
Chris Lattnerfe741762012-01-31 02:55:06 +0000259 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000260 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
261 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000262 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000263
Chris Lattner2188e402010-01-04 07:37:31 +0000264 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000265 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000266
Chris Lattner229907c2011-07-18 04:54:35 +0000267 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000268 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000269 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000270 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000271 EltTy = ATy->getElementType();
272 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000273 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000274 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000275
Chris Lattner2188e402010-01-04 07:37:31 +0000276 LaterIndices.push_back(IdxVal);
277 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000278
Chris Lattner2188e402010-01-04 07:37:31 +0000279 enum { Overdefined = -3, Undefined = -2 };
280
281 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000282
Chris Lattner2188e402010-01-04 07:37:31 +0000283 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
284 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
285 // and 87 is the second (and last) index. FirstTrueElement is -2 when
286 // undefined, otherwise set to the first true element. SecondTrueElement is
287 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
288 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
289
290 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
291 // form "i != 47 & i != 87". Same state transitions as for true elements.
292 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000293
Chris Lattner2188e402010-01-04 07:37:31 +0000294 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
295 /// define a state machine that triggers for ranges of values that the index
296 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
297 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
298 /// index in the range (inclusive). We use -2 for undefined here because we
299 /// use relative comparisons and don't want 0-1 to match -1.
300 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000301
Chris Lattner2188e402010-01-04 07:37:31 +0000302 // MagicBitvector - This is a magic bitvector where we set a bit if the
303 // comparison is true for element 'i'. If there are 64 elements or less in
304 // the array, this will fully represent all the comparison results.
305 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000306
Chris Lattner2188e402010-01-04 07:37:31 +0000307 // Scan the array and see if one of our patterns matches.
308 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000309 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
310 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000311 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000312
Chris Lattner2188e402010-01-04 07:37:31 +0000313 // If this is indexing an array of structures, get the structure element.
314 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000315 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000316
Chris Lattner2188e402010-01-04 07:37:31 +0000317 // If the element is masked, handle it.
318 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000319
Chris Lattner2188e402010-01-04 07:37:31 +0000320 // Find out if the comparison would be true or false for the i'th element.
321 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000322 CompareRHS, DL, TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000323 // If the result is undef for this element, ignore it.
324 if (isa<UndefValue>(C)) {
325 // Extend range state machines to cover this element in case there is an
326 // undef in the middle of the range.
327 if (TrueRangeEnd == (int)i-1)
328 TrueRangeEnd = i;
329 if (FalseRangeEnd == (int)i-1)
330 FalseRangeEnd = i;
331 continue;
332 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000333
Chris Lattner2188e402010-01-04 07:37:31 +0000334 // If we can't compute the result for any of the elements, we have to give
335 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000336 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000337
Chris Lattner2188e402010-01-04 07:37:31 +0000338 // Otherwise, we know if the comparison is true or false for this element,
339 // update our state machines.
340 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000341
Chris Lattner2188e402010-01-04 07:37:31 +0000342 // State machine for single/double/range index comparison.
343 if (IsTrueForElt) {
344 // Update the TrueElement state machine.
345 if (FirstTrueElement == Undefined)
346 FirstTrueElement = TrueRangeEnd = i; // First true element.
347 else {
348 // Update double-compare state machine.
349 if (SecondTrueElement == Undefined)
350 SecondTrueElement = i;
351 else
352 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000353
Chris Lattner2188e402010-01-04 07:37:31 +0000354 // Update range state machine.
355 if (TrueRangeEnd == (int)i-1)
356 TrueRangeEnd = i;
357 else
358 TrueRangeEnd = Overdefined;
359 }
360 } else {
361 // Update the FalseElement state machine.
362 if (FirstFalseElement == Undefined)
363 FirstFalseElement = FalseRangeEnd = i; // First false element.
364 else {
365 // Update double-compare state machine.
366 if (SecondFalseElement == Undefined)
367 SecondFalseElement = i;
368 else
369 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000370
Chris Lattner2188e402010-01-04 07:37:31 +0000371 // Update range state machine.
372 if (FalseRangeEnd == (int)i-1)
373 FalseRangeEnd = i;
374 else
375 FalseRangeEnd = Overdefined;
376 }
377 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000378
Chris Lattner2188e402010-01-04 07:37:31 +0000379 // If this element is in range, update our magic bitvector.
380 if (i < 64 && IsTrueForElt)
381 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000382
Chris Lattner2188e402010-01-04 07:37:31 +0000383 // If all of our states become overdefined, bail out early. Since the
384 // predicate is expensive, only check it every 8 elements. This is only
385 // really useful for really huge arrays.
386 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
387 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
388 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000389 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000390 }
391
392 // Now that we've scanned the entire array, emit our new comparison(s). We
393 // order the state machines in complexity of the generated code.
394 Value *Idx = GEP->getOperand(2);
395
Matt Arsenault5aeae182013-08-19 21:40:31 +0000396 // If the index is larger than the pointer size of the target, truncate the
397 // index down like the GEP would do implicitly. We don't have to do this for
398 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000399 if (!GEP->isInBounds()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000400 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000401 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
402 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
403 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
404 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000405
Chris Lattner2188e402010-01-04 07:37:31 +0000406 // If the comparison is only true for one or two elements, emit direct
407 // comparisons.
408 if (SecondTrueElement != Overdefined) {
409 // None true -> false.
410 if (FirstTrueElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000411 return replaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000412
Chris Lattner2188e402010-01-04 07:37:31 +0000413 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000414
Chris Lattner2188e402010-01-04 07:37:31 +0000415 // True for one element -> 'i == 47'.
416 if (SecondTrueElement == Undefined)
417 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000418
Chris Lattner2188e402010-01-04 07:37:31 +0000419 // True for two elements -> 'i == 47 | i == 72'.
420 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
421 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
422 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
423 return BinaryOperator::CreateOr(C1, C2);
424 }
425
426 // If the comparison is only false for one or two elements, emit direct
427 // comparisons.
428 if (SecondFalseElement != Overdefined) {
429 // None false -> true.
430 if (FirstFalseElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000431 return replaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000432
Chris Lattner2188e402010-01-04 07:37:31 +0000433 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
434
435 // False for one element -> 'i != 47'.
436 if (SecondFalseElement == Undefined)
437 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000438
Chris Lattner2188e402010-01-04 07:37:31 +0000439 // False for two elements -> 'i != 47 & i != 72'.
440 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
441 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
442 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
443 return BinaryOperator::CreateAnd(C1, C2);
444 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000445
Chris Lattner2188e402010-01-04 07:37:31 +0000446 // If the comparison can be replaced with a range comparison for the elements
447 // where it is true, emit the range check.
448 if (TrueRangeEnd != Overdefined) {
449 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000450
Chris Lattner2188e402010-01-04 07:37:31 +0000451 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
452 if (FirstTrueElement) {
453 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
454 Idx = Builder->CreateAdd(Idx, Offs);
455 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000456
Chris Lattner2188e402010-01-04 07:37:31 +0000457 Value *End = ConstantInt::get(Idx->getType(),
458 TrueRangeEnd-FirstTrueElement+1);
459 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
460 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000461
Chris Lattner2188e402010-01-04 07:37:31 +0000462 // False range check.
463 if (FalseRangeEnd != Overdefined) {
464 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
465 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
466 if (FirstFalseElement) {
467 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
468 Idx = Builder->CreateAdd(Idx, Offs);
469 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000470
Chris Lattner2188e402010-01-04 07:37:31 +0000471 Value *End = ConstantInt::get(Idx->getType(),
472 FalseRangeEnd-FirstFalseElement);
473 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
474 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000475
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000476 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000477 // of this load, replace it with computation that does:
478 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000479 {
Craig Topperf40110f2014-04-25 05:29:35 +0000480 Type *Ty = nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000481
482 // Look for an appropriate type:
483 // - The type of Idx if the magic fits
484 // - The smallest fitting legal type if we have a DataLayout
485 // - Default to i32
486 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
487 Ty = Idx->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000488 else
489 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000490
Craig Topperf40110f2014-04-25 05:29:35 +0000491 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000492 Value *V = Builder->CreateIntCast(Idx, Ty, false);
493 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
494 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
495 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
496 }
Chris Lattner2188e402010-01-04 07:37:31 +0000497 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000498
Craig Topperf40110f2014-04-25 05:29:35 +0000499 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000500}
501
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000502/// Return a value that can be used to compare the *offset* implied by a GEP to
503/// zero. For example, if we have &A[i], we want to return 'i' for
504/// "icmp ne i, 0". Note that, in general, indices can be complex, and scales
505/// are involved. The above expression would also be legal to codegen as
506/// "icmp ne (i*4), 0" (assuming A is a pointer to i32).
507/// This latter form is less amenable to optimization though, and we are allowed
Chris Lattner2188e402010-01-04 07:37:31 +0000508/// to generate the first by knowing that pointer arithmetic doesn't overflow.
509///
510/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000511///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000512static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
513 const DataLayout &DL) {
Chris Lattner2188e402010-01-04 07:37:31 +0000514 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000515
Chris Lattner2188e402010-01-04 07:37:31 +0000516 // Check to see if this gep only has a single variable index. If so, and if
517 // any constant indices are a multiple of its scale, then we can compute this
518 // in terms of the scale of the variable index. For example, if the GEP
519 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
520 // because the expression will cross zero at the same point.
521 unsigned i, e = GEP->getNumOperands();
522 int64_t Offset = 0;
523 for (i = 1; i != e; ++i, ++GTI) {
524 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
525 // Compute the aggregate offset of constant indices.
526 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000527
Chris Lattner2188e402010-01-04 07:37:31 +0000528 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000529 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000530 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000531 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000532 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000533 Offset += Size*CI->getSExtValue();
534 }
535 } else {
536 // Found our variable index.
537 break;
538 }
539 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000540
Chris Lattner2188e402010-01-04 07:37:31 +0000541 // If there are no variable indices, we must have a constant offset, just
542 // evaluate it the general way.
Craig Topperf40110f2014-04-25 05:29:35 +0000543 if (i == e) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000544
Chris Lattner2188e402010-01-04 07:37:31 +0000545 Value *VariableIdx = GEP->getOperand(i);
546 // Determine the scale factor of the variable element. For example, this is
547 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000548 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000549
Chris Lattner2188e402010-01-04 07:37:31 +0000550 // Verify that there are no other variable indices. If so, emit the hard way.
551 for (++i, ++GTI; i != e; ++i, ++GTI) {
552 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000553 if (!CI) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000554
Chris Lattner2188e402010-01-04 07:37:31 +0000555 // Compute the aggregate offset of constant indices.
556 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000557
Chris Lattner2188e402010-01-04 07:37:31 +0000558 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000559 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000560 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000561 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000562 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000563 Offset += Size*CI->getSExtValue();
564 }
565 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000566
Chris Lattner2188e402010-01-04 07:37:31 +0000567 // Okay, we know we have a single variable index, which must be a
568 // pointer/array/vector index. If there is no offset, life is simple, return
569 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000570 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000571 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000572 if (Offset == 0) {
573 // Cast to intptrty in case a truncation occurs. If an extension is needed,
574 // we don't need to bother extending: the extension won't affect where the
575 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000576 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000577 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
578 }
Chris Lattner2188e402010-01-04 07:37:31 +0000579 return VariableIdx;
580 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000581
Chris Lattner2188e402010-01-04 07:37:31 +0000582 // Otherwise, there is an index. The computation we will do will be modulo
583 // the pointer size, so get it.
584 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000585
Chris Lattner2188e402010-01-04 07:37:31 +0000586 Offset &= PtrSizeMask;
587 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000588
Chris Lattner2188e402010-01-04 07:37:31 +0000589 // To do this transformation, any constant index must be a multiple of the
590 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
591 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
592 // multiple of the variable scale.
593 int64_t NewOffs = Offset / (int64_t)VariableScale;
594 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000595 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000596
Chris Lattner2188e402010-01-04 07:37:31 +0000597 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000598 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000599 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
600 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000601 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000602 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000603}
604
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000605/// Returns true if we can rewrite Start as a GEP with pointer Base
606/// and some integer offset. The nodes that need to be re-written
607/// for this transformation will be added to Explored.
608static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
609 const DataLayout &DL,
610 SetVector<Value *> &Explored) {
611 SmallVector<Value *, 16> WorkList(1, Start);
612 Explored.insert(Base);
613
614 // The following traversal gives us an order which can be used
615 // when doing the final transformation. Since in the final
616 // transformation we create the PHI replacement instructions first,
617 // we don't have to get them in any particular order.
618 //
619 // However, for other instructions we will have to traverse the
620 // operands of an instruction first, which means that we have to
621 // do a post-order traversal.
622 while (!WorkList.empty()) {
623 SetVector<PHINode *> PHIs;
624
625 while (!WorkList.empty()) {
626 if (Explored.size() >= 100)
627 return false;
628
629 Value *V = WorkList.back();
630
631 if (Explored.count(V) != 0) {
632 WorkList.pop_back();
633 continue;
634 }
635
636 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
637 !isa<GEPOperator>(V) && !isa<PHINode>(V))
638 // We've found some value that we can't explore which is different from
639 // the base. Therefore we can't do this transformation.
640 return false;
641
642 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
643 auto *CI = dyn_cast<CastInst>(V);
644 if (!CI->isNoopCast(DL))
645 return false;
646
647 if (Explored.count(CI->getOperand(0)) == 0)
648 WorkList.push_back(CI->getOperand(0));
649 }
650
651 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
652 // We're limiting the GEP to having one index. This will preserve
653 // the original pointer type. We could handle more cases in the
654 // future.
655 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
656 GEP->getType() != Start->getType())
657 return false;
658
659 if (Explored.count(GEP->getOperand(0)) == 0)
660 WorkList.push_back(GEP->getOperand(0));
661 }
662
663 if (WorkList.back() == V) {
664 WorkList.pop_back();
665 // We've finished visiting this node, mark it as such.
666 Explored.insert(V);
667 }
668
669 if (auto *PN = dyn_cast<PHINode>(V)) {
David Majnemercdf28732016-03-19 04:39:52 +0000670 // We cannot transform PHIs on unsplittable basic blocks.
671 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
672 return false;
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000673 Explored.insert(PN);
674 PHIs.insert(PN);
675 }
676 }
677
678 // Explore the PHI nodes further.
679 for (auto *PN : PHIs)
680 for (Value *Op : PN->incoming_values())
681 if (Explored.count(Op) == 0)
682 WorkList.push_back(Op);
683 }
684
685 // Make sure that we can do this. Since we can't insert GEPs in a basic
686 // block before a PHI node, we can't easily do this transformation if
687 // we have PHI node users of transformed instructions.
688 for (Value *Val : Explored) {
689 for (Value *Use : Val->uses()) {
690
691 auto *PHI = dyn_cast<PHINode>(Use);
692 auto *Inst = dyn_cast<Instruction>(Val);
693
694 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
695 Explored.count(PHI) == 0)
696 continue;
697
698 if (PHI->getParent() == Inst->getParent())
699 return false;
700 }
701 }
702 return true;
703}
704
705// Sets the appropriate insert point on Builder where we can add
706// a replacement Instruction for V (if that is possible).
707static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
708 bool Before = true) {
709 if (auto *PHI = dyn_cast<PHINode>(V)) {
710 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
711 return;
712 }
713 if (auto *I = dyn_cast<Instruction>(V)) {
714 if (!Before)
715 I = &*std::next(I->getIterator());
716 Builder.SetInsertPoint(I);
717 return;
718 }
719 if (auto *A = dyn_cast<Argument>(V)) {
720 // Set the insertion point in the entry block.
721 BasicBlock &Entry = A->getParent()->getEntryBlock();
722 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
723 return;
724 }
725 // Otherwise, this is a constant and we don't need to set a new
726 // insertion point.
727 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
728}
729
730/// Returns a re-written value of Start as an indexed GEP using Base as a
731/// pointer.
732static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
733 const DataLayout &DL,
734 SetVector<Value *> &Explored) {
735 // Perform all the substitutions. This is a bit tricky because we can
736 // have cycles in our use-def chains.
737 // 1. Create the PHI nodes without any incoming values.
738 // 2. Create all the other values.
739 // 3. Add the edges for the PHI nodes.
740 // 4. Emit GEPs to get the original pointers.
741 // 5. Remove the original instructions.
742 Type *IndexType = IntegerType::get(
743 Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType()));
744
745 DenseMap<Value *, Value *> NewInsts;
746 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
747
748 // Create the new PHI nodes, without adding any incoming values.
749 for (Value *Val : Explored) {
750 if (Val == Base)
751 continue;
752 // Create empty phi nodes. This avoids cyclic dependencies when creating
753 // the remaining instructions.
754 if (auto *PHI = dyn_cast<PHINode>(Val))
755 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
756 PHI->getName() + ".idx", PHI);
757 }
758 IRBuilder<> Builder(Base->getContext());
759
760 // Create all the other instructions.
761 for (Value *Val : Explored) {
762
763 if (NewInsts.find(Val) != NewInsts.end())
764 continue;
765
766 if (auto *CI = dyn_cast<CastInst>(Val)) {
767 NewInsts[CI] = NewInsts[CI->getOperand(0)];
768 continue;
769 }
770 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
771 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
772 : GEP->getOperand(1);
773 setInsertionPoint(Builder, GEP);
774 // Indices might need to be sign extended. GEPs will magically do
775 // this, but we need to do it ourselves here.
776 if (Index->getType()->getScalarSizeInBits() !=
777 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
778 Index = Builder.CreateSExtOrTrunc(
779 Index, NewInsts[GEP->getOperand(0)]->getType(),
780 GEP->getOperand(0)->getName() + ".sext");
781 }
782
783 auto *Op = NewInsts[GEP->getOperand(0)];
784 if (isa<ConstantInt>(Op) && dyn_cast<ConstantInt>(Op)->isZero())
785 NewInsts[GEP] = Index;
786 else
787 NewInsts[GEP] = Builder.CreateNSWAdd(
788 Op, Index, GEP->getOperand(0)->getName() + ".add");
789 continue;
790 }
791 if (isa<PHINode>(Val))
792 continue;
793
794 llvm_unreachable("Unexpected instruction type");
795 }
796
797 // Add the incoming values to the PHI nodes.
798 for (Value *Val : Explored) {
799 if (Val == Base)
800 continue;
801 // All the instructions have been created, we can now add edges to the
802 // phi nodes.
803 if (auto *PHI = dyn_cast<PHINode>(Val)) {
804 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
805 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
806 Value *NewIncoming = PHI->getIncomingValue(I);
807
808 if (NewInsts.find(NewIncoming) != NewInsts.end())
809 NewIncoming = NewInsts[NewIncoming];
810
811 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
812 }
813 }
814 }
815
816 for (Value *Val : Explored) {
817 if (Val == Base)
818 continue;
819
820 // Depending on the type, for external users we have to emit
821 // a GEP or a GEP + ptrtoint.
822 setInsertionPoint(Builder, Val, false);
823
824 // If required, create an inttoptr instruction for Base.
825 Value *NewBase = Base;
826 if (!Base->getType()->isPointerTy())
827 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
828 Start->getName() + "to.ptr");
829
830 Value *GEP = Builder.CreateInBoundsGEP(
831 Start->getType()->getPointerElementType(), NewBase,
832 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
833
834 if (!Val->getType()->isPointerTy()) {
835 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
836 Val->getName() + ".conv");
837 GEP = Cast;
838 }
839 Val->replaceAllUsesWith(GEP);
840 }
841
842 return NewInsts[Start];
843}
844
845/// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
846/// the input Value as a constant indexed GEP. Returns a pair containing
847/// the GEPs Pointer and Index.
848static std::pair<Value *, Value *>
849getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
850 Type *IndexType = IntegerType::get(V->getContext(),
851 DL.getPointerTypeSizeInBits(V->getType()));
852
853 Constant *Index = ConstantInt::getNullValue(IndexType);
854 while (true) {
855 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
856 // We accept only inbouds GEPs here to exclude the possibility of
857 // overflow.
858 if (!GEP->isInBounds())
859 break;
860 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
861 GEP->getType() == V->getType()) {
862 V = GEP->getOperand(0);
863 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
864 Index = ConstantExpr::getAdd(
865 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
866 continue;
867 }
868 break;
869 }
870 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
871 if (!CI->isNoopCast(DL))
872 break;
873 V = CI->getOperand(0);
874 continue;
875 }
876 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
877 if (!CI->isNoopCast(DL))
878 break;
879 V = CI->getOperand(0);
880 continue;
881 }
882 break;
883 }
884 return {V, Index};
885}
886
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000887/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
888/// We can look through PHIs, GEPs and casts in order to determine a common base
889/// between GEPLHS and RHS.
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000890static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
891 ICmpInst::Predicate Cond,
892 const DataLayout &DL) {
893 if (!GEPLHS->hasAllConstantIndices())
894 return nullptr;
895
896 Value *PtrBase, *Index;
897 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
898
899 // The set of nodes that will take part in this transformation.
900 SetVector<Value *> Nodes;
901
902 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
903 return nullptr;
904
905 // We know we can re-write this as
906 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
907 // Since we've only looked through inbouds GEPs we know that we
908 // can't have overflow on either side. We can therefore re-write
909 // this as:
910 // OFFSET1 cmp OFFSET2
911 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
912
913 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
914 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
915 // offset. Since Index is the offset of LHS to the base pointer, we will now
916 // compare the offsets instead of comparing the pointers.
917 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
918}
919
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000920/// Fold comparisons between a GEP instruction and something else. At this point
921/// we know that the GEP is on the LHS of the comparison.
Chris Lattner2188e402010-01-04 07:37:31 +0000922Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
923 ICmpInst::Predicate Cond,
924 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000925 // Don't transform signed compares of GEPs into index compares. Even if the
926 // GEP is inbounds, the final add of the base pointer can have signed overflow
927 // and would change the result of the icmp.
928 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000929 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000930 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000931 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000932
Matt Arsenault44f60d02014-06-09 19:20:29 +0000933 // Look through bitcasts and addrspacecasts. We do not however want to remove
934 // 0 GEPs.
935 if (!isa<GetElementPtrInst>(RHS))
936 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000937
938 Value *PtrBase = GEPLHS->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000939 if (PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000940 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
941 // This transformation (ignoring the base and scales) is valid because we
942 // know pointers can't overflow since the gep is inbounds. See if we can
943 // output an optimized form.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000944 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this, DL);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000945
Chris Lattner2188e402010-01-04 07:37:31 +0000946 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000947 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000948 Offset = EmitGEPOffset(GEPLHS);
949 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
950 Constant::getNullValue(Offset->getType()));
951 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
952 // If the base pointers are different, but the indices are the same, just
953 // compare the base pointer.
954 if (PtrBase != GEPRHS->getOperand(0)) {
955 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
956 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
957 GEPRHS->getOperand(0)->getType();
958 if (IndicesTheSame)
959 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
960 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
961 IndicesTheSame = false;
962 break;
963 }
964
965 // If all indices are the same, just compare the base pointers.
966 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000967 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000968
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000969 // If we're comparing GEPs with two base pointers that only differ in type
970 // and both GEPs have only constant indices or just one use, then fold
971 // the compare with the adjusted indices.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000972 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000973 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
974 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
975 PtrBase->stripPointerCasts() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000976 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000977 Value *LOffset = EmitGEPOffset(GEPLHS);
978 Value *ROffset = EmitGEPOffset(GEPRHS);
979
980 // If we looked through an addrspacecast between different sized address
981 // spaces, the LHS and RHS pointers are different sized
982 // integers. Truncate to the smaller one.
983 Type *LHSIndexTy = LOffset->getType();
984 Type *RHSIndexTy = ROffset->getType();
985 if (LHSIndexTy != RHSIndexTy) {
986 if (LHSIndexTy->getPrimitiveSizeInBits() <
987 RHSIndexTy->getPrimitiveSizeInBits()) {
988 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
989 } else
990 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
991 }
992
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000993 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000994 LOffset, ROffset);
Sanjay Patel4b198802016-02-01 22:23:39 +0000995 return replaceInstUsesWith(I, Cmp);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000996 }
997
Chris Lattner2188e402010-01-04 07:37:31 +0000998 // Otherwise, the base pointers are different and the indices are
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000999 // different. Try convert this to an indexed compare by looking through
1000 // PHIs/casts.
1001 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +00001002 }
1003
1004 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001005 if (GEPLHS->hasAllZeroIndices())
Chris Lattner2188e402010-01-04 07:37:31 +00001006 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +00001007 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +00001008
1009 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001010 if (GEPRHS->hasAllZeroIndices())
Chris Lattner2188e402010-01-04 07:37:31 +00001011 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
1012
Stuart Hastings66a82b92011-05-14 05:55:10 +00001013 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +00001014 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
1015 // If the GEPs only differ by one index, compare it.
1016 unsigned NumDifferences = 0; // Keep track of # differences.
1017 unsigned DiffOperand = 0; // The operand that differs.
1018 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
1019 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
1020 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
1021 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
1022 // Irreconcilable differences.
1023 NumDifferences = 2;
1024 break;
1025 } else {
1026 if (NumDifferences++) break;
1027 DiffOperand = i;
1028 }
1029 }
1030
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +00001031 if (NumDifferences == 0) // SAME GEP?
Sanjay Patel4b198802016-02-01 22:23:39 +00001032 return replaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +00001033 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +00001034
Stuart Hastings66a82b92011-05-14 05:55:10 +00001035 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +00001036 Value *LHSV = GEPLHS->getOperand(DiffOperand);
1037 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1038 // Make sure we do a signed comparison here.
1039 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
1040 }
1041 }
1042
1043 // Only lower this if the icmp is the only user of the GEP or if we expect
1044 // the result to fold to a constant!
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001045 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner2188e402010-01-04 07:37:31 +00001046 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1047 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
1048 Value *L = EmitGEPOffset(GEPLHS);
1049 Value *R = EmitGEPOffset(GEPRHS);
1050 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1051 }
1052 }
Silviu Barangaf29dfd32016-01-15 15:52:05 +00001053
1054 // Try convert this to an indexed compare by looking through PHIs/casts as a
1055 // last resort.
1056 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +00001057}
1058
Hans Wennborgf1f36512015-10-07 00:20:07 +00001059Instruction *InstCombiner::FoldAllocaCmp(ICmpInst &ICI, AllocaInst *Alloca,
1060 Value *Other) {
1061 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1062
1063 // It would be tempting to fold away comparisons between allocas and any
1064 // pointer not based on that alloca (e.g. an argument). However, even
1065 // though such pointers cannot alias, they can still compare equal.
1066 //
1067 // But LLVM doesn't specify where allocas get their memory, so if the alloca
1068 // doesn't escape we can argue that it's impossible to guess its value, and we
1069 // can therefore act as if any such guesses are wrong.
1070 //
1071 // The code below checks that the alloca doesn't escape, and that it's only
1072 // used in a comparison once (the current instruction). The
1073 // single-comparison-use condition ensures that we're trivially folding all
1074 // comparisons against the alloca consistently, and avoids the risk of
1075 // erroneously folding a comparison of the pointer with itself.
1076
1077 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1078
1079 SmallVector<Use *, 32> Worklist;
1080 for (Use &U : Alloca->uses()) {
1081 if (Worklist.size() >= MaxIter)
1082 return nullptr;
1083 Worklist.push_back(&U);
1084 }
1085
1086 unsigned NumCmps = 0;
1087 while (!Worklist.empty()) {
1088 assert(Worklist.size() <= MaxIter);
1089 Use *U = Worklist.pop_back_val();
1090 Value *V = U->getUser();
1091 --MaxIter;
1092
1093 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1094 isa<SelectInst>(V)) {
1095 // Track the uses.
1096 } else if (isa<LoadInst>(V)) {
1097 // Loading from the pointer doesn't escape it.
1098 continue;
1099 } else if (auto *SI = dyn_cast<StoreInst>(V)) {
1100 // Storing *to* the pointer is fine, but storing the pointer escapes it.
1101 if (SI->getValueOperand() == U->get())
1102 return nullptr;
1103 continue;
1104 } else if (isa<ICmpInst>(V)) {
1105 if (NumCmps++)
1106 return nullptr; // Found more than one cmp.
1107 continue;
1108 } else if (auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
1109 switch (Intrin->getIntrinsicID()) {
1110 // These intrinsics don't escape or compare the pointer. Memset is safe
1111 // because we don't allow ptrtoint. Memcpy and memmove are safe because
1112 // we don't allow stores, so src cannot point to V.
1113 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1114 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
1115 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1116 continue;
1117 default:
1118 return nullptr;
1119 }
1120 } else {
1121 return nullptr;
1122 }
1123 for (Use &U : V->uses()) {
1124 if (Worklist.size() >= MaxIter)
1125 return nullptr;
1126 Worklist.push_back(&U);
1127 }
1128 }
1129
1130 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001131 return replaceInstUsesWith(
Hans Wennborgf1f36512015-10-07 00:20:07 +00001132 ICI,
1133 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1134}
1135
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001136/// Fold "icmp pred (X+CI), X".
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00001137Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
Chris Lattner2188e402010-01-04 07:37:31 +00001138 Value *X, ConstantInt *CI,
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00001139 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +00001140 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001141 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +00001142 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +00001143
Chris Lattner8c92b572010-01-08 17:48:19 +00001144 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +00001145 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
1146 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
1147 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00001148 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +00001149 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +00001150 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1151 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001152
Chris Lattner2188e402010-01-04 07:37:31 +00001153 // (X+1) >u X --> X <u (0-1) --> X != 255
1154 // (X+2) >u X --> X <u (0-2) --> X <u 254
1155 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +00001156 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +00001157 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001158
Chris Lattner2188e402010-01-04 07:37:31 +00001159 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
1160 ConstantInt *SMax = ConstantInt::get(X->getContext(),
1161 APInt::getSignedMaxValue(BitWidth));
1162
1163 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1164 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1165 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1166 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1167 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1168 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +00001169 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +00001170 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001171
Chris Lattner2188e402010-01-04 07:37:31 +00001172 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1173 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1174 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1175 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1176 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1177 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +00001178
Chris Lattner2188e402010-01-04 07:37:31 +00001179 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +00001180 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +00001181 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
1182}
1183
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001184/// Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS and CmpRHS are
1185/// both known to be integer constants.
Chris Lattner2188e402010-01-04 07:37:31 +00001186Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
1187 ConstantInt *DivRHS) {
1188 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
1189 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001190
1191 // FIXME: If the operand types don't match the type of the divide
Chris Lattner2188e402010-01-04 07:37:31 +00001192 // then don't attempt this transform. The code below doesn't have the
1193 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach129c52a2011-09-30 18:09:53 +00001194 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner2188e402010-01-04 07:37:31 +00001195 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach129c52a2011-09-30 18:09:53 +00001196 // (x /u C1) <u C2. Simply casting the operands and result won't
1197 // work. :( The if statement below tests that condition and bails
Chris Lattner98457102011-02-10 05:23:05 +00001198 // if it finds it.
Chris Lattner2188e402010-01-04 07:37:31 +00001199 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
1200 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Craig Topperf40110f2014-04-25 05:29:35 +00001201 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001202 if (DivRHS->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +00001203 return nullptr; // The ProdOV computation fails on divide by zero.
Chris Lattner2188e402010-01-04 07:37:31 +00001204 if (DivIsSigned && DivRHS->isAllOnesValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001205 return nullptr; // The overflow computation also screws up here
Chris Lattner43273af2011-02-13 08:07:21 +00001206 if (DivRHS->isOne()) {
1207 // This eliminates some funny cases with INT_MIN.
1208 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
1209 return &ICI;
1210 }
Chris Lattner2188e402010-01-04 07:37:31 +00001211
1212 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach129c52a2011-09-30 18:09:53 +00001213 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
1214 // C2 (CI). By solving for X we can turn this into a range check
1215 // instead of computing a divide.
Chris Lattner2188e402010-01-04 07:37:31 +00001216 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
1217
1218 // Determine if the product overflows by seeing if the product is
1219 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach129c52a2011-09-30 18:09:53 +00001220 // as in the LHS instruction that we're folding.
Chris Lattner2188e402010-01-04 07:37:31 +00001221 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
1222 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
1223
1224 // Get the ICmp opcode
1225 ICmpInst::Predicate Pred = ICI.getPredicate();
1226
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001227 // If the division is known to be exact, then there is no remainder from the
1228 // divide, so the covered range size is unit, otherwise it is the divisor.
Chris Lattner98457102011-02-10 05:23:05 +00001229 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001230
Chris Lattner2188e402010-01-04 07:37:31 +00001231 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach129c52a2011-09-30 18:09:53 +00001232 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner2188e402010-01-04 07:37:31 +00001233 // Compute this interval based on the constants involved and the signedness of
1234 // the compare/divide. This computes a half-open interval, keeping track of
1235 // whether either value in the interval overflows. After analysis each
1236 // overflow variable is set to 0 if it's corresponding bound variable is valid
1237 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
1238 int LoOverflow = 0, HiOverflow = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001239 Constant *LoBound = nullptr, *HiBound = nullptr;
Chris Lattner98457102011-02-10 05:23:05 +00001240
Chris Lattner2188e402010-01-04 07:37:31 +00001241 if (!DivIsSigned) { // udiv
1242 // e.g. X/5 op 3 --> [15, 20)
1243 LoBound = Prod;
1244 HiOverflow = LoOverflow = ProdOV;
Chris Lattner98457102011-02-10 05:23:05 +00001245 if (!HiOverflow) {
1246 // If this is not an exact divide, then many values in the range collapse
1247 // to the same result value.
1248 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
1249 }
Chris Lattner2188e402010-01-04 07:37:31 +00001250 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
1251 if (CmpRHSV == 0) { // (X / pos) op 0
1252 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner98457102011-02-10 05:23:05 +00001253 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
1254 HiBound = RangeSize;
Chris Lattner2188e402010-01-04 07:37:31 +00001255 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
1256 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
1257 HiOverflow = LoOverflow = ProdOV;
1258 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001259 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +00001260 } else { // (X / pos) op neg
1261 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
1262 HiBound = AddOne(Prod);
1263 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
1264 if (!LoOverflow) {
Chris Lattner98457102011-02-10 05:23:05 +00001265 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001266 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattner98457102011-02-10 05:23:05 +00001267 }
Chris Lattner2188e402010-01-04 07:37:31 +00001268 }
Chris Lattnerb1a15122011-07-15 06:08:15 +00001269 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattner98457102011-02-10 05:23:05 +00001270 if (DivI->isExact())
1271 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001272 if (CmpRHSV == 0) { // (X / neg) op 0
1273 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner98457102011-02-10 05:23:05 +00001274 LoBound = AddOne(RangeSize);
1275 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001276 if (HiBound == DivRHS) { // -INTMIN = INTMIN
1277 HiOverflow = 1; // [INTMIN+1, overflow)
Craig Topperf40110f2014-04-25 05:29:35 +00001278 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
Chris Lattner2188e402010-01-04 07:37:31 +00001279 }
1280 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
1281 // e.g. X/-5 op 3 --> [-19, -14)
1282 HiBound = AddOne(Prod);
1283 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
1284 if (!LoOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001285 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner2188e402010-01-04 07:37:31 +00001286 } else { // (X / neg) op neg
1287 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
1288 LoOverflow = HiOverflow = ProdOV;
1289 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001290 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +00001291 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001292
Chris Lattner2188e402010-01-04 07:37:31 +00001293 // Dividing by a negative swaps the condition. LT <-> GT
1294 Pred = ICmpInst::getSwappedPredicate(Pred);
1295 }
1296
1297 Value *X = DivI->getOperand(0);
1298 switch (Pred) {
1299 default: llvm_unreachable("Unhandled icmp opcode!");
1300 case ICmpInst::ICMP_EQ:
1301 if (LoOverflow && HiOverflow)
Sanjay Patel4b198802016-02-01 22:23:39 +00001302 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner067459c2010-03-05 08:46:26 +00001303 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001304 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1305 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +00001306 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001307 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1308 ICmpInst::ICMP_ULT, X, HiBound);
Sanjay Patel4b198802016-02-01 22:23:39 +00001309 return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
Chris Lattner98457102011-02-10 05:23:05 +00001310 DivIsSigned, true));
Chris Lattner2188e402010-01-04 07:37:31 +00001311 case ICmpInst::ICMP_NE:
1312 if (LoOverflow && HiOverflow)
Sanjay Patel4b198802016-02-01 22:23:39 +00001313 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner067459c2010-03-05 08:46:26 +00001314 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001315 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1316 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +00001317 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001318 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1319 ICmpInst::ICMP_UGE, X, HiBound);
Sanjay Patel4b198802016-02-01 22:23:39 +00001320 return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
Chris Lattner067459c2010-03-05 08:46:26 +00001321 DivIsSigned, false));
Chris Lattner2188e402010-01-04 07:37:31 +00001322 case ICmpInst::ICMP_ULT:
1323 case ICmpInst::ICMP_SLT:
1324 if (LoOverflow == +1) // Low bound is greater than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001325 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001326 if (LoOverflow == -1) // Low bound is less than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001327 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001328 return new ICmpInst(Pred, X, LoBound);
1329 case ICmpInst::ICMP_UGT:
1330 case ICmpInst::ICMP_SGT:
1331 if (HiOverflow == +1) // High bound greater than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001332 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner98457102011-02-10 05:23:05 +00001333 if (HiOverflow == -1) // High bound less than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001334 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001335 if (Pred == ICmpInst::ICMP_UGT)
1336 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +00001337 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner2188e402010-01-04 07:37:31 +00001338 }
1339}
1340
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001341/// Handle "icmp(([al]shr X, cst1), cst2)".
Chris Lattnerd369f572011-02-13 07:43:07 +00001342Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
1343 ConstantInt *ShAmt) {
Chris Lattnerd369f572011-02-13 07:43:07 +00001344 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001345
Chris Lattnerd369f572011-02-13 07:43:07 +00001346 // Check that the shift amount is in range. If not, don't perform
1347 // undefined shifts. When the shift is visited it will be
1348 // simplified.
1349 uint32_t TypeBits = CmpRHSV.getBitWidth();
1350 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner43273af2011-02-13 08:07:21 +00001351 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001352 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001353
Chris Lattner43273af2011-02-13 08:07:21 +00001354 if (!ICI.isEquality()) {
1355 // If we have an unsigned comparison and an ashr, we can't simplify this.
1356 // Similarly for signed comparisons with lshr.
1357 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
Craig Topperf40110f2014-04-25 05:29:35 +00001358 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001359
Eli Friedman865866e2011-05-25 23:26:20 +00001360 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
1361 // by a power of 2. Since we already have logic to simplify these,
1362 // transform to div and then simplify the resultant comparison.
Chris Lattner43273af2011-02-13 08:07:21 +00001363 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedman865866e2011-05-25 23:26:20 +00001364 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Craig Topperf40110f2014-04-25 05:29:35 +00001365 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001366
Chris Lattner43273af2011-02-13 08:07:21 +00001367 // Revisit the shift (to delete it).
1368 Worklist.Add(Shr);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001369
Chris Lattner43273af2011-02-13 08:07:21 +00001370 Constant *DivCst =
1371 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001372
Chris Lattner43273af2011-02-13 08:07:21 +00001373 Value *Tmp =
1374 Shr->getOpcode() == Instruction::AShr ?
1375 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
1376 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001377
Chris Lattner43273af2011-02-13 08:07:21 +00001378 ICI.setOperand(0, Tmp);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001379
Chris Lattner43273af2011-02-13 08:07:21 +00001380 // If the builder folded the binop, just return it.
1381 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
Craig Topperf40110f2014-04-25 05:29:35 +00001382 if (!TheDiv)
Chris Lattner43273af2011-02-13 08:07:21 +00001383 return &ICI;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001384
Chris Lattner43273af2011-02-13 08:07:21 +00001385 // Otherwise, fold this div/compare.
1386 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1387 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001388
Chris Lattner43273af2011-02-13 08:07:21 +00001389 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1390 assert(Res && "This div/cst should have folded!");
1391 return Res;
1392 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001393
Chris Lattnerd369f572011-02-13 07:43:07 +00001394 // If we are comparing against bits always shifted out, the
1395 // comparison cannot succeed.
1396 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszakbddea112013-06-06 20:18:46 +00001397 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattnerd369f572011-02-13 07:43:07 +00001398 if (Shr->getOpcode() == Instruction::LShr)
1399 Comp = Comp.lshr(ShAmtVal);
1400 else
1401 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001402
Chris Lattnerd369f572011-02-13 07:43:07 +00001403 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1404 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001405 Constant *Cst = Builder->getInt1(IsICMP_NE);
Sanjay Patel4b198802016-02-01 22:23:39 +00001406 return replaceInstUsesWith(ICI, Cst);
Chris Lattnerd369f572011-02-13 07:43:07 +00001407 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001408
Chris Lattnerd369f572011-02-13 07:43:07 +00001409 // Otherwise, check to see if the bits shifted out are known to be zero.
1410 // If so, we can compare against the unshifted value:
1411 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattner9bd7fdf2011-02-13 18:30:09 +00001412 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattnerd369f572011-02-13 07:43:07 +00001413 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001414
Chris Lattnerd369f572011-02-13 07:43:07 +00001415 if (Shr->hasOneUse()) {
1416 // Otherwise strength reduce the shift into an and.
1417 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszakbddea112013-06-06 20:18:46 +00001418 Constant *Mask = Builder->getInt(Val);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001419
Chris Lattnerd369f572011-02-13 07:43:07 +00001420 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1421 Mask, Shr->getName()+".mask");
1422 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1423 }
Craig Topperf40110f2014-04-25 05:29:35 +00001424 return nullptr;
Chris Lattnerd369f572011-02-13 07:43:07 +00001425}
1426
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001427/// Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001428/// (icmp eq/ne A, Log2(const2/const1)) ->
1429/// (icmp eq/ne A, Log2(const2) - Log2(const1)).
1430Instruction *InstCombiner::FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
1431 ConstantInt *CI1,
1432 ConstantInt *CI2) {
1433 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1434
1435 auto getConstant = [&I, this](bool IsTrue) {
1436 if (I.getPredicate() == I.ICMP_NE)
1437 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001438 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001439 };
1440
1441 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1442 if (I.getPredicate() == I.ICMP_NE)
1443 Pred = CmpInst::getInversePredicate(Pred);
1444 return new ICmpInst(Pred, LHS, RHS);
1445 };
1446
1447 APInt AP1 = CI1->getValue();
1448 APInt AP2 = CI2->getValue();
1449
David Majnemer2abb8182014-10-25 07:13:13 +00001450 // Don't bother doing any work for cases which InstSimplify handles.
1451 if (AP2 == 0)
1452 return nullptr;
1453 bool IsAShr = isa<AShrOperator>(Op);
1454 if (IsAShr) {
1455 if (AP2.isAllOnesValue())
1456 return nullptr;
1457 if (AP2.isNegative() != AP1.isNegative())
1458 return nullptr;
1459 if (AP2.sgt(AP1))
1460 return nullptr;
1461 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001462
David Majnemerd2056022014-10-21 19:51:55 +00001463 if (!AP1)
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001464 // 'A' must be large enough to shift out the highest set bit.
1465 return getICmp(I.ICMP_UGT, A,
1466 ConstantInt::get(A->getType(), AP2.logBase2()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001467
David Majnemerd2056022014-10-21 19:51:55 +00001468 if (AP1 == AP2)
1469 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001470
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001471 int Shift;
David Majnemerd2056022014-10-21 19:51:55 +00001472 if (IsAShr && AP1.isNegative())
David Majnemere5977eb2015-09-19 00:48:26 +00001473 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001474 else
David Majnemere5977eb2015-09-19 00:48:26 +00001475 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001476
David Majnemerd2056022014-10-21 19:51:55 +00001477 if (Shift > 0) {
David Majnemere5977eb2015-09-19 00:48:26 +00001478 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1479 // There are multiple solutions if we are comparing against -1 and the LHS
David Majnemer47ce0b82015-09-19 00:48:31 +00001480 // of the ashr is not a power of two.
David Majnemere5977eb2015-09-19 00:48:26 +00001481 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1482 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
David Majnemerd2056022014-10-21 19:51:55 +00001483 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
David Majnemere5977eb2015-09-19 00:48:26 +00001484 } else if (AP1 == AP2.lshr(Shift)) {
1485 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1486 }
David Majnemerd2056022014-10-21 19:51:55 +00001487 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001488 // Shifting const2 will never be equal to const1.
1489 return getConstant(false);
1490}
Chris Lattner2188e402010-01-04 07:37:31 +00001491
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001492/// Handle "(icmp eq/ne (shl const2, A), const1)" ->
David Majnemer59939ac2014-10-19 08:23:08 +00001493/// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)).
1494Instruction *InstCombiner::FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
1495 ConstantInt *CI1,
1496 ConstantInt *CI2) {
1497 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1498
1499 auto getConstant = [&I, this](bool IsTrue) {
1500 if (I.getPredicate() == I.ICMP_NE)
1501 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001502 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
David Majnemer59939ac2014-10-19 08:23:08 +00001503 };
1504
1505 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1506 if (I.getPredicate() == I.ICMP_NE)
1507 Pred = CmpInst::getInversePredicate(Pred);
1508 return new ICmpInst(Pred, LHS, RHS);
1509 };
1510
1511 APInt AP1 = CI1->getValue();
1512 APInt AP2 = CI2->getValue();
1513
David Majnemer2abb8182014-10-25 07:13:13 +00001514 // Don't bother doing any work for cases which InstSimplify handles.
1515 if (AP2 == 0)
1516 return nullptr;
David Majnemer59939ac2014-10-19 08:23:08 +00001517
1518 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1519
1520 if (!AP1 && AP2TrailingZeros != 0)
1521 return getICmp(I.ICMP_UGE, A,
1522 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1523
1524 if (AP1 == AP2)
1525 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1526
1527 // Get the distance between the lowest bits that are set.
1528 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1529
1530 if (Shift > 0 && AP2.shl(Shift) == AP1)
1531 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1532
1533 // Shifting const2 will never be equal to const1.
1534 return getConstant(false);
1535}
1536
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001537/// Handle "icmp (instr, intcst)".
Chris Lattner2188e402010-01-04 07:37:31 +00001538Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1539 Instruction *LHSI,
1540 ConstantInt *RHS) {
1541 const APInt &RHSV = RHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001542
Chris Lattner2188e402010-01-04 07:37:31 +00001543 switch (LHSI->getOpcode()) {
1544 case Instruction::Trunc:
Sanjoy Dase5f48892015-09-16 20:41:29 +00001545 if (RHS->isOne() && RHSV.getBitWidth() > 1) {
1546 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1547 Value *V = nullptr;
1548 if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1549 match(LHSI->getOperand(0), m_Signum(m_Value(V))))
1550 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1551 ConstantInt::get(V->getType(), 1));
1552 }
Chris Lattner2188e402010-01-04 07:37:31 +00001553 if (ICI.isEquality() && LHSI->hasOneUse()) {
1554 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1555 // of the high bits truncated out of x are known.
1556 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1557 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner2188e402010-01-04 07:37:31 +00001558 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001559 computeKnownBits(LHSI->getOperand(0), KnownZero, KnownOne, 0, &ICI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001560
Chris Lattner2188e402010-01-04 07:37:31 +00001561 // If all the high bits are known, we can do this xform.
1562 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1563 // Pull in the high bits from known-ones set.
Jay Foad583abbc2010-12-07 08:25:19 +00001564 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedmane0a64d82012-05-11 01:32:59 +00001565 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner2188e402010-01-04 07:37:31 +00001566 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001567 Builder->getInt(NewRHS));
Chris Lattner2188e402010-01-04 07:37:31 +00001568 }
1569 }
1570 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001571
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001572 case Instruction::Xor: // (icmp pred (xor X, XorCst), CI)
1573 if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001574 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1575 // fold the xor.
1576 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1577 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1578 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001579
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001580 // If the sign bit of the XorCst is not set, there is no change to
Chris Lattner2188e402010-01-04 07:37:31 +00001581 // the operation, just stop using the Xor.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001582 if (!XorCst->isNegative()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001583 ICI.setOperand(0, CompareVal);
1584 Worklist.Add(LHSI);
1585 return &ICI;
1586 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001587
Chris Lattner2188e402010-01-04 07:37:31 +00001588 // Was the old condition true if the operand is positive?
1589 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001590
Chris Lattner2188e402010-01-04 07:37:31 +00001591 // If so, the new one isn't.
1592 isTrueIfPositive ^= true;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001593
Chris Lattner2188e402010-01-04 07:37:31 +00001594 if (isTrueIfPositive)
1595 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1596 SubOne(RHS));
1597 else
1598 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1599 AddOne(RHS));
1600 }
1601
1602 if (LHSI->hasOneUse()) {
1603 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001604 if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1605 const APInt &SignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001606 ICmpInst::Predicate Pred = ICI.isSigned()
1607 ? ICI.getUnsignedPredicate()
1608 : ICI.getSignedPredicate();
1609 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001610 Builder->getInt(RHSV ^ SignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001611 }
1612
1613 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001614 if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1615 const APInt &NotSignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001616 ICmpInst::Predicate Pred = ICI.isSigned()
1617 ? ICI.getUnsignedPredicate()
1618 : ICI.getSignedPredicate();
1619 Pred = ICI.getSwappedPredicate(Pred);
1620 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001621 Builder->getInt(RHSV ^ NotSignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001622 }
1623 }
David Majnemer72d76272013-07-09 09:20:58 +00001624
1625 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1626 // iff -C is a power of 2
1627 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001628 XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1629 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
David Majnemer72d76272013-07-09 09:20:58 +00001630
1631 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1632 // iff -C is a power of 2
1633 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001634 XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1635 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001636 }
1637 break;
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001638 case Instruction::And: // (icmp pred (and X, AndCst), RHS)
Chris Lattner2188e402010-01-04 07:37:31 +00001639 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1640 LHSI->getOperand(0)->hasOneUse()) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001641 ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001642
Chris Lattner2188e402010-01-04 07:37:31 +00001643 // If the LHS is an AND of a truncating cast, we can widen the
1644 // and/compare to be the input width without changing the value
1645 // produced, eliminating a cast.
1646 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1647 // We can do this transformation if either the AND constant does not
Jim Grosbach129c52a2011-09-30 18:09:53 +00001648 // have its sign bit set or if it is an equality comparison.
Chris Lattner2188e402010-01-04 07:37:31 +00001649 // Extending a relational comparison when we're checking the sign
1650 // bit would not work.
Benjamin Kramer35159c12011-06-12 22:47:53 +00001651 if (ICI.isEquality() ||
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001652 (!AndCst->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer35159c12011-06-12 22:47:53 +00001653 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001654 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001655 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
Benjamin Kramer35159c12011-06-12 22:47:53 +00001656 NewAnd->takeName(LHSI);
Chris Lattner2188e402010-01-04 07:37:31 +00001657 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer35159c12011-06-12 22:47:53 +00001658 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner2188e402010-01-04 07:37:31 +00001659 }
1660 }
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001661
1662 // If the LHS is an AND of a zext, and we have an equality compare, we can
1663 // shrink the and/compare to the smaller type, eliminating the cast.
1664 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattner229907c2011-07-18 04:54:35 +00001665 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001666 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1667 // should fold the icmp to true/false in that case.
1668 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1669 Value *NewAnd =
1670 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001671 ConstantExpr::getTrunc(AndCst, Ty));
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001672 NewAnd->takeName(LHSI);
1673 return new ICmpInst(ICI.getPredicate(), NewAnd,
1674 ConstantExpr::getTrunc(RHS, Ty));
1675 }
1676 }
1677
Chris Lattner2188e402010-01-04 07:37:31 +00001678 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1679 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1680 // happens a LOT in code produced by the C front-end, for bitfield
1681 // access.
1682 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1683 if (Shift && !Shift->isShift())
Craig Topperf40110f2014-04-25 05:29:35 +00001684 Shift = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001685
Chris Lattner2188e402010-01-04 07:37:31 +00001686 ConstantInt *ShAmt;
Craig Topperf40110f2014-04-25 05:29:35 +00001687 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001688
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001689 // This seemingly simple opportunity to fold away a shift turns out to
1690 // be rather complicated. See PR17827
1691 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
Chris Lattner2188e402010-01-04 07:37:31 +00001692 if (ShAmt) {
Kay Tiong Khoo5389f742013-12-02 18:43:59 +00001693 bool CanFold = false;
1694 unsigned ShiftOpcode = Shift->getOpcode();
1695 if (ShiftOpcode == Instruction::AShr) {
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001696 // There may be some constraints that make this possible,
1697 // but nothing simple has been discovered yet.
1698 CanFold = false;
1699 } else if (ShiftOpcode == Instruction::Shl) {
1700 // For a left shift, we can fold if the comparison is not signed.
1701 // We can also fold a signed comparison if the mask value and
1702 // comparison value are not negative. These constraints may not be
1703 // obvious, but we can prove that they are correct using an SMT
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001704 // solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001705 if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
Chris Lattner2188e402010-01-04 07:37:31 +00001706 CanFold = true;
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001707 } else if (ShiftOpcode == Instruction::LShr) {
1708 // For a logical right shift, we can fold if the comparison is not
1709 // signed. We can also fold a signed comparison if the shifted mask
1710 // value and the shifted comparison value are not negative.
1711 // These constraints may not be obvious, but we can prove that they
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001712 // are correct using an SMT solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001713 if (!ICI.isSigned())
1714 CanFold = true;
1715 else {
1716 ConstantInt *ShiftedAndCst =
1717 cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1718 ConstantInt *ShiftedRHSCst =
1719 cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1720
1721 if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1722 CanFold = true;
1723 }
Chris Lattner2188e402010-01-04 07:37:31 +00001724 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001725
Chris Lattner2188e402010-01-04 07:37:31 +00001726 if (CanFold) {
1727 Constant *NewCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001728 if (ShiftOpcode == Instruction::Shl)
Chris Lattner2188e402010-01-04 07:37:31 +00001729 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1730 else
1731 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001732
Chris Lattner2188e402010-01-04 07:37:31 +00001733 // Check to see if we are shifting out any of the bits being
1734 // compared.
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001735 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001736 // If we shifted bits out, the fold is not going to work out.
1737 // As a special case, check to see if this means that the
1738 // result is always true or false now.
1739 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00001740 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001741 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Sanjay Patel4b198802016-02-01 22:23:39 +00001742 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001743 } else {
1744 ICI.setOperand(1, NewCst);
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001745 Constant *NewAndCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001746 if (ShiftOpcode == Instruction::Shl)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001747 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
Chris Lattner2188e402010-01-04 07:37:31 +00001748 else
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001749 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1750 LHSI->setOperand(1, NewAndCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001751 LHSI->setOperand(0, Shift->getOperand(0));
1752 Worklist.Add(Shift); // Shift is dead.
1753 return &ICI;
1754 }
1755 }
1756 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001757
Chris Lattner2188e402010-01-04 07:37:31 +00001758 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1759 // preferable because it allows the C<<Y expression to be hoisted out
1760 // of a loop if Y is invariant and X is not.
1761 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1762 ICI.isEquality() && !Shift->isArithmeticShift() &&
1763 !isa<Constant>(Shift->getOperand(0))) {
1764 // Compute C << Y.
1765 Value *NS;
1766 if (Shift->getOpcode() == Instruction::LShr) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001767 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001768 } else {
1769 // Insert a logical shift.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001770 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001771 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001772
Chris Lattner2188e402010-01-04 07:37:31 +00001773 // Compute X & (C << Y).
Jim Grosbach129c52a2011-09-30 18:09:53 +00001774 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001775 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001776
Chris Lattner2188e402010-01-04 07:37:31 +00001777 ICI.setOperand(0, NewAnd);
1778 return &ICI;
1779 }
Paul Redmond5917f4c2012-12-19 19:47:13 +00001780
David Majnemer0ffccf72014-08-24 09:10:57 +00001781 // (icmp pred (and (or (lshr X, Y), X), 1), 0) -->
1782 // (icmp pred (and X, (or (shl 1, Y), 1), 0))
1783 //
1784 // iff pred isn't signed
1785 {
1786 Value *X, *Y, *LShr;
1787 if (!ICI.isSigned() && RHSV == 0) {
1788 if (match(LHSI->getOperand(1), m_One())) {
1789 Constant *One = cast<Constant>(LHSI->getOperand(1));
1790 Value *Or = LHSI->getOperand(0);
1791 if (match(Or, m_Or(m_Value(LShr), m_Value(X))) &&
1792 match(LShr, m_LShr(m_Specific(X), m_Value(Y)))) {
1793 unsigned UsesRemoved = 0;
1794 if (LHSI->hasOneUse())
1795 ++UsesRemoved;
1796 if (Or->hasOneUse())
1797 ++UsesRemoved;
1798 if (LShr->hasOneUse())
1799 ++UsesRemoved;
1800 Value *NewOr = nullptr;
1801 // Compute X & ((1 << Y) | 1)
1802 if (auto *C = dyn_cast<Constant>(Y)) {
1803 if (UsesRemoved >= 1)
1804 NewOr =
1805 ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1806 } else {
1807 if (UsesRemoved >= 3)
1808 NewOr = Builder->CreateOr(Builder->CreateShl(One, Y,
1809 LShr->getName(),
1810 /*HasNUW=*/true),
1811 One, Or->getName());
1812 }
1813 if (NewOr) {
1814 Value *NewAnd = Builder->CreateAnd(X, NewOr, LHSI->getName());
1815 ICI.setOperand(0, NewAnd);
1816 return &ICI;
1817 }
1818 }
1819 }
1820 }
1821 }
1822
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001823 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1824 // bit set in (X & AndCst) will produce a result greater than RHSV.
Paul Redmond5917f4c2012-12-19 19:47:13 +00001825 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001826 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1827 if ((NTZ < AndCst->getBitWidth()) &&
1828 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
Paul Redmond5917f4c2012-12-19 19:47:13 +00001829 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1830 Constant::getNullValue(RHS->getType()));
1831 }
Chris Lattner2188e402010-01-04 07:37:31 +00001832 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001833
Chris Lattner2188e402010-01-04 07:37:31 +00001834 // Try to optimize things like "A[i]&42 == 0" to index computations.
1835 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1836 if (GetElementPtrInst *GEP =
1837 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1838 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1839 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1840 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1841 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1842 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1843 return Res;
1844 }
1845 }
David Majnemer414d4e52013-07-09 08:09:32 +00001846
1847 // X & -C == -C -> X > u ~C
1848 // X & -C != -C -> X <= u ~C
1849 // iff C is a power of 2
1850 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1851 return new ICmpInst(
1852 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1853 : ICmpInst::ICMP_ULE,
1854 LHSI->getOperand(0), SubOne(RHS));
David Majnemerdfa3b092015-08-16 07:09:17 +00001855
1856 // (icmp eq (and %A, C), 0) -> (icmp sgt (trunc %A), -1)
1857 // iff C is a power of 2
1858 if (ICI.isEquality() && LHSI->hasOneUse() && match(RHS, m_Zero())) {
1859 if (auto *CI = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1860 const APInt &AI = CI->getValue();
1861 int32_t ExactLogBase2 = AI.exactLogBase2();
1862 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1863 Type *NTy = IntegerType::get(ICI.getContext(), ExactLogBase2 + 1);
1864 Value *Trunc = Builder->CreateTrunc(LHSI->getOperand(0), NTy);
1865 return new ICmpInst(ICI.getPredicate() == ICmpInst::ICMP_EQ
1866 ? ICmpInst::ICMP_SGE
1867 : ICmpInst::ICMP_SLT,
1868 Trunc, Constant::getNullValue(NTy));
1869 }
1870 }
1871 }
Chris Lattner2188e402010-01-04 07:37:31 +00001872 break;
1873
1874 case Instruction::Or: {
Sanjoy Dase5f48892015-09-16 20:41:29 +00001875 if (RHS->isOne()) {
1876 // icmp slt signum(V) 1 --> icmp slt V, 1
1877 Value *V = nullptr;
1878 if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1879 match(LHSI, m_Signum(m_Value(V))))
1880 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1881 ConstantInt::get(V->getType(), 1));
1882 }
1883
Chris Lattner2188e402010-01-04 07:37:31 +00001884 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1885 break;
1886 Value *P, *Q;
1887 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1888 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1889 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner2188e402010-01-04 07:37:31 +00001890 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1891 Constant::getNullValue(P->getType()));
1892 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1893 Constant::getNullValue(Q->getType()));
1894 Instruction *Op;
1895 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1896 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1897 else
1898 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1899 return Op;
1900 }
1901 break;
1902 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001903
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001904 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1905 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1906 if (!Val) break;
1907
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001908 // If this is a signed comparison to 0 and the mul is sign preserving,
1909 // use the mul LHS operand instead.
1910 ICmpInst::Predicate pred = ICI.getPredicate();
1911 if (isSignTest(pred, RHS) && !Val->isZero() &&
1912 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1913 return new ICmpInst(Val->isNegative() ?
1914 ICmpInst::getSwappedPredicate(pred) : pred,
1915 LHSI->getOperand(0),
1916 Constant::getNullValue(RHS->getType()));
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001917
1918 break;
1919 }
1920
Chris Lattner2188e402010-01-04 07:37:31 +00001921 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
Chris Lattner2188e402010-01-04 07:37:31 +00001922 uint32_t TypeBits = RHSV.getBitWidth();
David Majnemerb889e402013-06-28 23:42:03 +00001923 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1924 if (!ShAmt) {
1925 Value *X;
1926 // (1 << X) pred P2 -> X pred Log2(P2)
1927 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1928 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1929 ICmpInst::Predicate Pred = ICI.getPredicate();
1930 if (ICI.isUnsigned()) {
1931 if (!RHSVIsPowerOf2) {
1932 // (1 << X) < 30 -> X <= 4
1933 // (1 << X) <= 30 -> X <= 4
1934 // (1 << X) >= 30 -> X > 4
1935 // (1 << X) > 30 -> X > 4
1936 if (Pred == ICmpInst::ICMP_ULT)
1937 Pred = ICmpInst::ICMP_ULE;
1938 else if (Pred == ICmpInst::ICMP_UGE)
1939 Pred = ICmpInst::ICMP_UGT;
1940 }
1941 unsigned RHSLog2 = RHSV.logBase2();
1942
1943 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
David Majnemerb889e402013-06-28 23:42:03 +00001944 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1945 if (RHSLog2 == TypeBits-1) {
1946 if (Pred == ICmpInst::ICMP_UGE)
1947 Pred = ICmpInst::ICMP_EQ;
David Majnemerb889e402013-06-28 23:42:03 +00001948 else if (Pred == ICmpInst::ICMP_ULT)
1949 Pred = ICmpInst::ICMP_NE;
1950 }
1951
1952 return new ICmpInst(Pred, X,
1953 ConstantInt::get(RHS->getType(), RHSLog2));
1954 } else if (ICI.isSigned()) {
1955 if (RHSV.isAllOnesValue()) {
1956 // (1 << X) <= -1 -> X == 31
1957 if (Pred == ICmpInst::ICMP_SLE)
1958 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1959 ConstantInt::get(RHS->getType(), TypeBits-1));
1960
1961 // (1 << X) > -1 -> X != 31
1962 if (Pred == ICmpInst::ICMP_SGT)
1963 return new ICmpInst(ICmpInst::ICMP_NE, X,
1964 ConstantInt::get(RHS->getType(), TypeBits-1));
1965 } else if (!RHSV) {
1966 // (1 << X) < 0 -> X == 31
1967 // (1 << X) <= 0 -> X == 31
1968 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1969 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1970 ConstantInt::get(RHS->getType(), TypeBits-1));
1971
1972 // (1 << X) >= 0 -> X != 31
1973 // (1 << X) > 0 -> X != 31
1974 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1975 return new ICmpInst(ICmpInst::ICMP_NE, X,
1976 ConstantInt::get(RHS->getType(), TypeBits-1));
1977 }
1978 } else if (ICI.isEquality()) {
1979 if (RHSVIsPowerOf2)
1980 return new ICmpInst(
1981 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
David Majnemerb889e402013-06-28 23:42:03 +00001982 }
1983 }
1984 break;
1985 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001986
Chris Lattner2188e402010-01-04 07:37:31 +00001987 // Check that the shift amount is in range. If not, don't perform
1988 // undefined shifts. When the shift is visited it will be
1989 // simplified.
1990 if (ShAmt->uge(TypeBits))
1991 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001992
Chris Lattner2188e402010-01-04 07:37:31 +00001993 if (ICI.isEquality()) {
1994 // If we are comparing against bits always shifted out, the
1995 // comparison cannot succeed.
1996 Constant *Comp =
1997 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1998 ShAmt);
1999 if (Comp != RHS) {// Comparing against a bit that we know is zero.
2000 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00002001 Constant *Cst = Builder->getInt1(IsICMP_NE);
Sanjay Patel4b198802016-02-01 22:23:39 +00002002 return replaceInstUsesWith(ICI, Cst);
Chris Lattner2188e402010-01-04 07:37:31 +00002003 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002004
Chris Lattner98457102011-02-10 05:23:05 +00002005 // If the shift is NUW, then it is just shifting out zeros, no need for an
2006 // AND.
2007 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
2008 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2009 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002010
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002011 // If the shift is NSW and we compare to 0, then it is just shifting out
2012 // sign bits, no need for an AND either.
2013 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
2014 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2015 ConstantExpr::getLShr(RHS, ShAmt));
2016
Chris Lattner2188e402010-01-04 07:37:31 +00002017 if (LHSI->hasOneUse()) {
2018 // Otherwise strength reduce the shift into an and.
2019 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Jakub Staszakbddea112013-06-06 20:18:46 +00002020 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
2021 TypeBits - ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002022
Chris Lattner2188e402010-01-04 07:37:31 +00002023 Value *And =
2024 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
2025 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner98457102011-02-10 05:23:05 +00002026 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner2188e402010-01-04 07:37:31 +00002027 }
2028 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002029
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002030 // If this is a signed comparison to 0 and the shift is sign preserving,
2031 // use the shift LHS operand instead.
2032 ICmpInst::Predicate pred = ICI.getPredicate();
2033 if (isSignTest(pred, RHS) &&
2034 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
2035 return new ICmpInst(pred,
2036 LHSI->getOperand(0),
2037 Constant::getNullValue(RHS->getType()));
2038
Chris Lattner2188e402010-01-04 07:37:31 +00002039 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2040 bool TrueIfSigned = false;
2041 if (LHSI->hasOneUse() &&
2042 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
2043 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattner43273af2011-02-13 08:07:21 +00002044 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach129c52a2011-09-30 18:09:53 +00002045 APInt::getOneBitSet(TypeBits,
Chris Lattner43273af2011-02-13 08:07:21 +00002046 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002047 Value *And =
2048 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
2049 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2050 And, Constant::getNullValue(And->getType()));
2051 }
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002052
2053 // Transform (icmp pred iM (shl iM %v, N), CI)
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00002054 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
2055 // 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 +00002056 // This enables to get rid of the shift in favor of a trunc which can be
2057 // free on the target. It has the additional benefit of comparing to a
2058 // smaller constant, which will be target friendly.
2059 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00002060 if (LHSI->hasOneUse() &&
2061 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002062 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
2063 Constant *NCI = ConstantExpr::getTrunc(
2064 ConstantExpr::getAShr(RHS,
2065 ConstantInt::get(RHS->getType(), Amt)),
2066 NTy);
2067 return new ICmpInst(ICI.getPredicate(),
2068 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaison1fd843e2013-02-15 15:18:17 +00002069 NCI);
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002070 }
2071
Chris Lattner2188e402010-01-04 07:37:31 +00002072 break;
2073 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002074
Chris Lattner2188e402010-01-04 07:37:31 +00002075 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewycky174a7052011-02-28 08:31:40 +00002076 case Instruction::AShr: {
2077 // Handle equality comparisons of shift-by-constant.
2078 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
2079 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2080 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattnerd369f572011-02-13 07:43:07 +00002081 return Res;
Nick Lewycky174a7052011-02-28 08:31:40 +00002082 }
2083
2084 // Handle exact shr's.
2085 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
2086 if (RHSV.isMinValue())
2087 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
2088 }
Chris Lattner2188e402010-01-04 07:37:31 +00002089 break;
Nick Lewycky174a7052011-02-28 08:31:40 +00002090 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002091
Chris Lattner2188e402010-01-04 07:37:31 +00002092 case Instruction::UDiv:
Chad Rosier4e6cda22016-05-10 20:22:09 +00002093 if (ConstantInt *DivLHS = dyn_cast<ConstantInt>(LHSI->getOperand(0))) {
2094 Value *X = LHSI->getOperand(1);
2095 APInt C1 = RHS->getValue();
2096 APInt C2 = DivLHS->getValue();
2097 assert(C2 != 0 && "udiv 0, X should have been simplified already.");
2098 // (icmp ugt (udiv C2, X), C1) -> (icmp ule X, C2/(C1+1))
2099 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
2100 assert(!C1.isMaxValue() &&
2101 "icmp ugt X, UINT_MAX should have been simplified already.");
2102 return new ICmpInst(ICmpInst::ICMP_ULE, X,
2103 ConstantInt::get(X->getType(), C2.udiv(C1 + 1)));
2104 }
2105 // (icmp ult (udiv C2, X), C1) -> (icmp ugt X, C2/C1)
2106 if (ICI.getPredicate() == ICmpInst::ICMP_ULT) {
2107 assert(C1 != 0 && "icmp ult X, 0 should have been simplified already.");
2108 return new ICmpInst(ICmpInst::ICMP_UGT, X,
2109 ConstantInt::get(X->getType(), C2.udiv(C1)));
2110 }
2111 }
2112 // fall-through
2113 case Instruction::SDiv:
Chris Lattner2188e402010-01-04 07:37:31 +00002114 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach129c52a2011-09-30 18:09:53 +00002115 // Fold this div into the comparison, producing a range check.
2116 // Determine, based on the divide type, what the range is being
2117 // checked. If there is an overflow on the low or high side, remember
Chris Lattner2188e402010-01-04 07:37:31 +00002118 // it, otherwise compute the range [low, hi) bounding the new value.
2119 // See: InsertRangeTest above for the kinds of replacements possible.
2120 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
2121 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
2122 DivRHS))
2123 return R;
2124 break;
2125
David Majnemerf2a9a512013-07-09 07:50:59 +00002126 case Instruction::Sub: {
2127 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
2128 if (!LHSC) break;
2129 const APInt &LHSV = LHSC->getValue();
2130
2131 // C1-X <u C2 -> (X|(C2-1)) == C1
2132 // iff C1 & (C2-1) == C2-1
2133 // C2 is a power of 2
2134 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
2135 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
2136 return new ICmpInst(ICmpInst::ICMP_EQ,
2137 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
2138 LHSC);
2139
David Majnemereeed73b2013-07-09 09:24:35 +00002140 // C1-X >u C2 -> (X|C2) != C1
David Majnemerf2a9a512013-07-09 07:50:59 +00002141 // iff C1 & C2 == C2
2142 // C2+1 is a power of 2
2143 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
2144 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
2145 return new ICmpInst(ICmpInst::ICMP_NE,
2146 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
2147 break;
2148 }
2149
Chris Lattner2188e402010-01-04 07:37:31 +00002150 case Instruction::Add:
2151 // Fold: icmp pred (add X, C1), C2
2152 if (!ICI.isEquality()) {
2153 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
2154 if (!LHSC) break;
2155 const APInt &LHSV = LHSC->getValue();
2156
2157 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
2158 .subtract(LHSV);
2159
2160 if (ICI.isSigned()) {
2161 if (CR.getLower().isSignBit()) {
2162 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002163 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00002164 } else if (CR.getUpper().isSignBit()) {
2165 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002166 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00002167 }
2168 } else {
2169 if (CR.getLower().isMinValue()) {
2170 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002171 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00002172 } else if (CR.getUpper().isMinValue()) {
2173 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002174 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00002175 }
2176 }
David Majnemerfa90a0b2013-07-08 11:53:08 +00002177
David Majnemerbafa5372013-07-09 07:58:32 +00002178 // X-C1 <u C2 -> (X & -C2) == C1
2179 // iff C1 & (C2-1) == 0
2180 // C2 is a power of 2
David Majnemerfa90a0b2013-07-08 11:53:08 +00002181 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
David Majnemerbafa5372013-07-09 07:58:32 +00002182 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
David Majnemerfa90a0b2013-07-08 11:53:08 +00002183 return new ICmpInst(ICmpInst::ICMP_EQ,
2184 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
2185 ConstantExpr::getNeg(LHSC));
David Majnemerbafa5372013-07-09 07:58:32 +00002186
David Majnemereeed73b2013-07-09 09:24:35 +00002187 // X-C1 >u C2 -> (X & ~C2) != C1
David Majnemerbafa5372013-07-09 07:58:32 +00002188 // iff C1 & C2 == 0
2189 // C2+1 is a power of 2
2190 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
2191 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
2192 return new ICmpInst(ICmpInst::ICMP_NE,
2193 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
2194 ConstantExpr::getNeg(LHSC));
Chris Lattner2188e402010-01-04 07:37:31 +00002195 }
2196 break;
2197 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002198
Chris Lattner2188e402010-01-04 07:37:31 +00002199 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
2200 if (ICI.isEquality()) {
2201 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002202
2203 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner2188e402010-01-04 07:37:31 +00002204 // the second operand is a constant, simplify a bit.
2205 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
2206 switch (BO->getOpcode()) {
2207 case Instruction::SRem:
2208 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2209 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
2210 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohman4ce1fb12010-04-08 23:03:40 +00002211 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner2188e402010-01-04 07:37:31 +00002212 Value *NewRem =
2213 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
2214 BO->getName());
2215 return new ICmpInst(ICI.getPredicate(), NewRem,
2216 Constant::getNullValue(BO->getType()));
2217 }
2218 }
2219 break;
2220 case Instruction::Add:
2221 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2222 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2223 if (BO->hasOneUse())
2224 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2225 ConstantExpr::getSub(RHS, BOp1C));
2226 } else if (RHSV == 0) {
2227 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2228 // efficiently invertible, or if the add has just this one use.
2229 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002230
Chris Lattner2188e402010-01-04 07:37:31 +00002231 if (Value *NegVal = dyn_castNegVal(BOp1))
2232 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner31b106d2011-04-26 20:02:45 +00002233 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner2188e402010-01-04 07:37:31 +00002234 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner31b106d2011-04-26 20:02:45 +00002235 if (BO->hasOneUse()) {
Chris Lattner2188e402010-01-04 07:37:31 +00002236 Value *Neg = Builder->CreateNeg(BOp1);
2237 Neg->takeName(BO);
2238 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
2239 }
2240 }
2241 break;
2242 case Instruction::Xor:
David Majnemer0f0abc72016-02-12 18:12:38 +00002243 if (BO->hasOneUse()) {
2244 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
2245 // For the xor case, we can xor two constants together, eliminating
2246 // the explicit xor.
2247 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2248 ConstantExpr::getXor(RHS, BOC));
2249 } else if (RHSV == 0) {
2250 // Replace ((xor A, B) != 0) with (A != B)
2251 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2252 BO->getOperand(1));
2253 }
Benjamin Kramerc9708492011-06-13 15:24:24 +00002254 }
Chris Lattner2188e402010-01-04 07:37:31 +00002255 break;
Benjamin Kramerc9708492011-06-13 15:24:24 +00002256 case Instruction::Sub:
David Majnemer0f0abc72016-02-12 18:12:38 +00002257 if (BO->hasOneUse()) {
2258 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
2259 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
Benjamin Kramerc9708492011-06-13 15:24:24 +00002260 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
David Majnemer0f0abc72016-02-12 18:12:38 +00002261 ConstantExpr::getSub(BOp0C, RHS));
2262 } else if (RHSV == 0) {
2263 // Replace ((sub A, B) != 0) with (A != B)
2264 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2265 BO->getOperand(1));
2266 }
Benjamin Kramerc9708492011-06-13 15:24:24 +00002267 }
2268 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002269 case Instruction::Or:
2270 // If bits are being or'd in that are not present in the constant we
2271 // are comparing against, then the comparison could never succeed!
Eli Friedman0428a612010-07-29 18:03:33 +00002272 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002273 Constant *NotCI = ConstantExpr::getNot(RHS);
2274 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00002275 return replaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Sanjay Patele998b912016-04-14 20:17:40 +00002276
2277 // Comparing if all bits outside of a constant mask are set?
2278 // Replace (X | C) == -1 with (X & ~C) == ~C.
2279 // This removes the -1 constant.
2280 if (BO->hasOneUse() && RHS->isAllOnesValue()) {
2281 Constant *NotBOC = ConstantExpr::getNot(BOC);
2282 Value *And = Builder->CreateAnd(BO->getOperand(0), NotBOC);
2283 return new ICmpInst(ICI.getPredicate(), And, NotBOC);
2284 }
Chris Lattner2188e402010-01-04 07:37:31 +00002285 }
2286 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002287
Chris Lattner2188e402010-01-04 07:37:31 +00002288 case Instruction::And:
2289 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2290 // If bits are being compared against that are and'd out, then the
2291 // comparison can never succeed!
2292 if ((RHSV & ~BOC->getValue()) != 0)
Sanjay Patel4b198802016-02-01 22:23:39 +00002293 return replaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002294
Chris Lattner2188e402010-01-04 07:37:31 +00002295 // If we have ((X & C) == C), turn it into ((X & C) != 0).
2296 if (RHS == BOC && RHSV.isPowerOf2())
2297 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
2298 ICmpInst::ICMP_NE, LHSI,
2299 Constant::getNullValue(RHS->getType()));
Benjamin Kramer9eca5fe2011-07-04 20:16:36 +00002300
2301 // Don't perform the following transforms if the AND has multiple uses
2302 if (!BO->hasOneUse())
2303 break;
2304
Chris Lattner2188e402010-01-04 07:37:31 +00002305 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
2306 if (BOC->getValue().isSignBit()) {
2307 Value *X = BO->getOperand(0);
2308 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002309 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00002310 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
2311 return new ICmpInst(pred, X, Zero);
2312 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002313
Chris Lattner2188e402010-01-04 07:37:31 +00002314 // ((X & ~7) == 0) --> X < 8
2315 if (RHSV == 0 && isHighOnes(BOC)) {
2316 Value *X = BO->getOperand(0);
2317 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002318 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00002319 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
2320 return new ICmpInst(pred, X, NegX);
2321 }
2322 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002323 break;
2324 case Instruction::Mul:
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00002325 if (RHSV == 0 && BO->hasNoSignedWrap()) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002326 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2327 // The trivial case (mul X, 0) is handled by InstSimplify
2328 // General case : (mul X, C) != 0 iff X != 0
2329 // (mul X, C) == 0 iff X == 0
2330 if (!BOC->isZero())
2331 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2332 Constant::getNullValue(RHS->getType()));
2333 }
2334 }
2335 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002336 default: break;
2337 }
2338 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
2339 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner54f4e392010-01-05 18:09:56 +00002340 switch (II->getIntrinsicID()) {
2341 case Intrinsic::bswap:
Chris Lattner2188e402010-01-04 07:37:31 +00002342 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00002343 ICI.setOperand(0, II->getArgOperand(0));
Jakub Staszakbddea112013-06-06 20:18:46 +00002344 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
Chris Lattner2188e402010-01-04 07:37:31 +00002345 return &ICI;
Chris Lattner54f4e392010-01-05 18:09:56 +00002346 case Intrinsic::ctlz:
2347 case Intrinsic::cttz:
2348 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
2349 if (RHSV == RHS->getType()->getBitWidth()) {
2350 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00002351 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00002352 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
2353 return &ICI;
2354 }
2355 break;
2356 case Intrinsic::ctpop:
2357 // popcount(A) == 0 -> A == 0 and likewise for !=
2358 if (RHS->isZero()) {
2359 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00002360 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00002361 ICI.setOperand(1, RHS);
2362 return &ICI;
2363 }
2364 break;
2365 default:
Duncan Sands41b4a6b2010-07-12 08:16:59 +00002366 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002367 }
2368 }
2369 }
Craig Topperf40110f2014-04-25 05:29:35 +00002370 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002371}
2372
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002373/// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so
2374/// far.
2375Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICmp) {
2376 const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00002377 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002378 Type *SrcTy = LHSCIOp->getType();
2379 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002380 Value *RHSCIOp;
2381
Jim Grosbach129c52a2011-09-30 18:09:53 +00002382 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00002383 // integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002384 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
2385 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002386 Value *RHSOp = nullptr;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002387 if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
Michael Liaod266b922015-02-13 04:51:26 +00002388 Value *RHSCIOp = RHSC->getOperand(0);
2389 if (RHSCIOp->getType()->getPointerAddressSpace() ==
2390 LHSCIOp->getType()->getPointerAddressSpace()) {
2391 RHSOp = RHSC->getOperand(0);
2392 // If the pointer types don't match, insert a bitcast.
2393 if (LHSCIOp->getType() != RHSOp->getType())
2394 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
2395 }
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002396 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002397 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002398 }
Chris Lattner2188e402010-01-04 07:37:31 +00002399
2400 if (RHSOp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002401 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002402 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002403
Chris Lattner2188e402010-01-04 07:37:31 +00002404 // The code below only handles extension cast instructions, so far.
2405 // Enforce this.
2406 if (LHSCI->getOpcode() != Instruction::ZExt &&
2407 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002408 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002409
2410 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002411 bool isSignedCmp = ICmp.isSigned();
Chris Lattner2188e402010-01-04 07:37:31 +00002412
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002413 if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002414 // Not an extension from the same type?
2415 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002416 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00002417 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002418
Chris Lattner2188e402010-01-04 07:37:31 +00002419 // If the signedness of the two casts doesn't agree (i.e. one is a sext
2420 // and the other is a zext), then we can't handle this.
2421 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00002422 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002423
2424 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002425 if (ICmp.isEquality())
2426 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002427
2428 // A signed comparison of sign extended values simplifies into a
2429 // signed comparison.
2430 if (isSignedCmp && isSignedExt)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002431 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002432
2433 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002434 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002435 }
2436
Sanjay Patel4c204232016-06-04 20:39:22 +00002437 // If we aren't dealing with a constant on the RHS, exit early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002438 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
2439 if (!C)
Craig Topperf40110f2014-04-25 05:29:35 +00002440 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002441
2442 // Compute the constant that would happen if we truncated to SrcTy then
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002443 // re-extended to DestTy.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002444 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002445 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattner2188e402010-01-04 07:37:31 +00002446
2447 // If the re-extended constant didn't change...
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002448 if (Res2 == C) {
Chris Lattner2188e402010-01-04 07:37:31 +00002449 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002450 if (ICmp.isEquality())
2451 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002452
2453 // A signed comparison of sign extended values simplifies into a
2454 // signed comparison.
2455 if (isSignedExt && isSignedCmp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002456 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002457
2458 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002459 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002460 }
2461
Jim Grosbach129c52a2011-09-30 18:09:53 +00002462 // The re-extended constant changed so the constant cannot be represented
Chris Lattner2188e402010-01-04 07:37:31 +00002463 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002464 // All the cases that fold to true or false will have already been handled
2465 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00002466
Duncan Sands8fb2c382011-01-20 13:21:55 +00002467 if (isSignedCmp || !isSignedExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002468 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002469
2470 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
2471 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002472
2473 // We're performing an unsigned comp with a sign extended value.
2474 // This is true if the input is >= 0. [aka >s -1]
2475 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002476 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00002477
2478 // Finally, return the value computed.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002479 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
2480 return replaceInstUsesWith(ICmp, Result);
Chris Lattner2188e402010-01-04 07:37:31 +00002481
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002482 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00002483 return BinaryOperator::CreateNot(Result);
2484}
2485
Sanjay Patel5f0217f2016-06-05 16:46:18 +00002486/// The caller has matched a pattern of the form:
Chris Lattneree61c1d2010-12-19 17:52:50 +00002487/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00002488/// If this is of the form:
2489/// sum = a + b
2490/// if (sum+128 >u 255)
2491/// Then replace it with llvm.sadd.with.overflow.i8.
2492///
Chris Lattneree61c1d2010-12-19 17:52:50 +00002493static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2494 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00002495 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00002496 // The transformation we're trying to do here is to transform this into an
2497 // llvm.sadd.with.overflow. To do this, we have to replace the original add
2498 // with a narrower add, and discard the add-with-constant that is part of the
2499 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00002500
Chris Lattnerf29562d2010-12-19 17:59:02 +00002501 // In order to eliminate the add-with-constant, the compare can be its only
2502 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00002503 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00002504 if (!AddWithCst->hasOneUse()) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002505
Chris Lattnerc56c8452010-12-19 18:22:06 +00002506 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
Craig Topperf40110f2014-04-25 05:29:35 +00002507 if (!CI2->getValue().isPowerOf2()) return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002508 unsigned NewWidth = CI2->getValue().countTrailingZeros();
Craig Topperf40110f2014-04-25 05:29:35 +00002509 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002510
Chris Lattnerc56c8452010-12-19 18:22:06 +00002511 // The width of the new add formed is 1 more than the bias.
2512 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002513
Chris Lattnerc56c8452010-12-19 18:22:06 +00002514 // Check to see that CI1 is an all-ones value with NewWidth bits.
2515 if (CI1->getBitWidth() == NewWidth ||
2516 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
Craig Topperf40110f2014-04-25 05:29:35 +00002517 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002518
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002519 // This is only really a signed overflow check if the inputs have been
2520 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2521 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2522 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
Hal Finkel60db0582014-09-07 18:57:58 +00002523 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2524 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
Craig Topperf40110f2014-04-25 05:29:35 +00002525 return nullptr;
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002526
Jim Grosbach129c52a2011-09-30 18:09:53 +00002527 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00002528 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2529 // and truncates that discard the high bits of the add. Verify that this is
2530 // the case.
2531 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00002532 for (User *U : OrigAdd->users()) {
2533 if (U == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002534
Chris Lattnerc56c8452010-12-19 18:22:06 +00002535 // Only accept truncates for now. We would really like a nice recursive
2536 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2537 // chain to see which bits of a value are actually demanded. If the
2538 // original add had another add which was then immediately truncated, we
2539 // could still do the transformation.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002540 TruncInst *TI = dyn_cast<TruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00002541 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2542 return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002543 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002544
Chris Lattneree61c1d2010-12-19 17:52:50 +00002545 // If the pattern matches, truncate the inputs to the narrower type and
2546 // use the sadd_with_overflow intrinsic to efficiently compute both the
2547 // result and the overflow bit.
Jay Foadb804a2b2011-07-12 14:06:48 +00002548 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002549 Value *F = Intrinsic::getDeclaration(I.getModule(),
2550 Intrinsic::sadd_with_overflow, NewType);
Chris Lattner79874562010-12-19 18:35:09 +00002551
Chris Lattnerce2995a2010-12-19 18:38:44 +00002552 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002553
Chris Lattner79874562010-12-19 18:35:09 +00002554 // Put the new code above the original add, in case there are any uses of the
2555 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002556 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002557
Chris Lattner79874562010-12-19 18:35:09 +00002558 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2559 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
David Blaikieff6409d2015-05-18 22:13:54 +00002560 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
Chris Lattner79874562010-12-19 18:35:09 +00002561 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2562 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002563
Chris Lattneree61c1d2010-12-19 17:52:50 +00002564 // The inner add was the result of the narrow add, zero extended to the
2565 // wider type. Replace it with the result computed by the intrinsic.
Sanjay Patel4b198802016-02-01 22:23:39 +00002566 IC.replaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002567
Chris Lattner79874562010-12-19 18:35:09 +00002568 // The original icmp gets replaced with the overflow value.
2569 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00002570}
Chris Lattner2188e402010-01-04 07:37:31 +00002571
Sanjoy Dasb0984472015-04-08 04:27:22 +00002572bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
2573 Value *RHS, Instruction &OrigI,
2574 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00002575 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
2576 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002577
2578 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
2579 Result = OpResult;
2580 Overflow = OverflowVal;
2581 if (ReuseName)
2582 Result->takeName(&OrigI);
2583 return true;
2584 };
2585
Sanjoy Das6f5dca72015-08-28 19:09:31 +00002586 // If the overflow check was an add followed by a compare, the insertion point
2587 // may be pointing to the compare. We want to insert the new instructions
2588 // before the add in case there are uses of the add between the add and the
2589 // compare.
2590 Builder->SetInsertPoint(&OrigI);
2591
Sanjoy Dasb0984472015-04-08 04:27:22 +00002592 switch (OCF) {
2593 case OCF_INVALID:
2594 llvm_unreachable("bad overflow check kind!");
2595
2596 case OCF_UNSIGNED_ADD: {
2597 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
2598 if (OR == OverflowResult::NeverOverflows)
2599 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
2600 true);
2601
2602 if (OR == OverflowResult::AlwaysOverflows)
2603 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
2604 }
2605 // FALL THROUGH uadd into sadd
2606 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002607 // X + 0 -> {X, false}
2608 if (match(RHS, m_Zero()))
2609 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002610
2611 // We can strength reduce this signed add into a regular add if we can prove
2612 // that it will never overflow.
2613 if (OCF == OCF_SIGNED_ADD)
2614 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
2615 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
2616 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00002617 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002618 }
2619
2620 case OCF_UNSIGNED_SUB:
2621 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002622 // X - 0 -> {X, false}
2623 if (match(RHS, m_Zero()))
2624 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002625
2626 if (OCF == OCF_SIGNED_SUB) {
2627 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
2628 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
2629 true);
2630 } else {
2631 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
2632 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
2633 true);
2634 }
2635 break;
2636 }
2637
2638 case OCF_UNSIGNED_MUL: {
2639 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
2640 if (OR == OverflowResult::NeverOverflows)
2641 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
2642 true);
2643 if (OR == OverflowResult::AlwaysOverflows)
2644 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
2645 } // FALL THROUGH
2646 case OCF_SIGNED_MUL:
2647 // X * undef -> undef
2648 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00002649 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002650
David Majnemer27e89ba2015-05-21 23:04:21 +00002651 // X * 0 -> {0, false}
2652 if (match(RHS, m_Zero()))
2653 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002654
David Majnemer27e89ba2015-05-21 23:04:21 +00002655 // X * 1 -> {X, false}
2656 if (match(RHS, m_One()))
2657 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002658
2659 if (OCF == OCF_SIGNED_MUL)
2660 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
2661 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
2662 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00002663 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002664 }
2665
2666 return false;
2667}
2668
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002669/// \brief Recognize and process idiom involving test for multiplication
2670/// overflow.
2671///
2672/// The caller has matched a pattern of the form:
2673/// I = cmp u (mul(zext A, zext B), V
2674/// The function checks if this is a test for overflow and if so replaces
2675/// multiplication with call to 'mul.with.overflow' intrinsic.
2676///
2677/// \param I Compare instruction.
2678/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2679/// the compare instruction. Must be of integer type.
2680/// \param OtherVal The other argument of compare instruction.
2681/// \returns Instruction which must replace the compare instruction, NULL if no
2682/// replacement required.
2683static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2684 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00002685 // Don't bother doing this transformation for pointers, don't do it for
2686 // vectors.
2687 if (!isa<IntegerType>(MulVal->getType()))
2688 return nullptr;
2689
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002690 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2691 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00002692 auto *MulInstr = dyn_cast<Instruction>(MulVal);
2693 if (!MulInstr)
2694 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002695 assert(MulInstr->getOpcode() == Instruction::Mul);
2696
David Majnemer634ca232014-11-01 23:46:05 +00002697 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
2698 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002699 assert(LHS->getOpcode() == Instruction::ZExt);
2700 assert(RHS->getOpcode() == Instruction::ZExt);
2701 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2702
2703 // Calculate type and width of the result produced by mul.with.overflow.
2704 Type *TyA = A->getType(), *TyB = B->getType();
2705 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2706 WidthB = TyB->getPrimitiveSizeInBits();
2707 unsigned MulWidth;
2708 Type *MulType;
2709 if (WidthB > WidthA) {
2710 MulWidth = WidthB;
2711 MulType = TyB;
2712 } else {
2713 MulWidth = WidthA;
2714 MulType = TyA;
2715 }
2716
2717 // In order to replace the original mul with a narrower mul.with.overflow,
2718 // all uses must ignore upper bits of the product. The number of used low
2719 // bits must be not greater than the width of mul.with.overflow.
2720 if (MulVal->hasNUsesOrMore(2))
2721 for (User *U : MulVal->users()) {
2722 if (U == &I)
2723 continue;
2724 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2725 // Check if truncation ignores bits above MulWidth.
2726 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2727 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002728 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002729 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2730 // Check if AND ignores bits above MulWidth.
2731 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00002732 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002733 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2734 const APInt &CVal = CI->getValue();
2735 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002736 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002737 }
2738 } else {
2739 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00002740 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002741 }
2742 }
2743
2744 // Recognize patterns
2745 switch (I.getPredicate()) {
2746 case ICmpInst::ICMP_EQ:
2747 case ICmpInst::ICMP_NE:
2748 // Recognize pattern:
2749 // mulval = mul(zext A, zext B)
2750 // cmp eq/neq mulval, zext trunc mulval
2751 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2752 if (Zext->hasOneUse()) {
2753 Value *ZextArg = Zext->getOperand(0);
2754 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2755 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2756 break; //Recognized
2757 }
2758
2759 // Recognize pattern:
2760 // mulval = mul(zext A, zext B)
2761 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2762 ConstantInt *CI;
2763 Value *ValToMask;
2764 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2765 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00002766 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002767 const APInt &CVal = CI->getValue() + 1;
2768 if (CVal.isPowerOf2()) {
2769 unsigned MaskWidth = CVal.logBase2();
2770 if (MaskWidth == MulWidth)
2771 break; // Recognized
2772 }
2773 }
Craig Topperf40110f2014-04-25 05:29:35 +00002774 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002775
2776 case ICmpInst::ICMP_UGT:
2777 // Recognize pattern:
2778 // mulval = mul(zext A, zext B)
2779 // cmp ugt mulval, max
2780 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2781 APInt MaxVal = APInt::getMaxValue(MulWidth);
2782 MaxVal = MaxVal.zext(CI->getBitWidth());
2783 if (MaxVal.eq(CI->getValue()))
2784 break; // Recognized
2785 }
Craig Topperf40110f2014-04-25 05:29:35 +00002786 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002787
2788 case ICmpInst::ICMP_UGE:
2789 // Recognize pattern:
2790 // mulval = mul(zext A, zext B)
2791 // cmp uge mulval, max+1
2792 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2793 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2794 if (MaxVal.eq(CI->getValue()))
2795 break; // Recognized
2796 }
Craig Topperf40110f2014-04-25 05:29:35 +00002797 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002798
2799 case ICmpInst::ICMP_ULE:
2800 // Recognize pattern:
2801 // mulval = mul(zext A, zext B)
2802 // cmp ule mulval, max
2803 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2804 APInt MaxVal = APInt::getMaxValue(MulWidth);
2805 MaxVal = MaxVal.zext(CI->getBitWidth());
2806 if (MaxVal.eq(CI->getValue()))
2807 break; // Recognized
2808 }
Craig Topperf40110f2014-04-25 05:29:35 +00002809 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002810
2811 case ICmpInst::ICMP_ULT:
2812 // Recognize pattern:
2813 // mulval = mul(zext A, zext B)
2814 // cmp ule mulval, max + 1
2815 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002816 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002817 if (MaxVal.eq(CI->getValue()))
2818 break; // Recognized
2819 }
Craig Topperf40110f2014-04-25 05:29:35 +00002820 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002821
2822 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002823 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002824 }
2825
2826 InstCombiner::BuilderTy *Builder = IC.Builder;
2827 Builder->SetInsertPoint(MulInstr);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002828
2829 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2830 Value *MulA = A, *MulB = B;
2831 if (WidthA < MulWidth)
2832 MulA = Builder->CreateZExt(A, MulType);
2833 if (WidthB < MulWidth)
2834 MulB = Builder->CreateZExt(B, MulType);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002835 Value *F = Intrinsic::getDeclaration(I.getModule(),
2836 Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00002837 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002838 IC.Worklist.Add(MulInstr);
2839
2840 // If there are uses of mul result other than the comparison, we know that
2841 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002842 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002843 if (MulVal->hasNUsesOrMore(2)) {
2844 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2845 for (User *U : MulVal->users()) {
2846 if (U == &I || U == OtherVal)
2847 continue;
2848 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2849 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
Sanjay Patel4b198802016-02-01 22:23:39 +00002850 IC.replaceInstUsesWith(*TI, Mul);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002851 else
2852 TI->setOperand(0, Mul);
2853 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2854 assert(BO->getOpcode() == Instruction::And);
2855 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2856 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2857 APInt ShortMask = CI->getValue().trunc(MulWidth);
2858 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2859 Instruction *Zext =
2860 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2861 IC.Worklist.Add(Zext);
Sanjay Patel4b198802016-02-01 22:23:39 +00002862 IC.replaceInstUsesWith(*BO, Zext);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002863 } else {
2864 llvm_unreachable("Unexpected Binary operation");
2865 }
2866 IC.Worklist.Add(cast<Instruction>(U));
2867 }
2868 }
2869 if (isa<Instruction>(OtherVal))
2870 IC.Worklist.Add(cast<Instruction>(OtherVal));
2871
2872 // The original icmp gets replaced with the overflow value, maybe inverted
2873 // depending on predicate.
2874 bool Inverse = false;
2875 switch (I.getPredicate()) {
2876 case ICmpInst::ICMP_NE:
2877 break;
2878 case ICmpInst::ICMP_EQ:
2879 Inverse = true;
2880 break;
2881 case ICmpInst::ICMP_UGT:
2882 case ICmpInst::ICMP_UGE:
2883 if (I.getOperand(0) == MulVal)
2884 break;
2885 Inverse = true;
2886 break;
2887 case ICmpInst::ICMP_ULT:
2888 case ICmpInst::ICMP_ULE:
2889 if (I.getOperand(1) == MulVal)
2890 break;
2891 Inverse = true;
2892 break;
2893 default:
2894 llvm_unreachable("Unexpected predicate");
2895 }
2896 if (Inverse) {
2897 Value *Res = Builder->CreateExtractValue(Call, 1);
2898 return BinaryOperator::CreateNot(Res);
2899 }
2900
2901 return ExtractValueInst::Create(Call, 1);
2902}
2903
Sanjay Patel5f0217f2016-06-05 16:46:18 +00002904/// When performing a comparison against a constant, it is possible that not all
2905/// the bits in the LHS are demanded. This helper method computes the mask that
2906/// IS demanded.
Owen Andersond490c2d2011-01-11 00:36:45 +00002907static APInt DemandedBitsLHSMask(ICmpInst &I,
2908 unsigned BitWidth, bool isSignCheck) {
2909 if (isSignCheck)
2910 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002911
Owen Andersond490c2d2011-01-11 00:36:45 +00002912 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2913 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00002914 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002915
Owen Andersond490c2d2011-01-11 00:36:45 +00002916 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002917 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00002918 // correspond to the trailing ones of the comparand. The value of these
2919 // bits doesn't impact the outcome of the comparison, because any value
2920 // greater than the RHS must differ in a bit higher than these due to carry.
2921 case ICmpInst::ICMP_UGT: {
2922 unsigned trailingOnes = RHS.countTrailingOnes();
2923 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2924 return ~lowBitsSet;
2925 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002926
Owen Andersond490c2d2011-01-11 00:36:45 +00002927 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2928 // Any value less than the RHS must differ in a higher bit because of carries.
2929 case ICmpInst::ICMP_ULT: {
2930 unsigned trailingZeros = RHS.countTrailingZeros();
2931 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2932 return ~lowBitsSet;
2933 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002934
Owen Andersond490c2d2011-01-11 00:36:45 +00002935 default:
2936 return APInt::getAllOnesValue(BitWidth);
2937 }
Owen Andersond490c2d2011-01-11 00:36:45 +00002938}
Chris Lattner2188e402010-01-04 07:37:31 +00002939
Quentin Colombet5ab55552013-09-09 20:56:48 +00002940/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2941/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00002942/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00002943/// as subtract operands and their positions in those instructions.
2944/// The rational is that several architectures use the same instruction for
2945/// both subtract and cmp, thus it is better if the order of those operands
2946/// match.
2947/// \return true if Op0 and Op1 should be swapped.
2948static bool swapMayExposeCSEOpportunities(const Value * Op0,
2949 const Value * Op1) {
2950 // Filter out pointer value as those cannot appears directly in subtract.
2951 // FIXME: we may want to go through inttoptrs or bitcasts.
2952 if (Op0->getType()->isPointerTy())
2953 return false;
2954 // Count every uses of both Op0 and Op1 in a subtract.
2955 // Each time Op0 is the first operand, count -1: swapping is bad, the
2956 // subtract has already the same layout as the compare.
2957 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00002958 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002959 // At the end, if the benefit is greater than 0, Op0 should come second to
2960 // expose more CSE opportunities.
2961 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002962 for (const User *U : Op0->users()) {
2963 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002964 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2965 continue;
2966 // If Op0 is the first argument, this is not beneficial to swap the
2967 // arguments.
2968 int LocalSwapBenefits = -1;
2969 unsigned Op1Idx = 1;
2970 if (BinOp->getOperand(Op1Idx) == Op0) {
2971 Op1Idx = 0;
2972 LocalSwapBenefits = 1;
2973 }
2974 if (BinOp->getOperand(Op1Idx) != Op1)
2975 continue;
2976 GlobalSwapBenefits += LocalSwapBenefits;
2977 }
2978 return GlobalSwapBenefits > 0;
2979}
2980
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00002981/// \brief Check that one use is in the same block as the definition and all
2982/// other uses are in blocks dominated by a given block
2983///
2984/// \param DI Definition
2985/// \param UI Use
2986/// \param DB Block that must dominate all uses of \p DI outside
2987/// the parent block
2988/// \return true when \p UI is the only use of \p DI in the parent block
2989/// and all other uses of \p DI are in blocks dominated by \p DB.
2990///
2991bool InstCombiner::dominatesAllUses(const Instruction *DI,
2992 const Instruction *UI,
2993 const BasicBlock *DB) const {
2994 assert(DI && UI && "Instruction not defined\n");
2995 // ignore incomplete definitions
2996 if (!DI->getParent())
2997 return false;
2998 // DI and UI must be in the same block
2999 if (DI->getParent() != UI->getParent())
3000 return false;
3001 // Protect from self-referencing blocks
3002 if (DI->getParent() == DB)
3003 return false;
3004 // DominatorTree available?
3005 if (!DT)
3006 return false;
3007 for (const User *U : DI->users()) {
3008 auto *Usr = cast<Instruction>(U);
3009 if (Usr != UI && !DT->dominates(DB, Usr->getParent()))
3010 return false;
3011 }
3012 return true;
3013}
3014
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003015/// Return true when the instruction sequence within a block is select-cmp-br.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003016static bool isChainSelectCmpBranch(const SelectInst *SI) {
3017 const BasicBlock *BB = SI->getParent();
3018 if (!BB)
3019 return false;
3020 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
3021 if (!BI || BI->getNumSuccessors() != 2)
3022 return false;
3023 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
3024 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
3025 return false;
3026 return true;
3027}
3028
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003029/// \brief True when a select result is replaced by one of its operands
3030/// in select-icmp sequence. This will eventually result in the elimination
3031/// of the select.
3032///
3033/// \param SI Select instruction
3034/// \param Icmp Compare instruction
3035/// \param SIOpd Operand that replaces the select
3036///
3037/// Notes:
3038/// - The replacement is global and requires dominator information
3039/// - The caller is responsible for the actual replacement
3040///
3041/// Example:
3042///
3043/// entry:
3044/// %4 = select i1 %3, %C* %0, %C* null
3045/// %5 = icmp eq %C* %4, null
3046/// br i1 %5, label %9, label %7
3047/// ...
3048/// ; <label>:7 ; preds = %entry
3049/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
3050/// ...
3051///
3052/// can be transformed to
3053///
3054/// %5 = icmp eq %C* %0, null
3055/// %6 = select i1 %3, i1 %5, i1 true
3056/// br i1 %6, label %9, label %7
3057/// ...
3058/// ; <label>:7 ; preds = %entry
3059/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
3060///
3061/// Similar when the first operand of the select is a constant or/and
3062/// the compare is for not equal rather than equal.
3063///
3064/// NOTE: The function is only called when the select and compare constants
3065/// are equal, the optimization can work only for EQ predicates. This is not a
3066/// major restriction since a NE compare should be 'normalized' to an equal
3067/// compare, which usually happens in the combiner and test case
3068/// select-cmp-br.ll
3069/// checks for it.
3070bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
3071 const ICmpInst *Icmp,
3072 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00003073 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003074 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
3075 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
3076 // The check for the unique predecessor is not the best that can be
3077 // done. But it protects efficiently against cases like when SI's
3078 // home block has two successors, Succ and Succ1, and Succ1 predecessor
3079 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
3080 // replaced can be reached on either path. So the uniqueness check
3081 // guarantees that the path all uses of SI (outside SI's parent) are on
3082 // is disjoint from all other paths out of SI. But that information
3083 // is more expensive to compute, and the trade-off here is in favor
3084 // of compile-time.
3085 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
3086 NumSel++;
3087 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
3088 return true;
3089 }
3090 }
3091 return false;
3092}
3093
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003094/// If we have an icmp le or icmp ge instruction with a constant operand, turn
3095/// it into the appropriate icmp lt or icmp gt instruction. This transform
3096/// allows them to be folded in visitICmpInst.
Sanjay Patele9b2c322016-05-17 00:57:57 +00003097static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
3098 ICmpInst::Predicate Pred = I.getPredicate();
3099 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE &&
3100 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE)
3101 return nullptr;
3102
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003103 Value *Op0 = I.getOperand(0);
3104 Value *Op1 = I.getOperand(1);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003105 auto *Op1C = dyn_cast<Constant>(Op1);
3106 if (!Op1C)
3107 return nullptr;
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003108
Sanjay Patele9b2c322016-05-17 00:57:57 +00003109 // Check if the constant operand can be safely incremented/decremented without
3110 // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled
3111 // the edge cases for us, so we just assert on them. For vectors, we must
3112 // handle the edge cases.
3113 Type *Op1Type = Op1->getType();
3114 bool IsSigned = I.isSigned();
3115 bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE);
Sanjay Patel18254932016-05-17 01:12:31 +00003116 auto *CI = dyn_cast<ConstantInt>(Op1C);
3117 if (CI) {
Sanjay Patele9b2c322016-05-17 00:57:57 +00003118 // A <= MAX -> TRUE ; A >= MIN -> TRUE
3119 assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned));
3120 } else if (Op1Type->isVectorTy()) {
Sanjay Patelb79ab272016-05-13 15:10:46 +00003121 // TODO? If the edge cases for vectors were guaranteed to be handled as they
Sanjay Patele9b2c322016-05-17 00:57:57 +00003122 // are for scalar, we could remove the min/max checks. However, to do that,
3123 // we would have to use insertelement/shufflevector to replace edge values.
3124 unsigned NumElts = Op1Type->getVectorNumElements();
3125 for (unsigned i = 0; i != NumElts; ++i) {
3126 Constant *Elt = Op1C->getAggregateElement(i);
Benjamin Kramerca9a0fe2016-05-17 12:08:55 +00003127 if (!Elt)
3128 return nullptr;
3129
Sanjay Patele9b2c322016-05-17 00:57:57 +00003130 if (isa<UndefValue>(Elt))
3131 continue;
3132 // Bail out if we can't determine if this constant is min/max or if we
3133 // know that this constant is min/max.
3134 auto *CI = dyn_cast<ConstantInt>(Elt);
3135 if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned)))
3136 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003137 }
Sanjay Patele9b2c322016-05-17 00:57:57 +00003138 } else {
3139 // ConstantExpr?
3140 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003141 }
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003142
Sanjay Patele9b2c322016-05-17 00:57:57 +00003143 // Increment or decrement the constant and set the new comparison predicate:
3144 // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT
Sanjay Patel22b01fe2016-05-17 20:20:40 +00003145 Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003146 CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT;
3147 NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred;
3148 return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne));
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003149}
3150
Chris Lattner2188e402010-01-04 07:37:31 +00003151Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
3152 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00003153 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003154 unsigned Op0Cplxity = getComplexity(Op0);
3155 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003156
Chris Lattner2188e402010-01-04 07:37:31 +00003157 /// Orders the operands of the compare so that they are listed from most
3158 /// complex to least complex. This puts constants before unary operators,
3159 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003160 if (Op0Cplxity < Op1Cplxity ||
Sanjay Patel4c204232016-06-04 20:39:22 +00003161 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003162 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00003163 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003164 Changed = true;
3165 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003166
Jingyue Wu5e34ce32015-06-25 20:14:47 +00003167 if (Value *V =
3168 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00003169 return replaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003170
Pete Cooperbc5c5242011-12-01 03:58:40 +00003171 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00003172 // ie, abs(val) != 0 -> val != 0
Sanjay Patel4c204232016-06-04 20:39:22 +00003173 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003174 Value *Cond, *SelectTrue, *SelectFalse;
3175 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00003176 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003177 if (Value *V = dyn_castNegVal(SelectTrue)) {
3178 if (V == SelectFalse)
3179 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
3180 }
3181 else if (Value *V = dyn_castNegVal(SelectFalse)) {
3182 if (V == SelectTrue)
3183 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00003184 }
3185 }
3186 }
3187
Chris Lattner229907c2011-07-18 04:54:35 +00003188 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00003189
3190 // icmp's with boolean values can always be turned into bitwise operations
Sanjay Patela6fbc822016-06-05 17:49:45 +00003191 if (Ty->getScalarType()->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00003192 switch (I.getPredicate()) {
3193 default: llvm_unreachable("Invalid icmp instruction!");
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003194 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
3195 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003196 return BinaryOperator::CreateNot(Xor);
3197 }
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003198 case ICmpInst::ICMP_NE: // icmp ne i1 A, B -> A^B
Chris Lattner2188e402010-01-04 07:37:31 +00003199 return BinaryOperator::CreateXor(Op0, Op1);
3200
3201 case ICmpInst::ICMP_UGT:
3202 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
3203 // FALL THROUGH
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003204 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
3205 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003206 return BinaryOperator::CreateAnd(Not, Op1);
3207 }
3208 case ICmpInst::ICMP_SGT:
3209 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
3210 // FALL THROUGH
3211 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003212 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003213 return BinaryOperator::CreateAnd(Not, Op0);
3214 }
3215 case ICmpInst::ICMP_UGE:
3216 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
3217 // FALL THROUGH
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003218 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
3219 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003220 return BinaryOperator::CreateOr(Not, Op1);
3221 }
3222 case ICmpInst::ICMP_SGE:
3223 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
3224 // FALL THROUGH
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003225 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
3226 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003227 return BinaryOperator::CreateOr(Not, Op0);
3228 }
3229 }
3230 }
3231
Sanjay Patele9b2c322016-05-17 00:57:57 +00003232 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003233 return NewICmp;
3234
Chris Lattner2188e402010-01-04 07:37:31 +00003235 unsigned BitWidth = 0;
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003236 if (Ty->isIntOrIntVectorTy())
Chris Lattner2188e402010-01-04 07:37:31 +00003237 BitWidth = Ty->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003238 else // Get pointer size.
3239 BitWidth = DL.getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00003240
Chris Lattner2188e402010-01-04 07:37:31 +00003241 bool isSignBit = false;
3242
3243 // See if we are doing a comparison with a constant.
3244 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00003245 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003246
Owen Anderson1294ea72010-12-17 18:08:00 +00003247 // Match the following pattern, which is a common idiom when writing
3248 // overflow-safe integer arithmetic function. The source performs an
3249 // addition in wider type, and explicitly checks for overflow using
3250 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
3251 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00003252 //
3253 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00003254 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00003255 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003256 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00003257 // sum = a + b
3258 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00003259 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00003260 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00003261 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00003262 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00003263 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00003264 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00003265 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003266
Philip Reamesec8a8b52016-03-09 21:05:07 +00003267 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
3268 if (CI->isZero() && I.getPredicate() == ICmpInst::ICMP_SGT)
3269 if (auto *SI = dyn_cast<SelectInst>(Op0)) {
3270 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
3271 if (SPR.Flavor == SPF_SMIN) {
Philip Reames8f12eba2016-03-09 21:31:47 +00003272 if (isKnownPositive(A, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003273 return new ICmpInst(I.getPredicate(), B, CI);
Philip Reames8f12eba2016-03-09 21:31:47 +00003274 if (isKnownPositive(B, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003275 return new ICmpInst(I.getPredicate(), A, CI);
3276 }
3277 }
3278
3279
David Majnemera0afb552015-01-14 19:26:56 +00003280 // The following transforms are only 'worth it' if the only user of the
3281 // subtraction is the icmp.
3282 if (Op0->hasOneUse()) {
3283 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
3284 if (I.isEquality() && CI->isZero() &&
3285 match(Op0, m_Sub(m_Value(A), m_Value(B))))
3286 return new ICmpInst(I.getPredicate(), A, B);
3287
3288 // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
3289 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
3290 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3291 return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
3292
3293 // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
3294 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
3295 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3296 return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
3297
3298 // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
3299 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
3300 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3301 return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
3302
3303 // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
3304 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
3305 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3306 return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
Chris Lattner2188e402010-01-04 07:37:31 +00003307 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003308
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003309 if (I.isEquality()) {
3310 ConstantInt *CI2;
3311 if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
3312 match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
David Majnemer59939ac2014-10-19 08:23:08 +00003313 // (icmp eq/ne (ashr/lshr const2, A), const1)
David Majnemer2abb8182014-10-25 07:13:13 +00003314 if (Instruction *Inst = FoldICmpCstShrCst(I, Op0, A, CI, CI2))
3315 return Inst;
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003316 }
David Majnemer59939ac2014-10-19 08:23:08 +00003317 if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
3318 // (icmp eq/ne (shl const2, A), const1)
David Majnemer2abb8182014-10-25 07:13:13 +00003319 if (Instruction *Inst = FoldICmpCstShlCst(I, Op0, A, CI, CI2))
3320 return Inst;
David Majnemer59939ac2014-10-19 08:23:08 +00003321 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003322 }
3323
Chris Lattner2188e402010-01-04 07:37:31 +00003324 // If this comparison is a normal comparison, it demands all
3325 // bits, if it is a sign bit comparison, it only demands the sign bit.
3326 bool UnusedBit;
3327 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
Balaram Makam569eaec2016-05-04 21:32:14 +00003328
3329 // Canonicalize icmp instructions based on dominating conditions.
3330 BasicBlock *Parent = I.getParent();
3331 BasicBlock *Dom = Parent->getSinglePredecessor();
3332 auto *BI = Dom ? dyn_cast<BranchInst>(Dom->getTerminator()) : nullptr;
3333 ICmpInst::Predicate Pred;
3334 BasicBlock *TrueBB, *FalseBB;
3335 ConstantInt *CI2;
3336 if (BI && match(BI, m_Br(m_ICmp(Pred, m_Specific(Op0), m_ConstantInt(CI2)),
3337 TrueBB, FalseBB)) &&
3338 TrueBB != FalseBB) {
3339 ConstantRange CR = ConstantRange::makeAllowedICmpRegion(I.getPredicate(),
3340 CI->getValue());
3341 ConstantRange DominatingCR =
3342 (Parent == TrueBB)
3343 ? ConstantRange::makeExactICmpRegion(Pred, CI2->getValue())
3344 : ConstantRange::makeExactICmpRegion(
3345 CmpInst::getInversePredicate(Pred), CI2->getValue());
3346 ConstantRange Intersection = DominatingCR.intersectWith(CR);
3347 ConstantRange Difference = DominatingCR.difference(CR);
3348 if (Intersection.isEmptySet())
3349 return replaceInstUsesWith(I, Builder->getFalse());
3350 if (Difference.isEmptySet())
3351 return replaceInstUsesWith(I, Builder->getTrue());
3352 // Canonicalizing a sign bit comparison that gets used in a branch,
3353 // pessimizes codegen by generating branch on zero instruction instead
3354 // of a test and branch. So we avoid canonicalizing in such situations
3355 // because test and branch instruction has better branch displacement
3356 // than compare and branch instruction.
3357 if (!isBranchOnSignBitCheck(I, isSignBit) && !I.isEquality()) {
3358 if (auto *AI = Intersection.getSingleElement())
3359 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Builder->getInt(*AI));
3360 if (auto *AD = Difference.getSingleElement())
3361 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Builder->getInt(*AD));
3362 }
3363 }
Chris Lattner2188e402010-01-04 07:37:31 +00003364 }
3365
3366 // See if we can fold the comparison based on range information we can get
3367 // by checking whether bits are known to be zero or one in the input.
3368 if (BitWidth != 0) {
3369 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
3370 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
3371
3372 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersond490c2d2011-01-11 00:36:45 +00003373 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner2188e402010-01-04 07:37:31 +00003374 Op0KnownZero, Op0KnownOne, 0))
3375 return &I;
3376 if (SimplifyDemandedBits(I.getOperandUse(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003377 APInt::getAllOnesValue(BitWidth), Op1KnownZero,
3378 Op1KnownOne, 0))
Chris Lattner2188e402010-01-04 07:37:31 +00003379 return &I;
3380
3381 // Given the known and unknown bits, compute a range that the LHS could be
3382 // in. Compute the Min, Max and RHS values based on the known bits. For the
3383 // EQ and NE we use unsigned values.
3384 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
3385 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
3386 if (I.isSigned()) {
3387 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3388 Op0Min, Op0Max);
3389 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3390 Op1Min, Op1Max);
3391 } else {
3392 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3393 Op0Min, Op0Max);
3394 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3395 Op1Min, Op1Max);
3396 }
3397
3398 // If Min and Max are known to be the same, then SimplifyDemandedBits
3399 // figured out that the LHS is a constant. Just constant fold this now so
3400 // that code below can assume that Min != Max.
3401 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
3402 return new ICmpInst(I.getPredicate(),
Nick Lewycky92db8e82011-03-06 03:36:19 +00003403 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003404 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
3405 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewycky92db8e82011-03-06 03:36:19 +00003406 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner2188e402010-01-04 07:37:31 +00003407
3408 // Based on the range information we know about the LHS, see if we can
Nick Lewycky6b4454192011-02-28 06:20:05 +00003409 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner2188e402010-01-04 07:37:31 +00003410 switch (I.getPredicate()) {
3411 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattnerf7e89612010-11-21 06:44:42 +00003412 case ICmpInst::ICMP_EQ: {
Chris Lattner2188e402010-01-04 07:37:31 +00003413 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003414 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003415
Chris Lattnerf7e89612010-11-21 06:44:42 +00003416 // If all bits are known zero except for one, then we know at most one
3417 // bit is set. If the comparison is against zero, then this is a check
3418 // to see if *that* bit is set.
3419 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003420 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003421 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003422 Value *LHS = nullptr;
3423 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003424 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3425 LHSC->getValue() != Op0KnownZeroInverted)
3426 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003427
Chris Lattnerf7e89612010-11-21 06:44:42 +00003428 // 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 +00003429 // then turn "((1 << x)&8) == 0" into "x != 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003430 // or turn "((1 << x)&7) == 0" into "x > 2".
Craig Topperf40110f2014-04-25 05:29:35 +00003431 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003432 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003433 APInt ValToCheck = Op0KnownZeroInverted;
3434 if (ValToCheck.isPowerOf2()) {
3435 unsigned CmpVal = ValToCheck.countTrailingZeros();
3436 return new ICmpInst(ICmpInst::ICMP_NE, X,
3437 ConstantInt::get(X->getType(), CmpVal));
3438 } else if ((++ValToCheck).isPowerOf2()) {
3439 unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
3440 return new ICmpInst(ICmpInst::ICMP_UGT, X,
3441 ConstantInt::get(X->getType(), CmpVal));
3442 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003443 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003444
Chris Lattnerf7e89612010-11-21 06:44:42 +00003445 // 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 +00003446 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattner98457102011-02-10 05:23:05 +00003447 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003448 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003449 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003450 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner98457102011-02-10 05:23:05 +00003451 ConstantInt::get(X->getType(),
3452 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003453 }
Chris Lattner2188e402010-01-04 07:37:31 +00003454 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003455 }
3456 case ICmpInst::ICMP_NE: {
Chris Lattner2188e402010-01-04 07:37:31 +00003457 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003458 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003459
Chris Lattnerf7e89612010-11-21 06:44:42 +00003460 // If all bits are known zero except for one, then we know at most one
3461 // bit is set. If the comparison is against zero, then this is a check
3462 // to see if *that* bit is set.
3463 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003464 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003465 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003466 Value *LHS = nullptr;
3467 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003468 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3469 LHSC->getValue() != Op0KnownZeroInverted)
3470 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003471
Chris Lattnerf7e89612010-11-21 06:44:42 +00003472 // 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 +00003473 // then turn "((1 << x)&8) != 0" into "x == 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003474 // or turn "((1 << x)&7) != 0" into "x < 3".
Craig Topperf40110f2014-04-25 05:29:35 +00003475 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003476 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003477 APInt ValToCheck = Op0KnownZeroInverted;
3478 if (ValToCheck.isPowerOf2()) {
3479 unsigned CmpVal = ValToCheck.countTrailingZeros();
3480 return new ICmpInst(ICmpInst::ICMP_EQ, X,
3481 ConstantInt::get(X->getType(), CmpVal));
3482 } else if ((++ValToCheck).isPowerOf2()) {
3483 unsigned CmpVal = ValToCheck.countTrailingZeros();
3484 return new ICmpInst(ICmpInst::ICMP_ULT, X,
3485 ConstantInt::get(X->getType(), CmpVal));
3486 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003487 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003488
Chris Lattnerf7e89612010-11-21 06:44:42 +00003489 // 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 +00003490 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattner98457102011-02-10 05:23:05 +00003491 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003492 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003493 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003494 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner98457102011-02-10 05:23:05 +00003495 ConstantInt::get(X->getType(),
3496 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003497 }
Chris Lattner2188e402010-01-04 07:37:31 +00003498 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003499 }
Chris Lattner2188e402010-01-04 07:37:31 +00003500 case ICmpInst::ICMP_ULT:
3501 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003502 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003503 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003504 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003505 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
3506 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3507 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3508 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
3509 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003510 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003511
3512 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
3513 if (CI->isMinValue(true))
3514 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
3515 Constant::getAllOnesValue(Op0->getType()));
3516 }
3517 break;
3518 case ICmpInst::ICMP_UGT:
3519 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003520 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003521 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003522 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003523
3524 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
3525 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3526 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3527 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
3528 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003529 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003530
3531 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
3532 if (CI->isMaxValue(true))
3533 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
3534 Constant::getNullValue(Op0->getType()));
3535 }
3536 break;
3537 case ICmpInst::ICMP_SLT:
3538 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003539 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003540 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003541 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003542 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
3543 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3544 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3545 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
3546 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003547 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003548 }
3549 break;
3550 case ICmpInst::ICMP_SGT:
3551 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003552 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003553 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003554 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003555
3556 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
3557 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3558 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3559 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
3560 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003561 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003562 }
3563 break;
3564 case ICmpInst::ICMP_SGE:
3565 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
3566 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003567 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003568 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003569 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003570 break;
3571 case ICmpInst::ICMP_SLE:
3572 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
3573 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003574 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003575 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003576 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003577 break;
3578 case ICmpInst::ICMP_UGE:
3579 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
3580 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003581 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003582 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003583 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003584 break;
3585 case ICmpInst::ICMP_ULE:
3586 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
3587 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003588 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003589 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003590 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003591 break;
3592 }
3593
3594 // Turn a signed comparison into an unsigned one if both operands
3595 // are known to have the same sign.
3596 if (I.isSigned() &&
3597 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
3598 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
3599 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
3600 }
3601
3602 // Test if the ICmpInst instruction is used exclusively by a select as
3603 // part of a minimum or maximum operation. If so, refrain from doing
3604 // any other folding. This helps out other analyses which understand
3605 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
3606 // and CodeGen. And in this case, at least one of the comparison
3607 // operands has at least one user besides the compare (the select),
3608 // which would often largely negate the benefit of folding anyway.
3609 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00003610 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00003611 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
3612 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00003613 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003614
3615 // See if we are doing a comparison between a constant and an instruction that
3616 // can be folded into the comparison.
3617 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chad Rosier131a42c2016-05-09 19:30:20 +00003618 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003619 // Since the RHS is a ConstantInt (CI), if the left hand side is an
3620 // instruction, see if that instruction also has constants so that the
3621 // instruction can be folded into the icmp
Chris Lattner2188e402010-01-04 07:37:31 +00003622 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3623 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
3624 return Res;
Chad Rosier131a42c2016-05-09 19:30:20 +00003625
3626 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3627 if (I.isEquality() && CI->isZero() &&
3628 match(Op0, m_UDiv(m_Value(A), m_Value(B)))) {
3629 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_EQ
3630 ? ICmpInst::ICMP_UGT
3631 : ICmpInst::ICMP_ULE;
3632 return new ICmpInst(Pred, B, A);
3633 }
Chris Lattner2188e402010-01-04 07:37:31 +00003634 }
3635
3636 // Handle icmp with constant (but not simple integer constant) RHS
3637 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3638 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3639 switch (LHSI->getOpcode()) {
3640 case Instruction::GetElementPtr:
3641 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3642 if (RHSC->isNullValue() &&
3643 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3644 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3645 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3646 break;
3647 case Instruction::PHI:
3648 // Only fold icmp into the PHI if the phi and icmp are in the same
3649 // block. If in the same block, we're encouraging jump threading. If
3650 // not, we are just pessimizing the code by making an i1 phi.
3651 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003652 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003653 return NV;
3654 break;
3655 case Instruction::Select: {
3656 // If either operand of the select is a constant, we can fold the
3657 // comparison into the select arms, which will cause one to be
3658 // constant folded and the select turned into a bitwise or.
Craig Topperf40110f2014-04-25 05:29:35 +00003659 Value *Op1 = nullptr, *Op2 = nullptr;
Hans Wennborg083ca9b2015-10-06 23:24:35 +00003660 ConstantInt *CI = nullptr;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003661 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003662 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003663 CI = dyn_cast<ConstantInt>(Op1);
3664 }
3665 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003666 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003667 CI = dyn_cast<ConstantInt>(Op2);
3668 }
Chris Lattner2188e402010-01-04 07:37:31 +00003669
3670 // We only want to perform this transformation if it will not lead to
3671 // additional code. This is true if either both sides of the select
3672 // fold to a constant (in which case the icmp is replaced with a select
3673 // which will usually simplify) or this is the only user of the
3674 // select (in which case we are trading a select+icmp for a simpler
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003675 // select+icmp) or all uses of the select can be replaced based on
3676 // dominance information ("Global cases").
3677 bool Transform = false;
3678 if (Op1 && Op2)
3679 Transform = true;
3680 else if (Op1 || Op2) {
3681 // Local case
3682 if (LHSI->hasOneUse())
3683 Transform = true;
3684 // Global cases
3685 else if (CI && !CI->isZero())
3686 // When Op1 is constant try replacing select with second operand.
3687 // Otherwise Op2 is constant and try replacing select with first
3688 // operand.
3689 Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
3690 Op1 ? 2 : 1);
3691 }
3692 if (Transform) {
Chris Lattner2188e402010-01-04 07:37:31 +00003693 if (!Op1)
3694 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3695 RHSC, I.getName());
3696 if (!Op2)
3697 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3698 RHSC, I.getName());
3699 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3700 }
3701 break;
3702 }
Chris Lattner2188e402010-01-04 07:37:31 +00003703 case Instruction::IntToPtr:
3704 // icmp pred inttoptr(X), null -> icmp pred X, 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003705 if (RHSC->isNullValue() &&
3706 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
Chris Lattner2188e402010-01-04 07:37:31 +00003707 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3708 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3709 break;
3710
3711 case Instruction::Load:
3712 // Try to optimize things like "A[i] > 4" to index computations.
3713 if (GetElementPtrInst *GEP =
3714 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3715 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3716 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3717 !cast<LoadInst>(LHSI)->isVolatile())
3718 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3719 return Res;
3720 }
3721 break;
3722 }
3723 }
3724
3725 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3726 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
3727 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
3728 return NI;
3729 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
3730 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
3731 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3732 return NI;
3733
Hans Wennborgf1f36512015-10-07 00:20:07 +00003734 // Try to optimize equality comparisons against alloca-based pointers.
3735 if (Op0->getType()->isPointerTy() && I.isEquality()) {
3736 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
3737 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
3738 if (Instruction *New = FoldAllocaCmp(I, Alloca, Op1))
3739 return New;
3740 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
3741 if (Instruction *New = FoldAllocaCmp(I, Alloca, Op0))
3742 return New;
3743 }
3744
Chris Lattner2188e402010-01-04 07:37:31 +00003745 // Test to see if the operands of the icmp are casted versions of other
3746 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3747 // now.
3748 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003749 if (Op0->getType()->isPointerTy() &&
3750 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003751 // We keep moving the cast from the left operand over to the right
3752 // operand, where it can often be eliminated completely.
3753 Op0 = CI->getOperand(0);
3754
3755 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3756 // so eliminate it as well.
3757 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3758 Op1 = CI2->getOperand(0);
3759
3760 // If Op1 is a constant, we can fold the cast into the constant.
3761 if (Op0->getType() != Op1->getType()) {
3762 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3763 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3764 } else {
3765 // Otherwise, cast the RHS right before the icmp
3766 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3767 }
3768 }
3769 return new ICmpInst(I.getPredicate(), Op0, Op1);
3770 }
3771 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003772
Chris Lattner2188e402010-01-04 07:37:31 +00003773 if (isa<CastInst>(Op0)) {
3774 // Handle the special case of: icmp (cast bool to X), <cst>
3775 // This comes up when you have code like
3776 // int X = A < B;
3777 // if (X) ...
3778 // For generality, we handle any zero-extension of any operand comparison
3779 // with a constant or another cast from the same type.
3780 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
3781 if (Instruction *R = visitICmpInstWithCastAndCast(I))
3782 return R;
3783 }
Chris Lattner2188e402010-01-04 07:37:31 +00003784
Duncan Sandse5220012011-02-17 07:46:37 +00003785 // Special logic for binary operators.
3786 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3787 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3788 if (BO0 || BO1) {
3789 CmpInst::Predicate Pred = I.getPredicate();
3790 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3791 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3792 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3793 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3794 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3795 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3796 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3797 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3798 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3799
3800 // Analyze the case when either Op0 or Op1 is an add instruction.
3801 // 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 +00003802 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +00003803 if (BO0 && BO0->getOpcode() == Instruction::Add) {
3804 A = BO0->getOperand(0);
3805 B = BO0->getOperand(1);
3806 }
3807 if (BO1 && BO1->getOpcode() == Instruction::Add) {
3808 C = BO1->getOperand(0);
3809 D = BO1->getOperand(1);
3810 }
Duncan Sandse5220012011-02-17 07:46:37 +00003811
David Majnemer549f4f22014-11-01 09:09:51 +00003812 // icmp (X+cst) < 0 --> X < -cst
3813 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
3814 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
3815 if (!RHSC->isMinValue(/*isSigned=*/true))
3816 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
3817
Duncan Sandse5220012011-02-17 07:46:37 +00003818 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3819 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3820 return new ICmpInst(Pred, A == Op1 ? B : A,
3821 Constant::getNullValue(Op1->getType()));
3822
3823 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3824 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3825 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3826 C == Op0 ? D : C);
3827
Duncan Sands84653b32011-02-18 16:25:37 +00003828 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003829 if (A && C && (A == C || A == D || B == C || B == D) &&
3830 NoOp0WrapProblem && NoOp1WrapProblem &&
3831 // Try not to increase register pressure.
3832 BO0->hasOneUse() && BO1->hasOneUse()) {
3833 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003834 Value *Y, *Z;
3835 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003836 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003837 Y = B;
3838 Z = D;
3839 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003840 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003841 Y = B;
3842 Z = C;
3843 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003844 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003845 Y = A;
3846 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003847 } else {
3848 assert(B == D);
3849 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003850 Y = A;
3851 Z = C;
3852 }
Duncan Sandse5220012011-02-17 07:46:37 +00003853 return new ICmpInst(Pred, Y, Z);
3854 }
3855
David Majnemerb81cd632013-04-11 20:05:46 +00003856 // icmp slt (X + -1), Y -> icmp sle X, Y
3857 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3858 match(B, m_AllOnes()))
3859 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3860
3861 // icmp sge (X + -1), Y -> icmp sgt X, Y
3862 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3863 match(B, m_AllOnes()))
3864 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3865
3866 // icmp sle (X + 1), Y -> icmp slt X, Y
3867 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3868 match(B, m_One()))
3869 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3870
3871 // icmp sgt (X + 1), Y -> icmp sge X, Y
3872 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3873 match(B, m_One()))
3874 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3875
Michael Liaoc65d3862015-10-19 22:08:14 +00003876 // icmp sgt X, (Y + -1) -> icmp sge X, Y
3877 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3878 match(D, m_AllOnes()))
3879 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3880
3881 // icmp sle X, (Y + -1) -> icmp slt X, Y
3882 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3883 match(D, m_AllOnes()))
3884 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3885
3886 // icmp sge X, (Y + 1) -> icmp sgt X, Y
3887 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE &&
3888 match(D, m_One()))
3889 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3890
3891 // icmp slt X, (Y + 1) -> icmp sle X, Y
3892 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT &&
3893 match(D, m_One()))
3894 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3895
David Majnemerb81cd632013-04-11 20:05:46 +00003896 // if C1 has greater magnitude than C2:
3897 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3898 // s.t. C3 = C1 - C2
3899 //
3900 // if C2 has greater magnitude than C1:
3901 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3902 // s.t. C3 = C2 - C1
3903 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3904 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3905 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3906 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3907 const APInt &AP1 = C1->getValue();
3908 const APInt &AP2 = C2->getValue();
3909 if (AP1.isNegative() == AP2.isNegative()) {
3910 APInt AP1Abs = C1->getValue().abs();
3911 APInt AP2Abs = C2->getValue().abs();
3912 if (AP1Abs.uge(AP2Abs)) {
3913 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
3914 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
3915 return new ICmpInst(Pred, NewAdd, C);
3916 } else {
3917 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
3918 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
3919 return new ICmpInst(Pred, A, NewAdd);
3920 }
3921 }
3922 }
3923
3924
Duncan Sandse5220012011-02-17 07:46:37 +00003925 // Analyze the case when either Op0 or Op1 is a sub instruction.
3926 // 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 +00003927 A = nullptr;
3928 B = nullptr;
3929 C = nullptr;
3930 D = nullptr;
3931 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
3932 A = BO0->getOperand(0);
3933 B = BO0->getOperand(1);
3934 }
3935 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3936 C = BO1->getOperand(0);
3937 D = BO1->getOperand(1);
3938 }
Duncan Sandse5220012011-02-17 07:46:37 +00003939
Duncan Sands84653b32011-02-18 16:25:37 +00003940 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3941 if (A == Op1 && NoOp0WrapProblem)
3942 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3943
3944 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
3945 if (C == Op0 && NoOp1WrapProblem)
3946 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3947
3948 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003949 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
3950 // Try not to increase register pressure.
3951 BO0->hasOneUse() && BO1->hasOneUse())
3952 return new ICmpInst(Pred, A, C);
3953
Duncan Sands84653b32011-02-18 16:25:37 +00003954 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
3955 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3956 // Try not to increase register pressure.
3957 BO0->hasOneUse() && BO1->hasOneUse())
3958 return new ICmpInst(Pred, D, B);
3959
David Majnemer186c9422014-05-15 00:02:20 +00003960 // icmp (0-X) < cst --> x > -cst
3961 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3962 Value *X;
3963 if (match(BO0, m_Neg(m_Value(X))))
3964 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
3965 if (!RHSC->isMinValue(/*isSigned=*/true))
3966 return new ICmpInst(I.getSwappedPredicate(), X,
3967 ConstantExpr::getNeg(RHSC));
3968 }
3969
Craig Topperf40110f2014-04-25 05:29:35 +00003970 BinaryOperator *SRem = nullptr;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003971 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00003972 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
3973 Op1 == BO0->getOperand(1))
3974 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003975 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00003976 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3977 Op0 == BO1->getOperand(1))
3978 SRem = BO1;
3979 if (SRem) {
3980 // We don't check hasOneUse to avoid increasing register pressure because
3981 // the value we use is the same value this instruction was already using.
3982 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
3983 default: break;
3984 case ICmpInst::ICMP_EQ:
Sanjay Patel4b198802016-02-01 22:23:39 +00003985 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003986 case ICmpInst::ICMP_NE:
Sanjay Patel4b198802016-02-01 22:23:39 +00003987 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003988 case ICmpInst::ICMP_SGT:
3989 case ICmpInst::ICMP_SGE:
3990 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
3991 Constant::getAllOnesValue(SRem->getType()));
3992 case ICmpInst::ICMP_SLT:
3993 case ICmpInst::ICMP_SLE:
3994 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
3995 Constant::getNullValue(SRem->getType()));
3996 }
3997 }
3998
Duncan Sandse5220012011-02-17 07:46:37 +00003999 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
4000 BO0->hasOneUse() && BO1->hasOneUse() &&
4001 BO0->getOperand(1) == BO1->getOperand(1)) {
4002 switch (BO0->getOpcode()) {
4003 default: break;
4004 case Instruction::Add:
4005 case Instruction::Sub:
4006 case Instruction::Xor:
4007 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
4008 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4009 BO1->getOperand(0));
4010 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
4011 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4012 if (CI->getValue().isSignBit()) {
4013 ICmpInst::Predicate Pred = I.isSigned()
4014 ? I.getUnsignedPredicate()
4015 : I.getSignedPredicate();
4016 return new ICmpInst(Pred, BO0->getOperand(0),
4017 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00004018 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004019
David Majnemerf8853ae2016-02-01 17:37:56 +00004020 if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00004021 ICmpInst::Predicate Pred = I.isSigned()
4022 ? I.getUnsignedPredicate()
4023 : I.getSignedPredicate();
4024 Pred = I.getSwappedPredicate(Pred);
4025 return new ICmpInst(Pred, BO0->getOperand(0),
4026 BO1->getOperand(0));
4027 }
Chris Lattner2188e402010-01-04 07:37:31 +00004028 }
Duncan Sandse5220012011-02-17 07:46:37 +00004029 break;
4030 case Instruction::Mul:
4031 if (!I.isEquality())
4032 break;
4033
4034 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4035 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
4036 // Mask = -1 >> count-trailing-zeros(Cst).
4037 if (!CI->isZero() && !CI->isOne()) {
4038 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004039 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00004040 APInt::getLowBitsSet(AP.getBitWidth(),
4041 AP.getBitWidth() -
4042 AP.countTrailingZeros()));
4043 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
4044 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
4045 return new ICmpInst(I.getPredicate(), And1, And2);
4046 }
4047 }
4048 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00004049 case Instruction::UDiv:
4050 case Instruction::LShr:
4051 if (I.isSigned())
4052 break;
4053 // fall-through
4054 case Instruction::SDiv:
4055 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00004056 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00004057 break;
4058 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4059 BO1->getOperand(0));
4060 case Instruction::Shl: {
4061 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
4062 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
4063 if (!NUW && !NSW)
4064 break;
4065 if (!NSW && I.isSigned())
4066 break;
4067 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4068 BO1->getOperand(0));
4069 }
Chris Lattner2188e402010-01-04 07:37:31 +00004070 }
4071 }
Sanjoy Dasc86c1622015-08-21 22:22:37 +00004072
4073 if (BO0) {
4074 // Transform A & (L - 1) `ult` L --> L != 0
4075 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
4076 auto BitwiseAnd =
4077 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
4078
4079 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
4080 auto *Zero = Constant::getNullValue(BO0->getType());
4081 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
4082 }
4083 }
Chris Lattner2188e402010-01-04 07:37:31 +00004084 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004085
Chris Lattner2188e402010-01-04 07:37:31 +00004086 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00004087 // Transform (A & ~B) == 0 --> (A & B) != 0
4088 // and (A & ~B) != 0 --> (A & B) == 0
4089 // if A is a power of 2.
4090 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00004091 match(Op1, m_Zero()) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004092 isKnownToBeAPowerOfTwo(A, DL, false, 0, AC, &I, DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00004093 return new ICmpInst(I.getInversePredicate(),
4094 Builder->CreateAnd(A, B),
4095 Op1);
4096
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004097 // ~x < ~y --> y < x
4098 // ~x < cst --> ~cst < x
4099 if (match(Op0, m_Not(m_Value(A)))) {
4100 if (match(Op1, m_Not(m_Value(B))))
4101 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00004102 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004103 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
4104 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00004105
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004106 Instruction *AddI = nullptr;
4107 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
4108 m_Instruction(AddI))) &&
4109 isa<IntegerType>(A->getType())) {
4110 Value *Result;
4111 Constant *Overflow;
4112 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
4113 Overflow)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004114 replaceInstUsesWith(*AddI, Result);
4115 return replaceInstUsesWith(I, Overflow);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004116 }
4117 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004118
4119 // (zext a) * (zext b) --> llvm.umul.with.overflow.
4120 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4121 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
4122 return R;
4123 }
4124 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4125 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
4126 return R;
4127 }
Chris Lattner2188e402010-01-04 07:37:31 +00004128 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004129
Chris Lattner2188e402010-01-04 07:37:31 +00004130 if (I.isEquality()) {
4131 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00004132
Chris Lattner2188e402010-01-04 07:37:31 +00004133 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4134 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4135 Value *OtherVal = A == Op1 ? B : A;
4136 return new ICmpInst(I.getPredicate(), OtherVal,
4137 Constant::getNullValue(A->getType()));
4138 }
4139
4140 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4141 // A^c1 == C^c2 --> A == C^(c1^c2)
4142 ConstantInt *C1, *C2;
4143 if (match(B, m_ConstantInt(C1)) &&
4144 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00004145 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004146 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00004147 return new ICmpInst(I.getPredicate(), A, Xor);
4148 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004149
Chris Lattner2188e402010-01-04 07:37:31 +00004150 // A^B == A^D -> B == D
4151 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4152 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4153 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4154 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4155 }
4156 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004157
Chris Lattner2188e402010-01-04 07:37:31 +00004158 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4159 (A == Op0 || B == Op0)) {
4160 // A == (A^B) -> B == 0
4161 Value *OtherVal = A == Op0 ? B : A;
4162 return new ICmpInst(I.getPredicate(), OtherVal,
4163 Constant::getNullValue(A->getType()));
4164 }
4165
Chris Lattner2188e402010-01-04 07:37:31 +00004166 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00004167 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00004168 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Craig Topperf40110f2014-04-25 05:29:35 +00004169 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004170
Chris Lattner2188e402010-01-04 07:37:31 +00004171 if (A == C) {
4172 X = B; Y = D; Z = A;
4173 } else if (A == D) {
4174 X = B; Y = C; Z = A;
4175 } else if (B == C) {
4176 X = A; Y = D; Z = B;
4177 } else if (B == D) {
4178 X = A; Y = C; Z = B;
4179 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004180
Chris Lattner2188e402010-01-04 07:37:31 +00004181 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004182 Op1 = Builder->CreateXor(X, Y);
4183 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00004184 I.setOperand(0, Op1);
4185 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4186 return &I;
4187 }
4188 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004189
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004190 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00004191 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004192 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00004193 if ((Op0->hasOneUse() &&
4194 match(Op0, m_ZExt(m_Value(A))) &&
4195 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
4196 (Op1->hasOneUse() &&
4197 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
4198 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004199 APInt Pow2 = Cst1->getValue() + 1;
4200 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
4201 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
4202 return new ICmpInst(I.getPredicate(), A,
4203 Builder->CreateTrunc(B, A->getType()));
4204 }
4205
Benjamin Kramer03f3e242013-11-16 16:00:48 +00004206 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
4207 // For lshr and ashr pairs.
4208 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4209 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
4210 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4211 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
4212 unsigned TypeBits = Cst1->getBitWidth();
4213 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4214 if (ShAmt < TypeBits && ShAmt != 0) {
4215 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
4216 ? ICmpInst::ICMP_UGE
4217 : ICmpInst::ICMP_ULT;
4218 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4219 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
4220 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
4221 }
4222 }
4223
Benjamin Kramer7fa8c432015-03-26 17:12:06 +00004224 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
4225 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
4226 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
4227 unsigned TypeBits = Cst1->getBitWidth();
4228 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4229 if (ShAmt < TypeBits && ShAmt != 0) {
4230 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4231 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
4232 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
4233 I.getName() + ".mask");
4234 return new ICmpInst(I.getPredicate(), And,
4235 Constant::getNullValue(Cst1->getType()));
4236 }
4237 }
4238
Chris Lattner1b06c712011-04-26 20:18:20 +00004239 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
4240 // "icmp (and X, mask), cst"
4241 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00004242 if (Op0->hasOneUse() &&
4243 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
4244 m_ConstantInt(ShAmt))))) &&
4245 match(Op1, m_ConstantInt(Cst1)) &&
4246 // Only do this when A has multiple uses. This is most important to do
4247 // when it exposes other optimizations.
4248 !A->hasOneUse()) {
4249 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004250
Chris Lattner1b06c712011-04-26 20:18:20 +00004251 if (ShAmt < ASize) {
4252 APInt MaskV =
4253 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
4254 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004255
Chris Lattner1b06c712011-04-26 20:18:20 +00004256 APInt CmpV = Cst1->getValue().zext(ASize);
4257 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004258
Chris Lattner1b06c712011-04-26 20:18:20 +00004259 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
4260 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
4261 }
4262 }
Chris Lattner2188e402010-01-04 07:37:31 +00004263 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004264
David Majnemerc1eca5a2014-11-06 23:23:30 +00004265 // The 'cmpxchg' instruction returns an aggregate containing the old value and
4266 // an i1 which indicates whether or not we successfully did the swap.
4267 //
4268 // Replace comparisons between the old value and the expected value with the
4269 // indicator that 'cmpxchg' returns.
4270 //
4271 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
4272 // spuriously fail. In those cases, the old value may equal the expected
4273 // value but it is possible for the swap to not occur.
4274 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4275 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4276 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4277 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4278 !ACXI->isWeak())
4279 return ExtractValueInst::Create(ACXI, 1);
4280
Chris Lattner2188e402010-01-04 07:37:31 +00004281 {
4282 Value *X; ConstantInt *Cst;
4283 // icmp X+Cst, X
4284 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00004285 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004286
4287 // icmp X, X+Cst
4288 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00004289 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004290 }
Craig Topperf40110f2014-04-25 05:29:35 +00004291 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004292}
4293
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004294/// Fold fcmp ([us]itofp x, cst) if possible.
Chris Lattner2188e402010-01-04 07:37:31 +00004295Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4296 Instruction *LHSI,
4297 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00004298 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004299 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004300
Chris Lattner2188e402010-01-04 07:37:31 +00004301 // Get the width of the mantissa. We don't want to hack on conversions that
4302 // might lose information from the integer, e.g. "i64 -> float"
4303 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00004304 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004305
Matt Arsenault55e73122015-01-06 15:50:59 +00004306 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4307
Chris Lattner2188e402010-01-04 07:37:31 +00004308 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004309
Matt Arsenault55e73122015-01-06 15:50:59 +00004310 if (I.isEquality()) {
4311 FCmpInst::Predicate P = I.getPredicate();
4312 bool IsExact = false;
4313 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
4314 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
4315
4316 // If the floating point constant isn't an integer value, we know if we will
4317 // ever compare equal / not equal to it.
4318 if (!IsExact) {
4319 // TODO: Can never be -0.0 and other non-representable values
4320 APFloat RHSRoundInt(RHS);
4321 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
4322 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
4323 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00004324 return replaceInstUsesWith(I, Builder->getFalse());
Matt Arsenault55e73122015-01-06 15:50:59 +00004325
4326 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
Sanjay Patel4b198802016-02-01 22:23:39 +00004327 return replaceInstUsesWith(I, Builder->getTrue());
Matt Arsenault55e73122015-01-06 15:50:59 +00004328 }
4329 }
4330
4331 // TODO: If the constant is exactly representable, is it always OK to do
4332 // equality compares as integer?
4333 }
4334
Arch D. Robison8ed08542015-09-15 17:51:59 +00004335 // Check to see that the input is converted from an integer type that is small
4336 // enough that preserves all bits. TODO: check here for "known" sign bits.
4337 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4338 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00004339
Arch D. Robison8ed08542015-09-15 17:51:59 +00004340 // Following test does NOT adjust InputSize downwards for signed inputs,
4341 // because the most negative value still requires all the mantissa bits
4342 // to distinguish it from one less than that value.
4343 if ((int)InputSize > MantissaWidth) {
4344 // Conversion would lose accuracy. Check if loss can impact comparison.
4345 int Exp = ilogb(RHS);
4346 if (Exp == APFloat::IEK_Inf) {
4347 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
4348 if (MaxExponent < (int)InputSize - !LHSUnsigned)
4349 // Conversion could create infinity.
4350 return nullptr;
4351 } else {
4352 // Note that if RHS is zero or NaN, then Exp is negative
4353 // and first condition is trivially false.
4354 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
4355 // Conversion could affect comparison.
4356 return nullptr;
4357 }
4358 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004359
Chris Lattner2188e402010-01-04 07:37:31 +00004360 // Otherwise, we can potentially simplify the comparison. We know that it
4361 // will always come through as an integer value and we know the constant is
4362 // not a NAN (it would have been previously simplified).
4363 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00004364
Chris Lattner2188e402010-01-04 07:37:31 +00004365 ICmpInst::Predicate Pred;
4366 switch (I.getPredicate()) {
4367 default: llvm_unreachable("Unexpected predicate!");
4368 case FCmpInst::FCMP_UEQ:
4369 case FCmpInst::FCMP_OEQ:
4370 Pred = ICmpInst::ICMP_EQ;
4371 break;
4372 case FCmpInst::FCMP_UGT:
4373 case FCmpInst::FCMP_OGT:
4374 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4375 break;
4376 case FCmpInst::FCMP_UGE:
4377 case FCmpInst::FCMP_OGE:
4378 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4379 break;
4380 case FCmpInst::FCMP_ULT:
4381 case FCmpInst::FCMP_OLT:
4382 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4383 break;
4384 case FCmpInst::FCMP_ULE:
4385 case FCmpInst::FCMP_OLE:
4386 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4387 break;
4388 case FCmpInst::FCMP_UNE:
4389 case FCmpInst::FCMP_ONE:
4390 Pred = ICmpInst::ICMP_NE;
4391 break;
4392 case FCmpInst::FCMP_ORD:
Sanjay Patel4b198802016-02-01 22:23:39 +00004393 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004394 case FCmpInst::FCMP_UNO:
Sanjay Patel4b198802016-02-01 22:23:39 +00004395 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004396 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004397
Chris Lattner2188e402010-01-04 07:37:31 +00004398 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004399
Chris Lattner2188e402010-01-04 07:37:31 +00004400 // See if the FP constant is too large for the integer. For example,
4401 // comparing an i8 to 300.0.
4402 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004403
Chris Lattner2188e402010-01-04 07:37:31 +00004404 if (!LHSUnsigned) {
4405 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4406 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004407 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004408 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4409 APFloat::rmNearestTiesToEven);
4410 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4411 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4412 Pred == ICmpInst::ICMP_SLE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004413 return replaceInstUsesWith(I, Builder->getTrue());
4414 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004415 }
4416 } else {
4417 // If the RHS value is > UnsignedMax, fold the comparison. This handles
4418 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004419 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004420 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4421 APFloat::rmNearestTiesToEven);
4422 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
4423 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
4424 Pred == ICmpInst::ICMP_ULE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004425 return replaceInstUsesWith(I, Builder->getTrue());
4426 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004427 }
4428 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004429
Chris Lattner2188e402010-01-04 07:37:31 +00004430 if (!LHSUnsigned) {
4431 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004432 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004433 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4434 APFloat::rmNearestTiesToEven);
4435 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4436 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4437 Pred == ICmpInst::ICMP_SGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004438 return replaceInstUsesWith(I, Builder->getTrue());
4439 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004440 }
Devang Patel698452b2012-02-13 23:05:18 +00004441 } else {
4442 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004443 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00004444 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
4445 APFloat::rmNearestTiesToEven);
4446 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
4447 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
4448 Pred == ICmpInst::ICMP_UGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004449 return replaceInstUsesWith(I, Builder->getTrue());
4450 return replaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00004451 }
Chris Lattner2188e402010-01-04 07:37:31 +00004452 }
4453
4454 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4455 // [0, UMAX], but it may still be fractional. See if it is fractional by
4456 // casting the FP value to the integer value and back, checking for equality.
4457 // Don't do this for zero, because -0.0 is not fractional.
4458 Constant *RHSInt = LHSUnsigned
4459 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4460 : ConstantExpr::getFPToSI(RHSC, IntTy);
4461 if (!RHS.isZero()) {
4462 bool Equal = LHSUnsigned
4463 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4464 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4465 if (!Equal) {
4466 // If we had a comparison against a fractional value, we have to adjust
4467 // the compare predicate and sometimes the value. RHSC is rounded towards
4468 // zero at this point.
4469 switch (Pred) {
4470 default: llvm_unreachable("Unexpected integer comparison!");
4471 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Sanjay Patel4b198802016-02-01 22:23:39 +00004472 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004473 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Sanjay Patel4b198802016-02-01 22:23:39 +00004474 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004475 case ICmpInst::ICMP_ULE:
4476 // (float)int <= 4.4 --> int <= 4
4477 // (float)int <= -4.4 --> false
4478 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004479 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004480 break;
4481 case ICmpInst::ICMP_SLE:
4482 // (float)int <= 4.4 --> int <= 4
4483 // (float)int <= -4.4 --> int < -4
4484 if (RHS.isNegative())
4485 Pred = ICmpInst::ICMP_SLT;
4486 break;
4487 case ICmpInst::ICMP_ULT:
4488 // (float)int < -4.4 --> false
4489 // (float)int < 4.4 --> int <= 4
4490 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004491 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004492 Pred = ICmpInst::ICMP_ULE;
4493 break;
4494 case ICmpInst::ICMP_SLT:
4495 // (float)int < -4.4 --> int < -4
4496 // (float)int < 4.4 --> int <= 4
4497 if (!RHS.isNegative())
4498 Pred = ICmpInst::ICMP_SLE;
4499 break;
4500 case ICmpInst::ICMP_UGT:
4501 // (float)int > 4.4 --> int > 4
4502 // (float)int > -4.4 --> true
4503 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004504 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004505 break;
4506 case ICmpInst::ICMP_SGT:
4507 // (float)int > 4.4 --> int > 4
4508 // (float)int > -4.4 --> int >= -4
4509 if (RHS.isNegative())
4510 Pred = ICmpInst::ICMP_SGE;
4511 break;
4512 case ICmpInst::ICMP_UGE:
4513 // (float)int >= -4.4 --> true
4514 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00004515 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004516 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004517 Pred = ICmpInst::ICMP_UGT;
4518 break;
4519 case ICmpInst::ICMP_SGE:
4520 // (float)int >= -4.4 --> int >= -4
4521 // (float)int >= 4.4 --> int > 4
4522 if (!RHS.isNegative())
4523 Pred = ICmpInst::ICMP_SGT;
4524 break;
4525 }
4526 }
4527 }
4528
4529 // Lower this FP comparison into an appropriate integer version of the
4530 // comparison.
4531 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4532}
4533
4534Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4535 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004536
Chris Lattner2188e402010-01-04 07:37:31 +00004537 /// Orders the operands of the compare so that they are listed from most
4538 /// complex to least complex. This puts constants before unary operators,
4539 /// before binary operators.
4540 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4541 I.swapOperands();
4542 Changed = true;
4543 }
4544
4545 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004546
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004547 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
4548 I.getFastMathFlags(), DL, TLI, DT, AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004549 return replaceInstUsesWith(I, V);
Chris Lattner2188e402010-01-04 07:37:31 +00004550
4551 // Simplify 'fcmp pred X, X'
4552 if (Op0 == Op1) {
4553 switch (I.getPredicate()) {
4554 default: llvm_unreachable("Unknown predicate!");
4555 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4556 case FCmpInst::FCMP_ULT: // True if unordered or less than
4557 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4558 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4559 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4560 I.setPredicate(FCmpInst::FCMP_UNO);
4561 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4562 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004563
Chris Lattner2188e402010-01-04 07:37:31 +00004564 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4565 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4566 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4567 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4568 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4569 I.setPredicate(FCmpInst::FCMP_ORD);
4570 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4571 return &I;
4572 }
4573 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004574
James Molloy2b21a7c2015-05-20 18:41:25 +00004575 // Test if the FCmpInst instruction is used exclusively by a select as
4576 // part of a minimum or maximum operation. If so, refrain from doing
4577 // any other folding. This helps out other analyses which understand
4578 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4579 // and CodeGen. And in this case, at least one of the comparison
4580 // operands has at least one user besides the compare (the select),
4581 // which would often largely negate the benefit of folding anyway.
4582 if (I.hasOneUse())
4583 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4584 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4585 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4586 return nullptr;
4587
Chris Lattner2188e402010-01-04 07:37:31 +00004588 // Handle fcmp with constant RHS
4589 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4590 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4591 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004592 case Instruction::FPExt: {
4593 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4594 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4595 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4596 if (!RHSF)
4597 break;
4598
4599 const fltSemantics *Sem;
4600 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004601 if (LHSExt->getSrcTy()->isHalfTy())
4602 Sem = &APFloat::IEEEhalf;
4603 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004604 Sem = &APFloat::IEEEsingle;
4605 else if (LHSExt->getSrcTy()->isDoubleTy())
4606 Sem = &APFloat::IEEEdouble;
4607 else if (LHSExt->getSrcTy()->isFP128Ty())
4608 Sem = &APFloat::IEEEquad;
4609 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
4610 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004611 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
4612 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004613 else
4614 break;
4615
4616 bool Lossy;
4617 APFloat F = RHSF->getValueAPF();
4618 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4619
Jim Grosbach24ff8342011-09-30 18:45:50 +00004620 // Avoid lossy conversions and denormals. Zero is a special case
4621 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004622 APFloat Fabs = F;
4623 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004624 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004625 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4626 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004627
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004628 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4629 ConstantFP::get(RHSC->getContext(), F));
4630 break;
4631 }
Chris Lattner2188e402010-01-04 07:37:31 +00004632 case Instruction::PHI:
4633 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4634 // block. If in the same block, we're encouraging jump threading. If
4635 // not, we are just pessimizing the code by making an i1 phi.
4636 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004637 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004638 return NV;
4639 break;
4640 case Instruction::SIToFP:
4641 case Instruction::UIToFP:
4642 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
4643 return NV;
4644 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004645 case Instruction::FSub: {
4646 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4647 Value *Op;
4648 if (match(LHSI, m_FNeg(m_Value(Op))))
4649 return new FCmpInst(I.getSwappedPredicate(), Op,
4650 ConstantExpr::getFNeg(RHSC));
4651 break;
4652 }
Dan Gohman94732022010-02-24 06:46:09 +00004653 case Instruction::Load:
4654 if (GetElementPtrInst *GEP =
4655 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4656 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4657 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4658 !cast<LoadInst>(LHSI)->isVolatile())
4659 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
4660 return Res;
4661 }
4662 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004663 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004664 if (!RHSC->isNullValue())
4665 break;
4666
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004667 CallInst *CI = cast<CallInst>(LHSI);
David Majnemerb4b27232016-04-19 19:10:21 +00004668 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer2e02ba72016-04-15 17:21:03 +00004669 if (IID != Intrinsic::fabs)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004670 break;
4671
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004672 // Various optimization for fabs compared with zero.
David Majnemer2e02ba72016-04-15 17:21:03 +00004673 switch (I.getPredicate()) {
4674 default:
4675 break;
4676 // fabs(x) < 0 --> false
4677 case FCmpInst::FCMP_OLT:
4678 llvm_unreachable("handled by SimplifyFCmpInst");
4679 // fabs(x) > 0 --> x != 0
4680 case FCmpInst::FCMP_OGT:
4681 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
4682 // fabs(x) <= 0 --> x == 0
4683 case FCmpInst::FCMP_OLE:
4684 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
4685 // fabs(x) >= 0 --> !isnan(x)
4686 case FCmpInst::FCMP_OGE:
4687 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
4688 // fabs(x) == 0 --> x == 0
4689 // fabs(x) != 0 --> x != 0
4690 case FCmpInst::FCMP_OEQ:
4691 case FCmpInst::FCMP_UEQ:
4692 case FCmpInst::FCMP_ONE:
4693 case FCmpInst::FCMP_UNE:
4694 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004695 }
4696 }
Chris Lattner2188e402010-01-04 07:37:31 +00004697 }
Chris Lattner2188e402010-01-04 07:37:31 +00004698 }
4699
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004700 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004701 Value *X, *Y;
4702 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004703 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004704
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004705 // fcmp (fpext x), (fpext y) -> fcmp x, y
4706 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4707 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4708 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4709 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4710 RHSExt->getOperand(0));
4711
Craig Topperf40110f2014-04-25 05:29:35 +00004712 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004713}