blob: b3727e4bbe5e0e0bf672cb2e24ebb1730dcf0672 [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
Sanjay Patel6a333c32016-06-06 16:56:57 +00002462 // The re-extended constant changed, partly changed (in the case of a vector),
2463 // or could not be determined to be equal (in the case of a constant
2464 // expression), so the constant cannot be represented in the shorter type.
2465 // Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002466 // All the cases that fold to true or false will have already been handled
2467 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00002468
Sanjay Patel6a333c32016-06-06 16:56:57 +00002469 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
Craig Topperf40110f2014-04-25 05:29:35 +00002470 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002471
2472 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
2473 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002474
2475 // We're performing an unsigned comp with a sign extended value.
2476 // This is true if the input is >= 0. [aka >s -1]
2477 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002478 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00002479
2480 // Finally, return the value computed.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002481 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
2482 return replaceInstUsesWith(ICmp, Result);
Chris Lattner2188e402010-01-04 07:37:31 +00002483
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002484 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00002485 return BinaryOperator::CreateNot(Result);
2486}
2487
Sanjay Patel5f0217f2016-06-05 16:46:18 +00002488/// The caller has matched a pattern of the form:
Chris Lattneree61c1d2010-12-19 17:52:50 +00002489/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00002490/// If this is of the form:
2491/// sum = a + b
2492/// if (sum+128 >u 255)
2493/// Then replace it with llvm.sadd.with.overflow.i8.
2494///
Chris Lattneree61c1d2010-12-19 17:52:50 +00002495static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2496 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00002497 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00002498 // The transformation we're trying to do here is to transform this into an
2499 // llvm.sadd.with.overflow. To do this, we have to replace the original add
2500 // with a narrower add, and discard the add-with-constant that is part of the
2501 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00002502
Chris Lattnerf29562d2010-12-19 17:59:02 +00002503 // In order to eliminate the add-with-constant, the compare can be its only
2504 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00002505 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00002506 if (!AddWithCst->hasOneUse()) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002507
Chris Lattnerc56c8452010-12-19 18:22:06 +00002508 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
Craig Topperf40110f2014-04-25 05:29:35 +00002509 if (!CI2->getValue().isPowerOf2()) return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002510 unsigned NewWidth = CI2->getValue().countTrailingZeros();
Craig Topperf40110f2014-04-25 05:29:35 +00002511 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002512
Chris Lattnerc56c8452010-12-19 18:22:06 +00002513 // The width of the new add formed is 1 more than the bias.
2514 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002515
Chris Lattnerc56c8452010-12-19 18:22:06 +00002516 // Check to see that CI1 is an all-ones value with NewWidth bits.
2517 if (CI1->getBitWidth() == NewWidth ||
2518 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
Craig Topperf40110f2014-04-25 05:29:35 +00002519 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002520
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002521 // This is only really a signed overflow check if the inputs have been
2522 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2523 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2524 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
Hal Finkel60db0582014-09-07 18:57:58 +00002525 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2526 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
Craig Topperf40110f2014-04-25 05:29:35 +00002527 return nullptr;
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002528
Jim Grosbach129c52a2011-09-30 18:09:53 +00002529 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00002530 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2531 // and truncates that discard the high bits of the add. Verify that this is
2532 // the case.
2533 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00002534 for (User *U : OrigAdd->users()) {
2535 if (U == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002536
Chris Lattnerc56c8452010-12-19 18:22:06 +00002537 // Only accept truncates for now. We would really like a nice recursive
2538 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2539 // chain to see which bits of a value are actually demanded. If the
2540 // original add had another add which was then immediately truncated, we
2541 // could still do the transformation.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002542 TruncInst *TI = dyn_cast<TruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00002543 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2544 return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002545 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002546
Chris Lattneree61c1d2010-12-19 17:52:50 +00002547 // If the pattern matches, truncate the inputs to the narrower type and
2548 // use the sadd_with_overflow intrinsic to efficiently compute both the
2549 // result and the overflow bit.
Jay Foadb804a2b2011-07-12 14:06:48 +00002550 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002551 Value *F = Intrinsic::getDeclaration(I.getModule(),
2552 Intrinsic::sadd_with_overflow, NewType);
Chris Lattner79874562010-12-19 18:35:09 +00002553
Chris Lattnerce2995a2010-12-19 18:38:44 +00002554 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002555
Chris Lattner79874562010-12-19 18:35:09 +00002556 // Put the new code above the original add, in case there are any uses of the
2557 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002558 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002559
Chris Lattner79874562010-12-19 18:35:09 +00002560 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2561 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
David Blaikieff6409d2015-05-18 22:13:54 +00002562 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
Chris Lattner79874562010-12-19 18:35:09 +00002563 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2564 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002565
Chris Lattneree61c1d2010-12-19 17:52:50 +00002566 // The inner add was the result of the narrow add, zero extended to the
2567 // wider type. Replace it with the result computed by the intrinsic.
Sanjay Patel4b198802016-02-01 22:23:39 +00002568 IC.replaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002569
Chris Lattner79874562010-12-19 18:35:09 +00002570 // The original icmp gets replaced with the overflow value.
2571 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00002572}
Chris Lattner2188e402010-01-04 07:37:31 +00002573
Sanjoy Dasb0984472015-04-08 04:27:22 +00002574bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
2575 Value *RHS, Instruction &OrigI,
2576 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00002577 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
2578 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002579
2580 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
2581 Result = OpResult;
2582 Overflow = OverflowVal;
2583 if (ReuseName)
2584 Result->takeName(&OrigI);
2585 return true;
2586 };
2587
Sanjoy Das6f5dca72015-08-28 19:09:31 +00002588 // If the overflow check was an add followed by a compare, the insertion point
2589 // may be pointing to the compare. We want to insert the new instructions
2590 // before the add in case there are uses of the add between the add and the
2591 // compare.
2592 Builder->SetInsertPoint(&OrigI);
2593
Sanjoy Dasb0984472015-04-08 04:27:22 +00002594 switch (OCF) {
2595 case OCF_INVALID:
2596 llvm_unreachable("bad overflow check kind!");
2597
2598 case OCF_UNSIGNED_ADD: {
2599 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
2600 if (OR == OverflowResult::NeverOverflows)
2601 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
2602 true);
2603
2604 if (OR == OverflowResult::AlwaysOverflows)
2605 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
2606 }
2607 // FALL THROUGH uadd into sadd
2608 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002609 // X + 0 -> {X, false}
2610 if (match(RHS, m_Zero()))
2611 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002612
2613 // We can strength reduce this signed add into a regular add if we can prove
2614 // that it will never overflow.
2615 if (OCF == OCF_SIGNED_ADD)
2616 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
2617 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
2618 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00002619 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002620 }
2621
2622 case OCF_UNSIGNED_SUB:
2623 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002624 // X - 0 -> {X, false}
2625 if (match(RHS, m_Zero()))
2626 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002627
2628 if (OCF == OCF_SIGNED_SUB) {
2629 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
2630 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
2631 true);
2632 } else {
2633 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
2634 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
2635 true);
2636 }
2637 break;
2638 }
2639
2640 case OCF_UNSIGNED_MUL: {
2641 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
2642 if (OR == OverflowResult::NeverOverflows)
2643 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
2644 true);
2645 if (OR == OverflowResult::AlwaysOverflows)
2646 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
2647 } // FALL THROUGH
2648 case OCF_SIGNED_MUL:
2649 // X * undef -> undef
2650 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00002651 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002652
David Majnemer27e89ba2015-05-21 23:04:21 +00002653 // X * 0 -> {0, false}
2654 if (match(RHS, m_Zero()))
2655 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002656
David Majnemer27e89ba2015-05-21 23:04:21 +00002657 // X * 1 -> {X, false}
2658 if (match(RHS, m_One()))
2659 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002660
2661 if (OCF == OCF_SIGNED_MUL)
2662 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
2663 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
2664 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00002665 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002666 }
2667
2668 return false;
2669}
2670
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002671/// \brief Recognize and process idiom involving test for multiplication
2672/// overflow.
2673///
2674/// The caller has matched a pattern of the form:
2675/// I = cmp u (mul(zext A, zext B), V
2676/// The function checks if this is a test for overflow and if so replaces
2677/// multiplication with call to 'mul.with.overflow' intrinsic.
2678///
2679/// \param I Compare instruction.
2680/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2681/// the compare instruction. Must be of integer type.
2682/// \param OtherVal The other argument of compare instruction.
2683/// \returns Instruction which must replace the compare instruction, NULL if no
2684/// replacement required.
2685static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2686 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00002687 // Don't bother doing this transformation for pointers, don't do it for
2688 // vectors.
2689 if (!isa<IntegerType>(MulVal->getType()))
2690 return nullptr;
2691
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002692 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2693 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00002694 auto *MulInstr = dyn_cast<Instruction>(MulVal);
2695 if (!MulInstr)
2696 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002697 assert(MulInstr->getOpcode() == Instruction::Mul);
2698
David Majnemer634ca232014-11-01 23:46:05 +00002699 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
2700 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002701 assert(LHS->getOpcode() == Instruction::ZExt);
2702 assert(RHS->getOpcode() == Instruction::ZExt);
2703 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2704
2705 // Calculate type and width of the result produced by mul.with.overflow.
2706 Type *TyA = A->getType(), *TyB = B->getType();
2707 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2708 WidthB = TyB->getPrimitiveSizeInBits();
2709 unsigned MulWidth;
2710 Type *MulType;
2711 if (WidthB > WidthA) {
2712 MulWidth = WidthB;
2713 MulType = TyB;
2714 } else {
2715 MulWidth = WidthA;
2716 MulType = TyA;
2717 }
2718
2719 // In order to replace the original mul with a narrower mul.with.overflow,
2720 // all uses must ignore upper bits of the product. The number of used low
2721 // bits must be not greater than the width of mul.with.overflow.
2722 if (MulVal->hasNUsesOrMore(2))
2723 for (User *U : MulVal->users()) {
2724 if (U == &I)
2725 continue;
2726 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2727 // Check if truncation ignores bits above MulWidth.
2728 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2729 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002730 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002731 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2732 // Check if AND ignores bits above MulWidth.
2733 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00002734 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002735 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2736 const APInt &CVal = CI->getValue();
2737 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002738 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002739 }
2740 } else {
2741 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00002742 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002743 }
2744 }
2745
2746 // Recognize patterns
2747 switch (I.getPredicate()) {
2748 case ICmpInst::ICMP_EQ:
2749 case ICmpInst::ICMP_NE:
2750 // Recognize pattern:
2751 // mulval = mul(zext A, zext B)
2752 // cmp eq/neq mulval, zext trunc mulval
2753 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2754 if (Zext->hasOneUse()) {
2755 Value *ZextArg = Zext->getOperand(0);
2756 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2757 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2758 break; //Recognized
2759 }
2760
2761 // Recognize pattern:
2762 // mulval = mul(zext A, zext B)
2763 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2764 ConstantInt *CI;
2765 Value *ValToMask;
2766 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2767 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00002768 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002769 const APInt &CVal = CI->getValue() + 1;
2770 if (CVal.isPowerOf2()) {
2771 unsigned MaskWidth = CVal.logBase2();
2772 if (MaskWidth == MulWidth)
2773 break; // Recognized
2774 }
2775 }
Craig Topperf40110f2014-04-25 05:29:35 +00002776 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002777
2778 case ICmpInst::ICMP_UGT:
2779 // Recognize pattern:
2780 // mulval = mul(zext A, zext B)
2781 // cmp ugt mulval, max
2782 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2783 APInt MaxVal = APInt::getMaxValue(MulWidth);
2784 MaxVal = MaxVal.zext(CI->getBitWidth());
2785 if (MaxVal.eq(CI->getValue()))
2786 break; // Recognized
2787 }
Craig Topperf40110f2014-04-25 05:29:35 +00002788 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002789
2790 case ICmpInst::ICMP_UGE:
2791 // Recognize pattern:
2792 // mulval = mul(zext A, zext B)
2793 // cmp uge mulval, max+1
2794 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2795 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2796 if (MaxVal.eq(CI->getValue()))
2797 break; // Recognized
2798 }
Craig Topperf40110f2014-04-25 05:29:35 +00002799 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002800
2801 case ICmpInst::ICMP_ULE:
2802 // Recognize pattern:
2803 // mulval = mul(zext A, zext B)
2804 // cmp ule mulval, max
2805 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2806 APInt MaxVal = APInt::getMaxValue(MulWidth);
2807 MaxVal = MaxVal.zext(CI->getBitWidth());
2808 if (MaxVal.eq(CI->getValue()))
2809 break; // Recognized
2810 }
Craig Topperf40110f2014-04-25 05:29:35 +00002811 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002812
2813 case ICmpInst::ICMP_ULT:
2814 // Recognize pattern:
2815 // mulval = mul(zext A, zext B)
2816 // cmp ule mulval, max + 1
2817 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002818 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002819 if (MaxVal.eq(CI->getValue()))
2820 break; // Recognized
2821 }
Craig Topperf40110f2014-04-25 05:29:35 +00002822 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002823
2824 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002825 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002826 }
2827
2828 InstCombiner::BuilderTy *Builder = IC.Builder;
2829 Builder->SetInsertPoint(MulInstr);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002830
2831 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2832 Value *MulA = A, *MulB = B;
2833 if (WidthA < MulWidth)
2834 MulA = Builder->CreateZExt(A, MulType);
2835 if (WidthB < MulWidth)
2836 MulB = Builder->CreateZExt(B, MulType);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002837 Value *F = Intrinsic::getDeclaration(I.getModule(),
2838 Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00002839 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002840 IC.Worklist.Add(MulInstr);
2841
2842 // If there are uses of mul result other than the comparison, we know that
2843 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002844 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002845 if (MulVal->hasNUsesOrMore(2)) {
2846 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2847 for (User *U : MulVal->users()) {
2848 if (U == &I || U == OtherVal)
2849 continue;
2850 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2851 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
Sanjay Patel4b198802016-02-01 22:23:39 +00002852 IC.replaceInstUsesWith(*TI, Mul);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002853 else
2854 TI->setOperand(0, Mul);
2855 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2856 assert(BO->getOpcode() == Instruction::And);
2857 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2858 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2859 APInt ShortMask = CI->getValue().trunc(MulWidth);
2860 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2861 Instruction *Zext =
2862 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2863 IC.Worklist.Add(Zext);
Sanjay Patel4b198802016-02-01 22:23:39 +00002864 IC.replaceInstUsesWith(*BO, Zext);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002865 } else {
2866 llvm_unreachable("Unexpected Binary operation");
2867 }
2868 IC.Worklist.Add(cast<Instruction>(U));
2869 }
2870 }
2871 if (isa<Instruction>(OtherVal))
2872 IC.Worklist.Add(cast<Instruction>(OtherVal));
2873
2874 // The original icmp gets replaced with the overflow value, maybe inverted
2875 // depending on predicate.
2876 bool Inverse = false;
2877 switch (I.getPredicate()) {
2878 case ICmpInst::ICMP_NE:
2879 break;
2880 case ICmpInst::ICMP_EQ:
2881 Inverse = true;
2882 break;
2883 case ICmpInst::ICMP_UGT:
2884 case ICmpInst::ICMP_UGE:
2885 if (I.getOperand(0) == MulVal)
2886 break;
2887 Inverse = true;
2888 break;
2889 case ICmpInst::ICMP_ULT:
2890 case ICmpInst::ICMP_ULE:
2891 if (I.getOperand(1) == MulVal)
2892 break;
2893 Inverse = true;
2894 break;
2895 default:
2896 llvm_unreachable("Unexpected predicate");
2897 }
2898 if (Inverse) {
2899 Value *Res = Builder->CreateExtractValue(Call, 1);
2900 return BinaryOperator::CreateNot(Res);
2901 }
2902
2903 return ExtractValueInst::Create(Call, 1);
2904}
2905
Sanjay Patel5f0217f2016-06-05 16:46:18 +00002906/// When performing a comparison against a constant, it is possible that not all
2907/// the bits in the LHS are demanded. This helper method computes the mask that
2908/// IS demanded.
Owen Andersond490c2d2011-01-11 00:36:45 +00002909static APInt DemandedBitsLHSMask(ICmpInst &I,
2910 unsigned BitWidth, bool isSignCheck) {
2911 if (isSignCheck)
2912 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002913
Owen Andersond490c2d2011-01-11 00:36:45 +00002914 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2915 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00002916 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002917
Owen Andersond490c2d2011-01-11 00:36:45 +00002918 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002919 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00002920 // correspond to the trailing ones of the comparand. The value of these
2921 // bits doesn't impact the outcome of the comparison, because any value
2922 // greater than the RHS must differ in a bit higher than these due to carry.
2923 case ICmpInst::ICMP_UGT: {
2924 unsigned trailingOnes = RHS.countTrailingOnes();
2925 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2926 return ~lowBitsSet;
2927 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002928
Owen Andersond490c2d2011-01-11 00:36:45 +00002929 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2930 // Any value less than the RHS must differ in a higher bit because of carries.
2931 case ICmpInst::ICMP_ULT: {
2932 unsigned trailingZeros = RHS.countTrailingZeros();
2933 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2934 return ~lowBitsSet;
2935 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002936
Owen Andersond490c2d2011-01-11 00:36:45 +00002937 default:
2938 return APInt::getAllOnesValue(BitWidth);
2939 }
Owen Andersond490c2d2011-01-11 00:36:45 +00002940}
Chris Lattner2188e402010-01-04 07:37:31 +00002941
Quentin Colombet5ab55552013-09-09 20:56:48 +00002942/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2943/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00002944/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00002945/// as subtract operands and their positions in those instructions.
2946/// The rational is that several architectures use the same instruction for
2947/// both subtract and cmp, thus it is better if the order of those operands
2948/// match.
2949/// \return true if Op0 and Op1 should be swapped.
2950static bool swapMayExposeCSEOpportunities(const Value * Op0,
2951 const Value * Op1) {
2952 // Filter out pointer value as those cannot appears directly in subtract.
2953 // FIXME: we may want to go through inttoptrs or bitcasts.
2954 if (Op0->getType()->isPointerTy())
2955 return false;
2956 // Count every uses of both Op0 and Op1 in a subtract.
2957 // Each time Op0 is the first operand, count -1: swapping is bad, the
2958 // subtract has already the same layout as the compare.
2959 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00002960 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002961 // At the end, if the benefit is greater than 0, Op0 should come second to
2962 // expose more CSE opportunities.
2963 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002964 for (const User *U : Op0->users()) {
2965 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002966 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2967 continue;
2968 // If Op0 is the first argument, this is not beneficial to swap the
2969 // arguments.
2970 int LocalSwapBenefits = -1;
2971 unsigned Op1Idx = 1;
2972 if (BinOp->getOperand(Op1Idx) == Op0) {
2973 Op1Idx = 0;
2974 LocalSwapBenefits = 1;
2975 }
2976 if (BinOp->getOperand(Op1Idx) != Op1)
2977 continue;
2978 GlobalSwapBenefits += LocalSwapBenefits;
2979 }
2980 return GlobalSwapBenefits > 0;
2981}
2982
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00002983/// \brief Check that one use is in the same block as the definition and all
2984/// other uses are in blocks dominated by a given block
2985///
2986/// \param DI Definition
2987/// \param UI Use
2988/// \param DB Block that must dominate all uses of \p DI outside
2989/// the parent block
2990/// \return true when \p UI is the only use of \p DI in the parent block
2991/// and all other uses of \p DI are in blocks dominated by \p DB.
2992///
2993bool InstCombiner::dominatesAllUses(const Instruction *DI,
2994 const Instruction *UI,
2995 const BasicBlock *DB) const {
2996 assert(DI && UI && "Instruction not defined\n");
2997 // ignore incomplete definitions
2998 if (!DI->getParent())
2999 return false;
3000 // DI and UI must be in the same block
3001 if (DI->getParent() != UI->getParent())
3002 return false;
3003 // Protect from self-referencing blocks
3004 if (DI->getParent() == DB)
3005 return false;
3006 // DominatorTree available?
3007 if (!DT)
3008 return false;
3009 for (const User *U : DI->users()) {
3010 auto *Usr = cast<Instruction>(U);
3011 if (Usr != UI && !DT->dominates(DB, Usr->getParent()))
3012 return false;
3013 }
3014 return true;
3015}
3016
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003017/// Return true when the instruction sequence within a block is select-cmp-br.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003018static bool isChainSelectCmpBranch(const SelectInst *SI) {
3019 const BasicBlock *BB = SI->getParent();
3020 if (!BB)
3021 return false;
3022 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
3023 if (!BI || BI->getNumSuccessors() != 2)
3024 return false;
3025 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
3026 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
3027 return false;
3028 return true;
3029}
3030
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003031/// \brief True when a select result is replaced by one of its operands
3032/// in select-icmp sequence. This will eventually result in the elimination
3033/// of the select.
3034///
3035/// \param SI Select instruction
3036/// \param Icmp Compare instruction
3037/// \param SIOpd Operand that replaces the select
3038///
3039/// Notes:
3040/// - The replacement is global and requires dominator information
3041/// - The caller is responsible for the actual replacement
3042///
3043/// Example:
3044///
3045/// entry:
3046/// %4 = select i1 %3, %C* %0, %C* null
3047/// %5 = icmp eq %C* %4, null
3048/// br i1 %5, label %9, label %7
3049/// ...
3050/// ; <label>:7 ; preds = %entry
3051/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
3052/// ...
3053///
3054/// can be transformed to
3055///
3056/// %5 = icmp eq %C* %0, null
3057/// %6 = select i1 %3, i1 %5, i1 true
3058/// br i1 %6, label %9, label %7
3059/// ...
3060/// ; <label>:7 ; preds = %entry
3061/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
3062///
3063/// Similar when the first operand of the select is a constant or/and
3064/// the compare is for not equal rather than equal.
3065///
3066/// NOTE: The function is only called when the select and compare constants
3067/// are equal, the optimization can work only for EQ predicates. This is not a
3068/// major restriction since a NE compare should be 'normalized' to an equal
3069/// compare, which usually happens in the combiner and test case
3070/// select-cmp-br.ll
3071/// checks for it.
3072bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
3073 const ICmpInst *Icmp,
3074 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00003075 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003076 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
3077 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
3078 // The check for the unique predecessor is not the best that can be
3079 // done. But it protects efficiently against cases like when SI's
3080 // home block has two successors, Succ and Succ1, and Succ1 predecessor
3081 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
3082 // replaced can be reached on either path. So the uniqueness check
3083 // guarantees that the path all uses of SI (outside SI's parent) are on
3084 // is disjoint from all other paths out of SI. But that information
3085 // is more expensive to compute, and the trade-off here is in favor
3086 // of compile-time.
3087 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
3088 NumSel++;
3089 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
3090 return true;
3091 }
3092 }
3093 return false;
3094}
3095
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003096/// If we have an icmp le or icmp ge instruction with a constant operand, turn
3097/// it into the appropriate icmp lt or icmp gt instruction. This transform
3098/// allows them to be folded in visitICmpInst.
Sanjay Patele9b2c322016-05-17 00:57:57 +00003099static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
3100 ICmpInst::Predicate Pred = I.getPredicate();
3101 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE &&
3102 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE)
3103 return nullptr;
3104
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003105 Value *Op0 = I.getOperand(0);
3106 Value *Op1 = I.getOperand(1);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003107 auto *Op1C = dyn_cast<Constant>(Op1);
3108 if (!Op1C)
3109 return nullptr;
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003110
Sanjay Patele9b2c322016-05-17 00:57:57 +00003111 // Check if the constant operand can be safely incremented/decremented without
3112 // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled
3113 // the edge cases for us, so we just assert on them. For vectors, we must
3114 // handle the edge cases.
3115 Type *Op1Type = Op1->getType();
3116 bool IsSigned = I.isSigned();
3117 bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE);
Sanjay Patel18254932016-05-17 01:12:31 +00003118 auto *CI = dyn_cast<ConstantInt>(Op1C);
3119 if (CI) {
Sanjay Patele9b2c322016-05-17 00:57:57 +00003120 // A <= MAX -> TRUE ; A >= MIN -> TRUE
3121 assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned));
3122 } else if (Op1Type->isVectorTy()) {
Sanjay Patelb79ab272016-05-13 15:10:46 +00003123 // TODO? If the edge cases for vectors were guaranteed to be handled as they
Sanjay Patele9b2c322016-05-17 00:57:57 +00003124 // are for scalar, we could remove the min/max checks. However, to do that,
3125 // we would have to use insertelement/shufflevector to replace edge values.
3126 unsigned NumElts = Op1Type->getVectorNumElements();
3127 for (unsigned i = 0; i != NumElts; ++i) {
3128 Constant *Elt = Op1C->getAggregateElement(i);
Benjamin Kramerca9a0fe2016-05-17 12:08:55 +00003129 if (!Elt)
3130 return nullptr;
3131
Sanjay Patele9b2c322016-05-17 00:57:57 +00003132 if (isa<UndefValue>(Elt))
3133 continue;
3134 // Bail out if we can't determine if this constant is min/max or if we
3135 // know that this constant is min/max.
3136 auto *CI = dyn_cast<ConstantInt>(Elt);
3137 if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned)))
3138 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003139 }
Sanjay Patele9b2c322016-05-17 00:57:57 +00003140 } else {
3141 // ConstantExpr?
3142 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003143 }
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003144
Sanjay Patele9b2c322016-05-17 00:57:57 +00003145 // Increment or decrement the constant and set the new comparison predicate:
3146 // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT
Sanjay Patel22b01fe2016-05-17 20:20:40 +00003147 Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003148 CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT;
3149 NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred;
3150 return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne));
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003151}
3152
Chris Lattner2188e402010-01-04 07:37:31 +00003153Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
3154 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00003155 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003156 unsigned Op0Cplxity = getComplexity(Op0);
3157 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003158
Chris Lattner2188e402010-01-04 07:37:31 +00003159 /// Orders the operands of the compare so that they are listed from most
3160 /// complex to least complex. This puts constants before unary operators,
3161 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003162 if (Op0Cplxity < Op1Cplxity ||
Sanjay Patel4c204232016-06-04 20:39:22 +00003163 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003164 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00003165 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003166 Changed = true;
3167 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003168
Jingyue Wu5e34ce32015-06-25 20:14:47 +00003169 if (Value *V =
3170 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00003171 return replaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003172
Pete Cooperbc5c5242011-12-01 03:58:40 +00003173 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00003174 // ie, abs(val) != 0 -> val != 0
Sanjay Patel4c204232016-06-04 20:39:22 +00003175 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003176 Value *Cond, *SelectTrue, *SelectFalse;
3177 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00003178 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003179 if (Value *V = dyn_castNegVal(SelectTrue)) {
3180 if (V == SelectFalse)
3181 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
3182 }
3183 else if (Value *V = dyn_castNegVal(SelectFalse)) {
3184 if (V == SelectTrue)
3185 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00003186 }
3187 }
3188 }
3189
Chris Lattner229907c2011-07-18 04:54:35 +00003190 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00003191
3192 // icmp's with boolean values can always be turned into bitwise operations
Sanjay Patela6fbc822016-06-05 17:49:45 +00003193 if (Ty->getScalarType()->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00003194 switch (I.getPredicate()) {
3195 default: llvm_unreachable("Invalid icmp instruction!");
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003196 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
3197 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003198 return BinaryOperator::CreateNot(Xor);
3199 }
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003200 case ICmpInst::ICMP_NE: // icmp ne i1 A, B -> A^B
Chris Lattner2188e402010-01-04 07:37:31 +00003201 return BinaryOperator::CreateXor(Op0, Op1);
3202
3203 case ICmpInst::ICMP_UGT:
3204 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
3205 // FALL THROUGH
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003206 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
3207 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003208 return BinaryOperator::CreateAnd(Not, Op1);
3209 }
3210 case ICmpInst::ICMP_SGT:
3211 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
3212 // FALL THROUGH
3213 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003214 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003215 return BinaryOperator::CreateAnd(Not, Op0);
3216 }
3217 case ICmpInst::ICMP_UGE:
3218 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
3219 // FALL THROUGH
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003220 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
3221 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003222 return BinaryOperator::CreateOr(Not, Op1);
3223 }
3224 case ICmpInst::ICMP_SGE:
3225 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
3226 // FALL THROUGH
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003227 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
3228 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003229 return BinaryOperator::CreateOr(Not, Op0);
3230 }
3231 }
3232 }
3233
Sanjay Patele9b2c322016-05-17 00:57:57 +00003234 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003235 return NewICmp;
3236
Chris Lattner2188e402010-01-04 07:37:31 +00003237 unsigned BitWidth = 0;
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003238 if (Ty->isIntOrIntVectorTy())
Chris Lattner2188e402010-01-04 07:37:31 +00003239 BitWidth = Ty->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003240 else // Get pointer size.
3241 BitWidth = DL.getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00003242
Chris Lattner2188e402010-01-04 07:37:31 +00003243 bool isSignBit = false;
3244
3245 // See if we are doing a comparison with a constant.
3246 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00003247 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003248
Owen Anderson1294ea72010-12-17 18:08:00 +00003249 // Match the following pattern, which is a common idiom when writing
3250 // overflow-safe integer arithmetic function. The source performs an
3251 // addition in wider type, and explicitly checks for overflow using
3252 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
3253 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00003254 //
3255 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00003256 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00003257 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003258 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00003259 // sum = a + b
3260 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00003261 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00003262 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00003263 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00003264 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00003265 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00003266 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00003267 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003268
Philip Reamesec8a8b52016-03-09 21:05:07 +00003269 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
3270 if (CI->isZero() && I.getPredicate() == ICmpInst::ICMP_SGT)
3271 if (auto *SI = dyn_cast<SelectInst>(Op0)) {
3272 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
3273 if (SPR.Flavor == SPF_SMIN) {
Philip Reames8f12eba2016-03-09 21:31:47 +00003274 if (isKnownPositive(A, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003275 return new ICmpInst(I.getPredicate(), B, CI);
Philip Reames8f12eba2016-03-09 21:31:47 +00003276 if (isKnownPositive(B, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003277 return new ICmpInst(I.getPredicate(), A, CI);
3278 }
3279 }
3280
3281
David Majnemera0afb552015-01-14 19:26:56 +00003282 // The following transforms are only 'worth it' if the only user of the
3283 // subtraction is the icmp.
3284 if (Op0->hasOneUse()) {
3285 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
3286 if (I.isEquality() && CI->isZero() &&
3287 match(Op0, m_Sub(m_Value(A), m_Value(B))))
3288 return new ICmpInst(I.getPredicate(), A, B);
3289
3290 // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
3291 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
3292 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3293 return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
3294
3295 // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
3296 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
3297 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3298 return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
3299
3300 // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
3301 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
3302 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3303 return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
3304
3305 // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
3306 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
3307 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3308 return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
Chris Lattner2188e402010-01-04 07:37:31 +00003309 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003310
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003311 if (I.isEquality()) {
3312 ConstantInt *CI2;
3313 if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
3314 match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
David Majnemer59939ac2014-10-19 08:23:08 +00003315 // (icmp eq/ne (ashr/lshr const2, A), const1)
David Majnemer2abb8182014-10-25 07:13:13 +00003316 if (Instruction *Inst = FoldICmpCstShrCst(I, Op0, A, CI, CI2))
3317 return Inst;
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003318 }
David Majnemer59939ac2014-10-19 08:23:08 +00003319 if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
3320 // (icmp eq/ne (shl const2, A), const1)
David Majnemer2abb8182014-10-25 07:13:13 +00003321 if (Instruction *Inst = FoldICmpCstShlCst(I, Op0, A, CI, CI2))
3322 return Inst;
David Majnemer59939ac2014-10-19 08:23:08 +00003323 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003324 }
3325
Chris Lattner2188e402010-01-04 07:37:31 +00003326 // If this comparison is a normal comparison, it demands all
3327 // bits, if it is a sign bit comparison, it only demands the sign bit.
3328 bool UnusedBit;
3329 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
Balaram Makam569eaec2016-05-04 21:32:14 +00003330
3331 // Canonicalize icmp instructions based on dominating conditions.
3332 BasicBlock *Parent = I.getParent();
3333 BasicBlock *Dom = Parent->getSinglePredecessor();
3334 auto *BI = Dom ? dyn_cast<BranchInst>(Dom->getTerminator()) : nullptr;
3335 ICmpInst::Predicate Pred;
3336 BasicBlock *TrueBB, *FalseBB;
3337 ConstantInt *CI2;
3338 if (BI && match(BI, m_Br(m_ICmp(Pred, m_Specific(Op0), m_ConstantInt(CI2)),
3339 TrueBB, FalseBB)) &&
3340 TrueBB != FalseBB) {
3341 ConstantRange CR = ConstantRange::makeAllowedICmpRegion(I.getPredicate(),
3342 CI->getValue());
3343 ConstantRange DominatingCR =
3344 (Parent == TrueBB)
3345 ? ConstantRange::makeExactICmpRegion(Pred, CI2->getValue())
3346 : ConstantRange::makeExactICmpRegion(
3347 CmpInst::getInversePredicate(Pred), CI2->getValue());
3348 ConstantRange Intersection = DominatingCR.intersectWith(CR);
3349 ConstantRange Difference = DominatingCR.difference(CR);
3350 if (Intersection.isEmptySet())
3351 return replaceInstUsesWith(I, Builder->getFalse());
3352 if (Difference.isEmptySet())
3353 return replaceInstUsesWith(I, Builder->getTrue());
3354 // Canonicalizing a sign bit comparison that gets used in a branch,
3355 // pessimizes codegen by generating branch on zero instruction instead
3356 // of a test and branch. So we avoid canonicalizing in such situations
3357 // because test and branch instruction has better branch displacement
3358 // than compare and branch instruction.
3359 if (!isBranchOnSignBitCheck(I, isSignBit) && !I.isEquality()) {
3360 if (auto *AI = Intersection.getSingleElement())
3361 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Builder->getInt(*AI));
3362 if (auto *AD = Difference.getSingleElement())
3363 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Builder->getInt(*AD));
3364 }
3365 }
Chris Lattner2188e402010-01-04 07:37:31 +00003366 }
3367
3368 // See if we can fold the comparison based on range information we can get
3369 // by checking whether bits are known to be zero or one in the input.
3370 if (BitWidth != 0) {
3371 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
3372 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
3373
3374 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersond490c2d2011-01-11 00:36:45 +00003375 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner2188e402010-01-04 07:37:31 +00003376 Op0KnownZero, Op0KnownOne, 0))
3377 return &I;
3378 if (SimplifyDemandedBits(I.getOperandUse(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003379 APInt::getAllOnesValue(BitWidth), Op1KnownZero,
3380 Op1KnownOne, 0))
Chris Lattner2188e402010-01-04 07:37:31 +00003381 return &I;
3382
3383 // Given the known and unknown bits, compute a range that the LHS could be
3384 // in. Compute the Min, Max and RHS values based on the known bits. For the
3385 // EQ and NE we use unsigned values.
3386 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
3387 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
3388 if (I.isSigned()) {
3389 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3390 Op0Min, Op0Max);
3391 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3392 Op1Min, Op1Max);
3393 } else {
3394 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3395 Op0Min, Op0Max);
3396 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3397 Op1Min, Op1Max);
3398 }
3399
3400 // If Min and Max are known to be the same, then SimplifyDemandedBits
3401 // figured out that the LHS is a constant. Just constant fold this now so
3402 // that code below can assume that Min != Max.
3403 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
3404 return new ICmpInst(I.getPredicate(),
Nick Lewycky92db8e82011-03-06 03:36:19 +00003405 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003406 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
3407 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewycky92db8e82011-03-06 03:36:19 +00003408 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner2188e402010-01-04 07:37:31 +00003409
3410 // Based on the range information we know about the LHS, see if we can
Nick Lewycky6b4454192011-02-28 06:20:05 +00003411 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner2188e402010-01-04 07:37:31 +00003412 switch (I.getPredicate()) {
3413 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattnerf7e89612010-11-21 06:44:42 +00003414 case ICmpInst::ICMP_EQ: {
Chris Lattner2188e402010-01-04 07:37:31 +00003415 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003416 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003417
Chris Lattnerf7e89612010-11-21 06:44:42 +00003418 // If all bits are known zero except for one, then we know at most one
3419 // bit is set. If the comparison is against zero, then this is a check
3420 // to see if *that* bit is set.
3421 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003422 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003423 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003424 Value *LHS = nullptr;
3425 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003426 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3427 LHSC->getValue() != Op0KnownZeroInverted)
3428 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003429
Chris Lattnerf7e89612010-11-21 06:44:42 +00003430 // 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 +00003431 // then turn "((1 << x)&8) == 0" into "x != 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003432 // or turn "((1 << x)&7) == 0" into "x > 2".
Craig Topperf40110f2014-04-25 05:29:35 +00003433 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003434 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003435 APInt ValToCheck = Op0KnownZeroInverted;
3436 if (ValToCheck.isPowerOf2()) {
3437 unsigned CmpVal = ValToCheck.countTrailingZeros();
3438 return new ICmpInst(ICmpInst::ICMP_NE, X,
3439 ConstantInt::get(X->getType(), CmpVal));
3440 } else if ((++ValToCheck).isPowerOf2()) {
3441 unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
3442 return new ICmpInst(ICmpInst::ICMP_UGT, X,
3443 ConstantInt::get(X->getType(), CmpVal));
3444 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003445 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003446
Chris Lattnerf7e89612010-11-21 06:44:42 +00003447 // 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 +00003448 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattner98457102011-02-10 05:23:05 +00003449 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003450 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003451 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003452 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner98457102011-02-10 05:23:05 +00003453 ConstantInt::get(X->getType(),
3454 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003455 }
Chris Lattner2188e402010-01-04 07:37:31 +00003456 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003457 }
3458 case ICmpInst::ICMP_NE: {
Chris Lattner2188e402010-01-04 07:37:31 +00003459 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003460 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003461
Chris Lattnerf7e89612010-11-21 06:44:42 +00003462 // If all bits are known zero except for one, then we know at most one
3463 // bit is set. If the comparison is against zero, then this is a check
3464 // to see if *that* bit is set.
3465 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003466 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003467 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003468 Value *LHS = nullptr;
3469 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003470 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3471 LHSC->getValue() != Op0KnownZeroInverted)
3472 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003473
Chris Lattnerf7e89612010-11-21 06:44:42 +00003474 // 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 +00003475 // then turn "((1 << x)&8) != 0" into "x == 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003476 // or turn "((1 << x)&7) != 0" into "x < 3".
Craig Topperf40110f2014-04-25 05:29:35 +00003477 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003478 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003479 APInt ValToCheck = Op0KnownZeroInverted;
3480 if (ValToCheck.isPowerOf2()) {
3481 unsigned CmpVal = ValToCheck.countTrailingZeros();
3482 return new ICmpInst(ICmpInst::ICMP_EQ, X,
3483 ConstantInt::get(X->getType(), CmpVal));
3484 } else if ((++ValToCheck).isPowerOf2()) {
3485 unsigned CmpVal = ValToCheck.countTrailingZeros();
3486 return new ICmpInst(ICmpInst::ICMP_ULT, X,
3487 ConstantInt::get(X->getType(), CmpVal));
3488 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003489 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003490
Chris Lattnerf7e89612010-11-21 06:44:42 +00003491 // 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 +00003492 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattner98457102011-02-10 05:23:05 +00003493 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003494 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003495 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003496 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner98457102011-02-10 05:23:05 +00003497 ConstantInt::get(X->getType(),
3498 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003499 }
Chris Lattner2188e402010-01-04 07:37:31 +00003500 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003501 }
Chris Lattner2188e402010-01-04 07:37:31 +00003502 case ICmpInst::ICMP_ULT:
3503 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003504 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003505 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003506 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003507 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
3508 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3509 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3510 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
3511 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003512 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003513
3514 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
3515 if (CI->isMinValue(true))
3516 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
3517 Constant::getAllOnesValue(Op0->getType()));
3518 }
3519 break;
3520 case ICmpInst::ICMP_UGT:
3521 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003522 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003523 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003524 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003525
3526 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
3527 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3528 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3529 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
3530 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003531 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003532
3533 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
3534 if (CI->isMaxValue(true))
3535 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
3536 Constant::getNullValue(Op0->getType()));
3537 }
3538 break;
3539 case ICmpInst::ICMP_SLT:
3540 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003541 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003542 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003543 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003544 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
3545 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3546 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3547 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
3548 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003549 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003550 }
3551 break;
3552 case ICmpInst::ICMP_SGT:
3553 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003554 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003555 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003556 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003557
3558 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
3559 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3560 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3561 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
3562 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003563 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003564 }
3565 break;
3566 case ICmpInst::ICMP_SGE:
3567 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
3568 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003569 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003570 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003571 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003572 break;
3573 case ICmpInst::ICMP_SLE:
3574 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
3575 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003576 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003577 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003578 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003579 break;
3580 case ICmpInst::ICMP_UGE:
3581 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
3582 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003583 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003584 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003585 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003586 break;
3587 case ICmpInst::ICMP_ULE:
3588 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
3589 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003590 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003591 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003592 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003593 break;
3594 }
3595
3596 // Turn a signed comparison into an unsigned one if both operands
3597 // are known to have the same sign.
3598 if (I.isSigned() &&
3599 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
3600 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
3601 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
3602 }
3603
3604 // Test if the ICmpInst instruction is used exclusively by a select as
3605 // part of a minimum or maximum operation. If so, refrain from doing
3606 // any other folding. This helps out other analyses which understand
3607 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
3608 // and CodeGen. And in this case, at least one of the comparison
3609 // operands has at least one user besides the compare (the select),
3610 // which would often largely negate the benefit of folding anyway.
3611 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00003612 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00003613 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
3614 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00003615 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003616
3617 // See if we are doing a comparison between a constant and an instruction that
3618 // can be folded into the comparison.
3619 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chad Rosier131a42c2016-05-09 19:30:20 +00003620 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003621 // Since the RHS is a ConstantInt (CI), if the left hand side is an
3622 // instruction, see if that instruction also has constants so that the
3623 // instruction can be folded into the icmp
Chris Lattner2188e402010-01-04 07:37:31 +00003624 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3625 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
3626 return Res;
Chad Rosier131a42c2016-05-09 19:30:20 +00003627
3628 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3629 if (I.isEquality() && CI->isZero() &&
3630 match(Op0, m_UDiv(m_Value(A), m_Value(B)))) {
3631 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_EQ
3632 ? ICmpInst::ICMP_UGT
3633 : ICmpInst::ICMP_ULE;
3634 return new ICmpInst(Pred, B, A);
3635 }
Chris Lattner2188e402010-01-04 07:37:31 +00003636 }
3637
3638 // Handle icmp with constant (but not simple integer constant) RHS
3639 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3640 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3641 switch (LHSI->getOpcode()) {
3642 case Instruction::GetElementPtr:
3643 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3644 if (RHSC->isNullValue() &&
3645 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3646 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3647 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3648 break;
3649 case Instruction::PHI:
3650 // Only fold icmp into the PHI if the phi and icmp are in the same
3651 // block. If in the same block, we're encouraging jump threading. If
3652 // not, we are just pessimizing the code by making an i1 phi.
3653 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003654 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003655 return NV;
3656 break;
3657 case Instruction::Select: {
3658 // If either operand of the select is a constant, we can fold the
3659 // comparison into the select arms, which will cause one to be
3660 // constant folded and the select turned into a bitwise or.
Craig Topperf40110f2014-04-25 05:29:35 +00003661 Value *Op1 = nullptr, *Op2 = nullptr;
Hans Wennborg083ca9b2015-10-06 23:24:35 +00003662 ConstantInt *CI = nullptr;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003663 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003664 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003665 CI = dyn_cast<ConstantInt>(Op1);
3666 }
3667 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003668 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003669 CI = dyn_cast<ConstantInt>(Op2);
3670 }
Chris Lattner2188e402010-01-04 07:37:31 +00003671
3672 // We only want to perform this transformation if it will not lead to
3673 // additional code. This is true if either both sides of the select
3674 // fold to a constant (in which case the icmp is replaced with a select
3675 // which will usually simplify) or this is the only user of the
3676 // select (in which case we are trading a select+icmp for a simpler
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003677 // select+icmp) or all uses of the select can be replaced based on
3678 // dominance information ("Global cases").
3679 bool Transform = false;
3680 if (Op1 && Op2)
3681 Transform = true;
3682 else if (Op1 || Op2) {
3683 // Local case
3684 if (LHSI->hasOneUse())
3685 Transform = true;
3686 // Global cases
3687 else if (CI && !CI->isZero())
3688 // When Op1 is constant try replacing select with second operand.
3689 // Otherwise Op2 is constant and try replacing select with first
3690 // operand.
3691 Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
3692 Op1 ? 2 : 1);
3693 }
3694 if (Transform) {
Chris Lattner2188e402010-01-04 07:37:31 +00003695 if (!Op1)
3696 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3697 RHSC, I.getName());
3698 if (!Op2)
3699 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3700 RHSC, I.getName());
3701 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3702 }
3703 break;
3704 }
Chris Lattner2188e402010-01-04 07:37:31 +00003705 case Instruction::IntToPtr:
3706 // icmp pred inttoptr(X), null -> icmp pred X, 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003707 if (RHSC->isNullValue() &&
3708 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
Chris Lattner2188e402010-01-04 07:37:31 +00003709 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3710 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3711 break;
3712
3713 case Instruction::Load:
3714 // Try to optimize things like "A[i] > 4" to index computations.
3715 if (GetElementPtrInst *GEP =
3716 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3717 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3718 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3719 !cast<LoadInst>(LHSI)->isVolatile())
3720 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3721 return Res;
3722 }
3723 break;
3724 }
3725 }
3726
3727 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3728 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
3729 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
3730 return NI;
3731 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
3732 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
3733 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3734 return NI;
3735
Hans Wennborgf1f36512015-10-07 00:20:07 +00003736 // Try to optimize equality comparisons against alloca-based pointers.
3737 if (Op0->getType()->isPointerTy() && I.isEquality()) {
3738 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
3739 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
3740 if (Instruction *New = FoldAllocaCmp(I, Alloca, Op1))
3741 return New;
3742 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
3743 if (Instruction *New = FoldAllocaCmp(I, Alloca, Op0))
3744 return New;
3745 }
3746
Chris Lattner2188e402010-01-04 07:37:31 +00003747 // Test to see if the operands of the icmp are casted versions of other
3748 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3749 // now.
3750 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003751 if (Op0->getType()->isPointerTy() &&
3752 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003753 // We keep moving the cast from the left operand over to the right
3754 // operand, where it can often be eliminated completely.
3755 Op0 = CI->getOperand(0);
3756
3757 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3758 // so eliminate it as well.
3759 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3760 Op1 = CI2->getOperand(0);
3761
3762 // If Op1 is a constant, we can fold the cast into the constant.
3763 if (Op0->getType() != Op1->getType()) {
3764 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3765 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3766 } else {
3767 // Otherwise, cast the RHS right before the icmp
3768 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3769 }
3770 }
3771 return new ICmpInst(I.getPredicate(), Op0, Op1);
3772 }
3773 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003774
Chris Lattner2188e402010-01-04 07:37:31 +00003775 if (isa<CastInst>(Op0)) {
3776 // Handle the special case of: icmp (cast bool to X), <cst>
3777 // This comes up when you have code like
3778 // int X = A < B;
3779 // if (X) ...
3780 // For generality, we handle any zero-extension of any operand comparison
3781 // with a constant or another cast from the same type.
3782 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
3783 if (Instruction *R = visitICmpInstWithCastAndCast(I))
3784 return R;
3785 }
Chris Lattner2188e402010-01-04 07:37:31 +00003786
Duncan Sandse5220012011-02-17 07:46:37 +00003787 // Special logic for binary operators.
3788 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3789 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3790 if (BO0 || BO1) {
3791 CmpInst::Predicate Pred = I.getPredicate();
3792 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3793 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3794 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3795 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3796 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3797 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3798 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3799 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3800 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3801
3802 // Analyze the case when either Op0 or Op1 is an add instruction.
3803 // 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 +00003804 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +00003805 if (BO0 && BO0->getOpcode() == Instruction::Add) {
3806 A = BO0->getOperand(0);
3807 B = BO0->getOperand(1);
3808 }
3809 if (BO1 && BO1->getOpcode() == Instruction::Add) {
3810 C = BO1->getOperand(0);
3811 D = BO1->getOperand(1);
3812 }
Duncan Sandse5220012011-02-17 07:46:37 +00003813
David Majnemer549f4f22014-11-01 09:09:51 +00003814 // icmp (X+cst) < 0 --> X < -cst
3815 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
3816 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
3817 if (!RHSC->isMinValue(/*isSigned=*/true))
3818 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
3819
Duncan Sandse5220012011-02-17 07:46:37 +00003820 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3821 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3822 return new ICmpInst(Pred, A == Op1 ? B : A,
3823 Constant::getNullValue(Op1->getType()));
3824
3825 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3826 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3827 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3828 C == Op0 ? D : C);
3829
Duncan Sands84653b32011-02-18 16:25:37 +00003830 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003831 if (A && C && (A == C || A == D || B == C || B == D) &&
3832 NoOp0WrapProblem && NoOp1WrapProblem &&
3833 // Try not to increase register pressure.
3834 BO0->hasOneUse() && BO1->hasOneUse()) {
3835 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003836 Value *Y, *Z;
3837 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003838 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003839 Y = B;
3840 Z = D;
3841 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003842 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003843 Y = B;
3844 Z = C;
3845 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003846 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003847 Y = A;
3848 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003849 } else {
3850 assert(B == D);
3851 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003852 Y = A;
3853 Z = C;
3854 }
Duncan Sandse5220012011-02-17 07:46:37 +00003855 return new ICmpInst(Pred, Y, Z);
3856 }
3857
David Majnemerb81cd632013-04-11 20:05:46 +00003858 // icmp slt (X + -1), Y -> icmp sle X, Y
3859 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3860 match(B, m_AllOnes()))
3861 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3862
3863 // icmp sge (X + -1), Y -> icmp sgt X, Y
3864 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3865 match(B, m_AllOnes()))
3866 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3867
3868 // icmp sle (X + 1), Y -> icmp slt X, Y
3869 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3870 match(B, m_One()))
3871 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3872
3873 // icmp sgt (X + 1), Y -> icmp sge X, Y
3874 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3875 match(B, m_One()))
3876 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3877
Michael Liaoc65d3862015-10-19 22:08:14 +00003878 // icmp sgt X, (Y + -1) -> icmp sge X, Y
3879 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3880 match(D, m_AllOnes()))
3881 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3882
3883 // icmp sle X, (Y + -1) -> icmp slt X, Y
3884 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3885 match(D, m_AllOnes()))
3886 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3887
3888 // icmp sge X, (Y + 1) -> icmp sgt X, Y
3889 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE &&
3890 match(D, m_One()))
3891 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3892
3893 // icmp slt X, (Y + 1) -> icmp sle X, Y
3894 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT &&
3895 match(D, m_One()))
3896 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3897
David Majnemerb81cd632013-04-11 20:05:46 +00003898 // if C1 has greater magnitude than C2:
3899 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3900 // s.t. C3 = C1 - C2
3901 //
3902 // if C2 has greater magnitude than C1:
3903 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3904 // s.t. C3 = C2 - C1
3905 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3906 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3907 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3908 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3909 const APInt &AP1 = C1->getValue();
3910 const APInt &AP2 = C2->getValue();
3911 if (AP1.isNegative() == AP2.isNegative()) {
3912 APInt AP1Abs = C1->getValue().abs();
3913 APInt AP2Abs = C2->getValue().abs();
3914 if (AP1Abs.uge(AP2Abs)) {
3915 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
3916 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
3917 return new ICmpInst(Pred, NewAdd, C);
3918 } else {
3919 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
3920 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
3921 return new ICmpInst(Pred, A, NewAdd);
3922 }
3923 }
3924 }
3925
3926
Duncan Sandse5220012011-02-17 07:46:37 +00003927 // Analyze the case when either Op0 or Op1 is a sub instruction.
3928 // 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 +00003929 A = nullptr;
3930 B = nullptr;
3931 C = nullptr;
3932 D = nullptr;
3933 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
3934 A = BO0->getOperand(0);
3935 B = BO0->getOperand(1);
3936 }
3937 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3938 C = BO1->getOperand(0);
3939 D = BO1->getOperand(1);
3940 }
Duncan Sandse5220012011-02-17 07:46:37 +00003941
Duncan Sands84653b32011-02-18 16:25:37 +00003942 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3943 if (A == Op1 && NoOp0WrapProblem)
3944 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3945
3946 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
3947 if (C == Op0 && NoOp1WrapProblem)
3948 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3949
3950 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003951 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
3952 // Try not to increase register pressure.
3953 BO0->hasOneUse() && BO1->hasOneUse())
3954 return new ICmpInst(Pred, A, C);
3955
Duncan Sands84653b32011-02-18 16:25:37 +00003956 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
3957 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3958 // Try not to increase register pressure.
3959 BO0->hasOneUse() && BO1->hasOneUse())
3960 return new ICmpInst(Pred, D, B);
3961
David Majnemer186c9422014-05-15 00:02:20 +00003962 // icmp (0-X) < cst --> x > -cst
3963 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3964 Value *X;
3965 if (match(BO0, m_Neg(m_Value(X))))
3966 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
3967 if (!RHSC->isMinValue(/*isSigned=*/true))
3968 return new ICmpInst(I.getSwappedPredicate(), X,
3969 ConstantExpr::getNeg(RHSC));
3970 }
3971
Craig Topperf40110f2014-04-25 05:29:35 +00003972 BinaryOperator *SRem = nullptr;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003973 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00003974 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
3975 Op1 == BO0->getOperand(1))
3976 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003977 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00003978 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3979 Op0 == BO1->getOperand(1))
3980 SRem = BO1;
3981 if (SRem) {
3982 // We don't check hasOneUse to avoid increasing register pressure because
3983 // the value we use is the same value this instruction was already using.
3984 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
3985 default: break;
3986 case ICmpInst::ICMP_EQ:
Sanjay Patel4b198802016-02-01 22:23:39 +00003987 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003988 case ICmpInst::ICMP_NE:
Sanjay Patel4b198802016-02-01 22:23:39 +00003989 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003990 case ICmpInst::ICMP_SGT:
3991 case ICmpInst::ICMP_SGE:
3992 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
3993 Constant::getAllOnesValue(SRem->getType()));
3994 case ICmpInst::ICMP_SLT:
3995 case ICmpInst::ICMP_SLE:
3996 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
3997 Constant::getNullValue(SRem->getType()));
3998 }
3999 }
4000
Duncan Sandse5220012011-02-17 07:46:37 +00004001 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
4002 BO0->hasOneUse() && BO1->hasOneUse() &&
4003 BO0->getOperand(1) == BO1->getOperand(1)) {
4004 switch (BO0->getOpcode()) {
4005 default: break;
4006 case Instruction::Add:
4007 case Instruction::Sub:
4008 case Instruction::Xor:
4009 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
4010 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4011 BO1->getOperand(0));
4012 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
4013 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4014 if (CI->getValue().isSignBit()) {
4015 ICmpInst::Predicate Pred = I.isSigned()
4016 ? I.getUnsignedPredicate()
4017 : I.getSignedPredicate();
4018 return new ICmpInst(Pred, BO0->getOperand(0),
4019 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00004020 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004021
David Majnemerf8853ae2016-02-01 17:37:56 +00004022 if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00004023 ICmpInst::Predicate Pred = I.isSigned()
4024 ? I.getUnsignedPredicate()
4025 : I.getSignedPredicate();
4026 Pred = I.getSwappedPredicate(Pred);
4027 return new ICmpInst(Pred, BO0->getOperand(0),
4028 BO1->getOperand(0));
4029 }
Chris Lattner2188e402010-01-04 07:37:31 +00004030 }
Duncan Sandse5220012011-02-17 07:46:37 +00004031 break;
4032 case Instruction::Mul:
4033 if (!I.isEquality())
4034 break;
4035
4036 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4037 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
4038 // Mask = -1 >> count-trailing-zeros(Cst).
4039 if (!CI->isZero() && !CI->isOne()) {
4040 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004041 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00004042 APInt::getLowBitsSet(AP.getBitWidth(),
4043 AP.getBitWidth() -
4044 AP.countTrailingZeros()));
4045 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
4046 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
4047 return new ICmpInst(I.getPredicate(), And1, And2);
4048 }
4049 }
4050 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00004051 case Instruction::UDiv:
4052 case Instruction::LShr:
4053 if (I.isSigned())
4054 break;
4055 // fall-through
4056 case Instruction::SDiv:
4057 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00004058 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00004059 break;
4060 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4061 BO1->getOperand(0));
4062 case Instruction::Shl: {
4063 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
4064 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
4065 if (!NUW && !NSW)
4066 break;
4067 if (!NSW && I.isSigned())
4068 break;
4069 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4070 BO1->getOperand(0));
4071 }
Chris Lattner2188e402010-01-04 07:37:31 +00004072 }
4073 }
Sanjoy Dasc86c1622015-08-21 22:22:37 +00004074
4075 if (BO0) {
4076 // Transform A & (L - 1) `ult` L --> L != 0
4077 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
4078 auto BitwiseAnd =
4079 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
4080
4081 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
4082 auto *Zero = Constant::getNullValue(BO0->getType());
4083 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
4084 }
4085 }
Chris Lattner2188e402010-01-04 07:37:31 +00004086 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004087
Chris Lattner2188e402010-01-04 07:37:31 +00004088 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00004089 // Transform (A & ~B) == 0 --> (A & B) != 0
4090 // and (A & ~B) != 0 --> (A & B) == 0
4091 // if A is a power of 2.
4092 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00004093 match(Op1, m_Zero()) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004094 isKnownToBeAPowerOfTwo(A, DL, false, 0, AC, &I, DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00004095 return new ICmpInst(I.getInversePredicate(),
4096 Builder->CreateAnd(A, B),
4097 Op1);
4098
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004099 // ~x < ~y --> y < x
4100 // ~x < cst --> ~cst < x
4101 if (match(Op0, m_Not(m_Value(A)))) {
4102 if (match(Op1, m_Not(m_Value(B))))
4103 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00004104 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004105 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
4106 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00004107
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004108 Instruction *AddI = nullptr;
4109 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
4110 m_Instruction(AddI))) &&
4111 isa<IntegerType>(A->getType())) {
4112 Value *Result;
4113 Constant *Overflow;
4114 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
4115 Overflow)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004116 replaceInstUsesWith(*AddI, Result);
4117 return replaceInstUsesWith(I, Overflow);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004118 }
4119 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004120
4121 // (zext a) * (zext b) --> llvm.umul.with.overflow.
4122 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4123 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
4124 return R;
4125 }
4126 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4127 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
4128 return R;
4129 }
Chris Lattner2188e402010-01-04 07:37:31 +00004130 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004131
Chris Lattner2188e402010-01-04 07:37:31 +00004132 if (I.isEquality()) {
4133 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00004134
Chris Lattner2188e402010-01-04 07:37:31 +00004135 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4136 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4137 Value *OtherVal = A == Op1 ? B : A;
4138 return new ICmpInst(I.getPredicate(), OtherVal,
4139 Constant::getNullValue(A->getType()));
4140 }
4141
4142 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4143 // A^c1 == C^c2 --> A == C^(c1^c2)
4144 ConstantInt *C1, *C2;
4145 if (match(B, m_ConstantInt(C1)) &&
4146 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00004147 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004148 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00004149 return new ICmpInst(I.getPredicate(), A, Xor);
4150 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004151
Chris Lattner2188e402010-01-04 07:37:31 +00004152 // A^B == A^D -> B == D
4153 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4154 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4155 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4156 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4157 }
4158 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004159
Chris Lattner2188e402010-01-04 07:37:31 +00004160 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4161 (A == Op0 || B == Op0)) {
4162 // A == (A^B) -> B == 0
4163 Value *OtherVal = A == Op0 ? B : A;
4164 return new ICmpInst(I.getPredicate(), OtherVal,
4165 Constant::getNullValue(A->getType()));
4166 }
4167
Chris Lattner2188e402010-01-04 07:37:31 +00004168 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00004169 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00004170 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Craig Topperf40110f2014-04-25 05:29:35 +00004171 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004172
Chris Lattner2188e402010-01-04 07:37:31 +00004173 if (A == C) {
4174 X = B; Y = D; Z = A;
4175 } else if (A == D) {
4176 X = B; Y = C; Z = A;
4177 } else if (B == C) {
4178 X = A; Y = D; Z = B;
4179 } else if (B == D) {
4180 X = A; Y = C; Z = B;
4181 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004182
Chris Lattner2188e402010-01-04 07:37:31 +00004183 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004184 Op1 = Builder->CreateXor(X, Y);
4185 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00004186 I.setOperand(0, Op1);
4187 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4188 return &I;
4189 }
4190 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004191
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004192 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00004193 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004194 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00004195 if ((Op0->hasOneUse() &&
4196 match(Op0, m_ZExt(m_Value(A))) &&
4197 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
4198 (Op1->hasOneUse() &&
4199 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
4200 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004201 APInt Pow2 = Cst1->getValue() + 1;
4202 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
4203 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
4204 return new ICmpInst(I.getPredicate(), A,
4205 Builder->CreateTrunc(B, A->getType()));
4206 }
4207
Benjamin Kramer03f3e242013-11-16 16:00:48 +00004208 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
4209 // For lshr and ashr pairs.
4210 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4211 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
4212 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4213 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
4214 unsigned TypeBits = Cst1->getBitWidth();
4215 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4216 if (ShAmt < TypeBits && ShAmt != 0) {
4217 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
4218 ? ICmpInst::ICMP_UGE
4219 : ICmpInst::ICMP_ULT;
4220 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4221 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
4222 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
4223 }
4224 }
4225
Benjamin Kramer7fa8c432015-03-26 17:12:06 +00004226 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
4227 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
4228 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
4229 unsigned TypeBits = Cst1->getBitWidth();
4230 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4231 if (ShAmt < TypeBits && ShAmt != 0) {
4232 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4233 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
4234 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
4235 I.getName() + ".mask");
4236 return new ICmpInst(I.getPredicate(), And,
4237 Constant::getNullValue(Cst1->getType()));
4238 }
4239 }
4240
Chris Lattner1b06c712011-04-26 20:18:20 +00004241 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
4242 // "icmp (and X, mask), cst"
4243 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00004244 if (Op0->hasOneUse() &&
4245 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
4246 m_ConstantInt(ShAmt))))) &&
4247 match(Op1, m_ConstantInt(Cst1)) &&
4248 // Only do this when A has multiple uses. This is most important to do
4249 // when it exposes other optimizations.
4250 !A->hasOneUse()) {
4251 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004252
Chris Lattner1b06c712011-04-26 20:18:20 +00004253 if (ShAmt < ASize) {
4254 APInt MaskV =
4255 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
4256 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004257
Chris Lattner1b06c712011-04-26 20:18:20 +00004258 APInt CmpV = Cst1->getValue().zext(ASize);
4259 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004260
Chris Lattner1b06c712011-04-26 20:18:20 +00004261 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
4262 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
4263 }
4264 }
Chris Lattner2188e402010-01-04 07:37:31 +00004265 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004266
David Majnemerc1eca5a2014-11-06 23:23:30 +00004267 // The 'cmpxchg' instruction returns an aggregate containing the old value and
4268 // an i1 which indicates whether or not we successfully did the swap.
4269 //
4270 // Replace comparisons between the old value and the expected value with the
4271 // indicator that 'cmpxchg' returns.
4272 //
4273 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
4274 // spuriously fail. In those cases, the old value may equal the expected
4275 // value but it is possible for the swap to not occur.
4276 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4277 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4278 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4279 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4280 !ACXI->isWeak())
4281 return ExtractValueInst::Create(ACXI, 1);
4282
Chris Lattner2188e402010-01-04 07:37:31 +00004283 {
4284 Value *X; ConstantInt *Cst;
4285 // icmp X+Cst, X
4286 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00004287 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004288
4289 // icmp X, X+Cst
4290 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00004291 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004292 }
Craig Topperf40110f2014-04-25 05:29:35 +00004293 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004294}
4295
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004296/// Fold fcmp ([us]itofp x, cst) if possible.
Chris Lattner2188e402010-01-04 07:37:31 +00004297Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4298 Instruction *LHSI,
4299 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00004300 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004301 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004302
Chris Lattner2188e402010-01-04 07:37:31 +00004303 // Get the width of the mantissa. We don't want to hack on conversions that
4304 // might lose information from the integer, e.g. "i64 -> float"
4305 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00004306 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004307
Matt Arsenault55e73122015-01-06 15:50:59 +00004308 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4309
Chris Lattner2188e402010-01-04 07:37:31 +00004310 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004311
Matt Arsenault55e73122015-01-06 15:50:59 +00004312 if (I.isEquality()) {
4313 FCmpInst::Predicate P = I.getPredicate();
4314 bool IsExact = false;
4315 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
4316 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
4317
4318 // If the floating point constant isn't an integer value, we know if we will
4319 // ever compare equal / not equal to it.
4320 if (!IsExact) {
4321 // TODO: Can never be -0.0 and other non-representable values
4322 APFloat RHSRoundInt(RHS);
4323 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
4324 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
4325 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00004326 return replaceInstUsesWith(I, Builder->getFalse());
Matt Arsenault55e73122015-01-06 15:50:59 +00004327
4328 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
Sanjay Patel4b198802016-02-01 22:23:39 +00004329 return replaceInstUsesWith(I, Builder->getTrue());
Matt Arsenault55e73122015-01-06 15:50:59 +00004330 }
4331 }
4332
4333 // TODO: If the constant is exactly representable, is it always OK to do
4334 // equality compares as integer?
4335 }
4336
Arch D. Robison8ed08542015-09-15 17:51:59 +00004337 // Check to see that the input is converted from an integer type that is small
4338 // enough that preserves all bits. TODO: check here for "known" sign bits.
4339 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4340 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00004341
Arch D. Robison8ed08542015-09-15 17:51:59 +00004342 // Following test does NOT adjust InputSize downwards for signed inputs,
4343 // because the most negative value still requires all the mantissa bits
4344 // to distinguish it from one less than that value.
4345 if ((int)InputSize > MantissaWidth) {
4346 // Conversion would lose accuracy. Check if loss can impact comparison.
4347 int Exp = ilogb(RHS);
4348 if (Exp == APFloat::IEK_Inf) {
4349 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
4350 if (MaxExponent < (int)InputSize - !LHSUnsigned)
4351 // Conversion could create infinity.
4352 return nullptr;
4353 } else {
4354 // Note that if RHS is zero or NaN, then Exp is negative
4355 // and first condition is trivially false.
4356 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
4357 // Conversion could affect comparison.
4358 return nullptr;
4359 }
4360 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004361
Chris Lattner2188e402010-01-04 07:37:31 +00004362 // Otherwise, we can potentially simplify the comparison. We know that it
4363 // will always come through as an integer value and we know the constant is
4364 // not a NAN (it would have been previously simplified).
4365 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00004366
Chris Lattner2188e402010-01-04 07:37:31 +00004367 ICmpInst::Predicate Pred;
4368 switch (I.getPredicate()) {
4369 default: llvm_unreachable("Unexpected predicate!");
4370 case FCmpInst::FCMP_UEQ:
4371 case FCmpInst::FCMP_OEQ:
4372 Pred = ICmpInst::ICMP_EQ;
4373 break;
4374 case FCmpInst::FCMP_UGT:
4375 case FCmpInst::FCMP_OGT:
4376 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4377 break;
4378 case FCmpInst::FCMP_UGE:
4379 case FCmpInst::FCMP_OGE:
4380 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4381 break;
4382 case FCmpInst::FCMP_ULT:
4383 case FCmpInst::FCMP_OLT:
4384 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4385 break;
4386 case FCmpInst::FCMP_ULE:
4387 case FCmpInst::FCMP_OLE:
4388 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4389 break;
4390 case FCmpInst::FCMP_UNE:
4391 case FCmpInst::FCMP_ONE:
4392 Pred = ICmpInst::ICMP_NE;
4393 break;
4394 case FCmpInst::FCMP_ORD:
Sanjay Patel4b198802016-02-01 22:23:39 +00004395 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004396 case FCmpInst::FCMP_UNO:
Sanjay Patel4b198802016-02-01 22:23:39 +00004397 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004398 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004399
Chris Lattner2188e402010-01-04 07:37:31 +00004400 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004401
Chris Lattner2188e402010-01-04 07:37:31 +00004402 // See if the FP constant is too large for the integer. For example,
4403 // comparing an i8 to 300.0.
4404 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004405
Chris Lattner2188e402010-01-04 07:37:31 +00004406 if (!LHSUnsigned) {
4407 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4408 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004409 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004410 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4411 APFloat::rmNearestTiesToEven);
4412 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4413 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4414 Pred == ICmpInst::ICMP_SLE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004415 return replaceInstUsesWith(I, Builder->getTrue());
4416 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004417 }
4418 } else {
4419 // If the RHS value is > UnsignedMax, fold the comparison. This handles
4420 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004421 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004422 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4423 APFloat::rmNearestTiesToEven);
4424 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
4425 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
4426 Pred == ICmpInst::ICMP_ULE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004427 return replaceInstUsesWith(I, Builder->getTrue());
4428 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004429 }
4430 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004431
Chris Lattner2188e402010-01-04 07:37:31 +00004432 if (!LHSUnsigned) {
4433 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004434 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004435 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4436 APFloat::rmNearestTiesToEven);
4437 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4438 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4439 Pred == ICmpInst::ICMP_SGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004440 return replaceInstUsesWith(I, Builder->getTrue());
4441 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004442 }
Devang Patel698452b2012-02-13 23:05:18 +00004443 } else {
4444 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004445 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00004446 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
4447 APFloat::rmNearestTiesToEven);
4448 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
4449 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
4450 Pred == ICmpInst::ICMP_UGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004451 return replaceInstUsesWith(I, Builder->getTrue());
4452 return replaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00004453 }
Chris Lattner2188e402010-01-04 07:37:31 +00004454 }
4455
4456 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4457 // [0, UMAX], but it may still be fractional. See if it is fractional by
4458 // casting the FP value to the integer value and back, checking for equality.
4459 // Don't do this for zero, because -0.0 is not fractional.
4460 Constant *RHSInt = LHSUnsigned
4461 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4462 : ConstantExpr::getFPToSI(RHSC, IntTy);
4463 if (!RHS.isZero()) {
4464 bool Equal = LHSUnsigned
4465 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4466 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4467 if (!Equal) {
4468 // If we had a comparison against a fractional value, we have to adjust
4469 // the compare predicate and sometimes the value. RHSC is rounded towards
4470 // zero at this point.
4471 switch (Pred) {
4472 default: llvm_unreachable("Unexpected integer comparison!");
4473 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Sanjay Patel4b198802016-02-01 22:23:39 +00004474 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004475 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Sanjay Patel4b198802016-02-01 22:23:39 +00004476 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004477 case ICmpInst::ICMP_ULE:
4478 // (float)int <= 4.4 --> int <= 4
4479 // (float)int <= -4.4 --> false
4480 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004481 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004482 break;
4483 case ICmpInst::ICMP_SLE:
4484 // (float)int <= 4.4 --> int <= 4
4485 // (float)int <= -4.4 --> int < -4
4486 if (RHS.isNegative())
4487 Pred = ICmpInst::ICMP_SLT;
4488 break;
4489 case ICmpInst::ICMP_ULT:
4490 // (float)int < -4.4 --> false
4491 // (float)int < 4.4 --> int <= 4
4492 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004493 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004494 Pred = ICmpInst::ICMP_ULE;
4495 break;
4496 case ICmpInst::ICMP_SLT:
4497 // (float)int < -4.4 --> int < -4
4498 // (float)int < 4.4 --> int <= 4
4499 if (!RHS.isNegative())
4500 Pred = ICmpInst::ICMP_SLE;
4501 break;
4502 case ICmpInst::ICMP_UGT:
4503 // (float)int > 4.4 --> int > 4
4504 // (float)int > -4.4 --> true
4505 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004506 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004507 break;
4508 case ICmpInst::ICMP_SGT:
4509 // (float)int > 4.4 --> int > 4
4510 // (float)int > -4.4 --> int >= -4
4511 if (RHS.isNegative())
4512 Pred = ICmpInst::ICMP_SGE;
4513 break;
4514 case ICmpInst::ICMP_UGE:
4515 // (float)int >= -4.4 --> true
4516 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00004517 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004518 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004519 Pred = ICmpInst::ICMP_UGT;
4520 break;
4521 case ICmpInst::ICMP_SGE:
4522 // (float)int >= -4.4 --> int >= -4
4523 // (float)int >= 4.4 --> int > 4
4524 if (!RHS.isNegative())
4525 Pred = ICmpInst::ICMP_SGT;
4526 break;
4527 }
4528 }
4529 }
4530
4531 // Lower this FP comparison into an appropriate integer version of the
4532 // comparison.
4533 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4534}
4535
4536Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4537 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004538
Chris Lattner2188e402010-01-04 07:37:31 +00004539 /// Orders the operands of the compare so that they are listed from most
4540 /// complex to least complex. This puts constants before unary operators,
4541 /// before binary operators.
4542 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4543 I.swapOperands();
4544 Changed = true;
4545 }
4546
4547 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004548
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004549 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
4550 I.getFastMathFlags(), DL, TLI, DT, AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004551 return replaceInstUsesWith(I, V);
Chris Lattner2188e402010-01-04 07:37:31 +00004552
4553 // Simplify 'fcmp pred X, X'
4554 if (Op0 == Op1) {
4555 switch (I.getPredicate()) {
4556 default: llvm_unreachable("Unknown predicate!");
4557 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4558 case FCmpInst::FCMP_ULT: // True if unordered or less than
4559 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4560 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4561 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4562 I.setPredicate(FCmpInst::FCMP_UNO);
4563 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4564 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004565
Chris Lattner2188e402010-01-04 07:37:31 +00004566 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4567 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4568 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4569 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4570 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4571 I.setPredicate(FCmpInst::FCMP_ORD);
4572 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4573 return &I;
4574 }
4575 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004576
James Molloy2b21a7c2015-05-20 18:41:25 +00004577 // Test if the FCmpInst instruction is used exclusively by a select as
4578 // part of a minimum or maximum operation. If so, refrain from doing
4579 // any other folding. This helps out other analyses which understand
4580 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4581 // and CodeGen. And in this case, at least one of the comparison
4582 // operands has at least one user besides the compare (the select),
4583 // which would often largely negate the benefit of folding anyway.
4584 if (I.hasOneUse())
4585 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4586 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4587 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4588 return nullptr;
4589
Chris Lattner2188e402010-01-04 07:37:31 +00004590 // Handle fcmp with constant RHS
4591 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4592 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4593 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004594 case Instruction::FPExt: {
4595 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4596 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4597 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4598 if (!RHSF)
4599 break;
4600
4601 const fltSemantics *Sem;
4602 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004603 if (LHSExt->getSrcTy()->isHalfTy())
4604 Sem = &APFloat::IEEEhalf;
4605 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004606 Sem = &APFloat::IEEEsingle;
4607 else if (LHSExt->getSrcTy()->isDoubleTy())
4608 Sem = &APFloat::IEEEdouble;
4609 else if (LHSExt->getSrcTy()->isFP128Ty())
4610 Sem = &APFloat::IEEEquad;
4611 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
4612 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004613 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
4614 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004615 else
4616 break;
4617
4618 bool Lossy;
4619 APFloat F = RHSF->getValueAPF();
4620 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4621
Jim Grosbach24ff8342011-09-30 18:45:50 +00004622 // Avoid lossy conversions and denormals. Zero is a special case
4623 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004624 APFloat Fabs = F;
4625 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004626 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004627 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4628 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004629
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004630 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4631 ConstantFP::get(RHSC->getContext(), F));
4632 break;
4633 }
Chris Lattner2188e402010-01-04 07:37:31 +00004634 case Instruction::PHI:
4635 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4636 // block. If in the same block, we're encouraging jump threading. If
4637 // not, we are just pessimizing the code by making an i1 phi.
4638 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004639 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004640 return NV;
4641 break;
4642 case Instruction::SIToFP:
4643 case Instruction::UIToFP:
4644 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
4645 return NV;
4646 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004647 case Instruction::FSub: {
4648 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4649 Value *Op;
4650 if (match(LHSI, m_FNeg(m_Value(Op))))
4651 return new FCmpInst(I.getSwappedPredicate(), Op,
4652 ConstantExpr::getFNeg(RHSC));
4653 break;
4654 }
Dan Gohman94732022010-02-24 06:46:09 +00004655 case Instruction::Load:
4656 if (GetElementPtrInst *GEP =
4657 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4658 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4659 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4660 !cast<LoadInst>(LHSI)->isVolatile())
4661 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
4662 return Res;
4663 }
4664 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004665 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004666 if (!RHSC->isNullValue())
4667 break;
4668
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004669 CallInst *CI = cast<CallInst>(LHSI);
David Majnemerb4b27232016-04-19 19:10:21 +00004670 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer2e02ba72016-04-15 17:21:03 +00004671 if (IID != Intrinsic::fabs)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004672 break;
4673
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004674 // Various optimization for fabs compared with zero.
David Majnemer2e02ba72016-04-15 17:21:03 +00004675 switch (I.getPredicate()) {
4676 default:
4677 break;
4678 // fabs(x) < 0 --> false
4679 case FCmpInst::FCMP_OLT:
4680 llvm_unreachable("handled by SimplifyFCmpInst");
4681 // fabs(x) > 0 --> x != 0
4682 case FCmpInst::FCMP_OGT:
4683 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
4684 // fabs(x) <= 0 --> x == 0
4685 case FCmpInst::FCMP_OLE:
4686 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
4687 // fabs(x) >= 0 --> !isnan(x)
4688 case FCmpInst::FCMP_OGE:
4689 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
4690 // fabs(x) == 0 --> x == 0
4691 // fabs(x) != 0 --> x != 0
4692 case FCmpInst::FCMP_OEQ:
4693 case FCmpInst::FCMP_UEQ:
4694 case FCmpInst::FCMP_ONE:
4695 case FCmpInst::FCMP_UNE:
4696 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004697 }
4698 }
Chris Lattner2188e402010-01-04 07:37:31 +00004699 }
Chris Lattner2188e402010-01-04 07:37:31 +00004700 }
4701
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004702 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004703 Value *X, *Y;
4704 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004705 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004706
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004707 // fcmp (fpext x), (fpext y) -> fcmp x, y
4708 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4709 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4710 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4711 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4712 RHSExt->getOperand(0));
4713
Craig Topperf40110f2014-04-25 05:29:35 +00004714 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004715}