blob: f14b818c5943457f15100c73b6142d1f066a1b6e [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
Chris Lattner98457102011-02-10 05:23:05 +000038
Chris Lattner2188e402010-01-04 07:37:31 +000039static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
40 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
41}
42
43static bool HasAddOverflow(ConstantInt *Result,
44 ConstantInt *In1, ConstantInt *In2,
45 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000046 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000047 return Result->getValue().ult(In1->getValue());
Chris Lattnerb1a15122011-07-15 06:08:15 +000048
49 if (In2->isNegative())
50 return Result->getValue().sgt(In1->getValue());
51 return Result->getValue().slt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000052}
53
Sanjay Patel5f0217f2016-06-05 16:46:18 +000054/// Compute Result = In1+In2, returning true if the result overflowed for this
55/// type.
Chris Lattner2188e402010-01-04 07:37:31 +000056static bool AddWithOverflow(Constant *&Result, Constant *In1,
57 Constant *In2, bool IsSigned = false) {
58 Result = ConstantExpr::getAdd(In1, In2);
59
Chris Lattner229907c2011-07-18 04:54:35 +000060 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000061 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
62 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
63 if (HasAddOverflow(ExtractElement(Result, Idx),
64 ExtractElement(In1, Idx),
65 ExtractElement(In2, Idx),
66 IsSigned))
67 return true;
68 }
69 return false;
70 }
71
72 return HasAddOverflow(cast<ConstantInt>(Result),
73 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
74 IsSigned);
75}
76
77static bool HasSubOverflow(ConstantInt *Result,
78 ConstantInt *In1, ConstantInt *In2,
79 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000080 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000081 return Result->getValue().ugt(In1->getValue());
Jim Grosbach129c52a2011-09-30 18:09:53 +000082
Chris Lattnerb1a15122011-07-15 06:08:15 +000083 if (In2->isNegative())
84 return Result->getValue().slt(In1->getValue());
85
86 return Result->getValue().sgt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000087}
88
Sanjay Patel5f0217f2016-06-05 16:46:18 +000089/// Compute Result = In1-In2, returning true if the result overflowed for this
90/// type.
Chris Lattner2188e402010-01-04 07:37:31 +000091static bool SubWithOverflow(Constant *&Result, Constant *In1,
92 Constant *In2, bool IsSigned = false) {
93 Result = ConstantExpr::getSub(In1, In2);
94
Chris Lattner229907c2011-07-18 04:54:35 +000095 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000096 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
97 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
98 if (HasSubOverflow(ExtractElement(Result, Idx),
99 ExtractElement(In1, Idx),
100 ExtractElement(In2, Idx),
101 IsSigned))
102 return true;
103 }
104 return false;
105 }
106
107 return HasSubOverflow(cast<ConstantInt>(Result),
108 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
109 IsSigned);
110}
111
Balaram Makam569eaec2016-05-04 21:32:14 +0000112/// Given an icmp instruction, return true if any use of this comparison is a
113/// branch on sign bit comparison.
114static bool isBranchOnSignBitCheck(ICmpInst &I, bool isSignBit) {
115 for (auto *U : I.users())
116 if (isa<BranchInst>(U))
117 return isSignBit;
118 return false;
119}
120
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000121/// Given an exploded icmp instruction, return true if the comparison only
122/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if the
123/// result of the comparison is true when the input value is signed.
Sanjay Patel79263662016-08-21 15:07:45 +0000124static bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000125 bool &TrueIfSigned) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000126 switch (Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +0000127 case ICmpInst::ICMP_SLT: // True if LHS s< 0
128 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000129 return RHS == 0;
Chris Lattner2188e402010-01-04 07:37:31 +0000130 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
131 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000132 return RHS.isAllOnesValue();
Chris Lattner2188e402010-01-04 07:37:31 +0000133 case ICmpInst::ICMP_SGT: // True if LHS s> -1
134 TrueIfSigned = false;
Sanjay Patel79263662016-08-21 15:07:45 +0000135 return RHS.isAllOnesValue();
Chris Lattner2188e402010-01-04 07:37:31 +0000136 case ICmpInst::ICMP_UGT:
137 // True if LHS u> RHS and RHS == high-bit-mask - 1
138 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000139 return RHS.isMaxSignedValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000140 case ICmpInst::ICMP_UGE:
Chris Lattner2188e402010-01-04 07:37:31 +0000141 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
142 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000143 return RHS.isSignBit();
Chris Lattner2188e402010-01-04 07:37:31 +0000144 default:
145 return false;
146 }
147}
148
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000149/// Returns true if the exploded icmp can be expressed as a signed comparison
150/// to zero and updates the predicate accordingly.
151/// The signedness of the comparison is preserved.
Sanjay Patel5b112842016-08-18 14:59:14 +0000152/// TODO: Refactor with decomposeBitTestICmp()?
153static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000154 if (!ICmpInst::isSigned(Pred))
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000155 return false;
156
Sanjay Patel5b112842016-08-18 14:59:14 +0000157 if (C == 0)
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000158 return ICmpInst::isRelational(Pred);
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000159
Sanjay Patel5b112842016-08-18 14:59:14 +0000160 if (C == 1) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000161 if (Pred == ICmpInst::ICMP_SLT) {
162 Pred = ICmpInst::ICMP_SLE;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000163 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000164 }
Sanjay Patel5b112842016-08-18 14:59:14 +0000165 } else if (C.isAllOnesValue()) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000166 if (Pred == ICmpInst::ICMP_SGT) {
167 Pred = ICmpInst::ICMP_SGE;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000168 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000169 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000170 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000171
172 return false;
173}
174
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000175/// Given a signed integer type and a set of known zero and one bits, compute
176/// the maximum and minimum values that could have the specified known zero and
177/// known one bits, returning them in Min/Max.
178static void ComputeSignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
179 const APInt &KnownOne,
180 APInt &Min, APInt &Max) {
Chris Lattner2188e402010-01-04 07:37:31 +0000181 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
182 KnownZero.getBitWidth() == Min.getBitWidth() &&
183 KnownZero.getBitWidth() == Max.getBitWidth() &&
184 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
185 APInt UnknownBits = ~(KnownZero|KnownOne);
186
187 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
188 // bit if it is unknown.
189 Min = KnownOne;
190 Max = KnownOne|UnknownBits;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000191
Chris Lattner2188e402010-01-04 07:37:31 +0000192 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000193 Min.setBit(Min.getBitWidth()-1);
194 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000195 }
196}
197
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000198/// Given an unsigned integer type and a set of known zero and one bits, compute
199/// the maximum and minimum values that could have the specified known zero and
200/// known one bits, returning them in Min/Max.
Chris Lattner2188e402010-01-04 07:37:31 +0000201static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
202 const APInt &KnownOne,
203 APInt &Min, APInt &Max) {
204 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
205 KnownZero.getBitWidth() == Min.getBitWidth() &&
206 KnownZero.getBitWidth() == Max.getBitWidth() &&
207 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
208 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000209
Chris Lattner2188e402010-01-04 07:37:31 +0000210 // The minimum value is when the unknown bits are all zeros.
211 Min = KnownOne;
212 // The maximum value is when the unknown bits are all ones.
213 Max = KnownOne|UnknownBits;
214}
215
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000216/// This is called when we see this pattern:
Chris Lattner2188e402010-01-04 07:37:31 +0000217/// cmp pred (load (gep GV, ...)), cmpcst
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000218/// where GV is a global variable with a constant initializer. Try to simplify
219/// this into some simple computation that does not need the load. For example
Chris Lattner2188e402010-01-04 07:37:31 +0000220/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
221///
222/// If AndCst is non-null, then the loaded value is masked with that constant
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000223/// before doing the comparison. This handles cases like "A[i]&4 == 0".
Sanjay Patel43395062016-07-21 18:07:40 +0000224Instruction *InstCombiner::foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
225 GlobalVariable *GV,
226 CmpInst &ICI,
227 ConstantInt *AndCst) {
Chris Lattnerfe741762012-01-31 02:55:06 +0000228 Constant *Init = GV->getInitializer();
229 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
Craig Topperf40110f2014-04-25 05:29:35 +0000230 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000231
Chris Lattnerfe741762012-01-31 02:55:06 +0000232 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +0000233 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000234
Chris Lattner2188e402010-01-04 07:37:31 +0000235 // There are many forms of this optimization we can handle, for now, just do
236 // the simple index into a single-dimensional array.
237 //
238 // Require: GEP GV, 0, i {{, constant indices}}
239 if (GEP->getNumOperands() < 3 ||
240 !isa<ConstantInt>(GEP->getOperand(1)) ||
241 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
242 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000243 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000244
245 // Check that indices after the variable are constants and in-range for the
246 // type they index. Collect the indices. This is typically for arrays of
247 // structs.
248 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000249
Chris Lattnerfe741762012-01-31 02:55:06 +0000250 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000251 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
252 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000253 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000254
Chris Lattner2188e402010-01-04 07:37:31 +0000255 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000256 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000257
Chris Lattner229907c2011-07-18 04:54:35 +0000258 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000259 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000260 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000261 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000262 EltTy = ATy->getElementType();
263 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000264 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000265 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000266
Chris Lattner2188e402010-01-04 07:37:31 +0000267 LaterIndices.push_back(IdxVal);
268 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000269
Chris Lattner2188e402010-01-04 07:37:31 +0000270 enum { Overdefined = -3, Undefined = -2 };
271
272 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000273
Chris Lattner2188e402010-01-04 07:37:31 +0000274 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
275 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
276 // and 87 is the second (and last) index. FirstTrueElement is -2 when
277 // undefined, otherwise set to the first true element. SecondTrueElement is
278 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
279 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
280
281 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
282 // form "i != 47 & i != 87". Same state transitions as for true elements.
283 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000284
Chris Lattner2188e402010-01-04 07:37:31 +0000285 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
286 /// define a state machine that triggers for ranges of values that the index
287 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
288 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
289 /// index in the range (inclusive). We use -2 for undefined here because we
290 /// use relative comparisons and don't want 0-1 to match -1.
291 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000292
Chris Lattner2188e402010-01-04 07:37:31 +0000293 // MagicBitvector - This is a magic bitvector where we set a bit if the
294 // comparison is true for element 'i'. If there are 64 elements or less in
295 // the array, this will fully represent all the comparison results.
296 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000297
Chris Lattner2188e402010-01-04 07:37:31 +0000298 // Scan the array and see if one of our patterns matches.
299 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000300 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
301 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000302 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000303
Chris Lattner2188e402010-01-04 07:37:31 +0000304 // If this is indexing an array of structures, get the structure element.
305 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000306 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000307
Chris Lattner2188e402010-01-04 07:37:31 +0000308 // If the element is masked, handle it.
309 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000310
Chris Lattner2188e402010-01-04 07:37:31 +0000311 // Find out if the comparison would be true or false for the i'th element.
312 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Justin Bogner99798402016-08-05 01:06:44 +0000313 CompareRHS, DL, &TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000314 // If the result is undef for this element, ignore it.
315 if (isa<UndefValue>(C)) {
316 // Extend range state machines to cover this element in case there is an
317 // undef in the middle of the range.
318 if (TrueRangeEnd == (int)i-1)
319 TrueRangeEnd = i;
320 if (FalseRangeEnd == (int)i-1)
321 FalseRangeEnd = i;
322 continue;
323 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000324
Chris Lattner2188e402010-01-04 07:37:31 +0000325 // If we can't compute the result for any of the elements, we have to give
326 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000327 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000328
Chris Lattner2188e402010-01-04 07:37:31 +0000329 // Otherwise, we know if the comparison is true or false for this element,
330 // update our state machines.
331 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000332
Chris Lattner2188e402010-01-04 07:37:31 +0000333 // State machine for single/double/range index comparison.
334 if (IsTrueForElt) {
335 // Update the TrueElement state machine.
336 if (FirstTrueElement == Undefined)
337 FirstTrueElement = TrueRangeEnd = i; // First true element.
338 else {
339 // Update double-compare state machine.
340 if (SecondTrueElement == Undefined)
341 SecondTrueElement = i;
342 else
343 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000344
Chris Lattner2188e402010-01-04 07:37:31 +0000345 // Update range state machine.
346 if (TrueRangeEnd == (int)i-1)
347 TrueRangeEnd = i;
348 else
349 TrueRangeEnd = Overdefined;
350 }
351 } else {
352 // Update the FalseElement state machine.
353 if (FirstFalseElement == Undefined)
354 FirstFalseElement = FalseRangeEnd = i; // First false element.
355 else {
356 // Update double-compare state machine.
357 if (SecondFalseElement == Undefined)
358 SecondFalseElement = i;
359 else
360 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000361
Chris Lattner2188e402010-01-04 07:37:31 +0000362 // Update range state machine.
363 if (FalseRangeEnd == (int)i-1)
364 FalseRangeEnd = i;
365 else
366 FalseRangeEnd = Overdefined;
367 }
368 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000369
Chris Lattner2188e402010-01-04 07:37:31 +0000370 // If this element is in range, update our magic bitvector.
371 if (i < 64 && IsTrueForElt)
372 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000373
Chris Lattner2188e402010-01-04 07:37:31 +0000374 // If all of our states become overdefined, bail out early. Since the
375 // predicate is expensive, only check it every 8 elements. This is only
376 // really useful for really huge arrays.
377 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
378 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
379 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000380 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000381 }
382
383 // Now that we've scanned the entire array, emit our new comparison(s). We
384 // order the state machines in complexity of the generated code.
385 Value *Idx = GEP->getOperand(2);
386
Matt Arsenault5aeae182013-08-19 21:40:31 +0000387 // If the index is larger than the pointer size of the target, truncate the
388 // index down like the GEP would do implicitly. We don't have to do this for
389 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000390 if (!GEP->isInBounds()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000391 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000392 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
393 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
394 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
395 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000396
Chris Lattner2188e402010-01-04 07:37:31 +0000397 // If the comparison is only true for one or two elements, emit direct
398 // comparisons.
399 if (SecondTrueElement != Overdefined) {
400 // None true -> false.
401 if (FirstTrueElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000402 return replaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000403
Chris Lattner2188e402010-01-04 07:37:31 +0000404 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000405
Chris Lattner2188e402010-01-04 07:37:31 +0000406 // True for one element -> 'i == 47'.
407 if (SecondTrueElement == Undefined)
408 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000409
Chris Lattner2188e402010-01-04 07:37:31 +0000410 // True for two elements -> 'i == 47 | i == 72'.
411 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
412 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
413 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
414 return BinaryOperator::CreateOr(C1, C2);
415 }
416
417 // If the comparison is only false for one or two elements, emit direct
418 // comparisons.
419 if (SecondFalseElement != Overdefined) {
420 // None false -> true.
421 if (FirstFalseElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000422 return replaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000423
Chris Lattner2188e402010-01-04 07:37:31 +0000424 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
425
426 // False for one element -> 'i != 47'.
427 if (SecondFalseElement == Undefined)
428 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000429
Chris Lattner2188e402010-01-04 07:37:31 +0000430 // False for two elements -> 'i != 47 & i != 72'.
431 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
432 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
433 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
434 return BinaryOperator::CreateAnd(C1, C2);
435 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000436
Chris Lattner2188e402010-01-04 07:37:31 +0000437 // If the comparison can be replaced with a range comparison for the elements
438 // where it is true, emit the range check.
439 if (TrueRangeEnd != Overdefined) {
440 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000441
Chris Lattner2188e402010-01-04 07:37:31 +0000442 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
443 if (FirstTrueElement) {
444 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
445 Idx = Builder->CreateAdd(Idx, Offs);
446 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000447
Chris Lattner2188e402010-01-04 07:37:31 +0000448 Value *End = ConstantInt::get(Idx->getType(),
449 TrueRangeEnd-FirstTrueElement+1);
450 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
451 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000452
Chris Lattner2188e402010-01-04 07:37:31 +0000453 // False range check.
454 if (FalseRangeEnd != Overdefined) {
455 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
456 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
457 if (FirstFalseElement) {
458 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
459 Idx = Builder->CreateAdd(Idx, Offs);
460 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000461
Chris Lattner2188e402010-01-04 07:37:31 +0000462 Value *End = ConstantInt::get(Idx->getType(),
463 FalseRangeEnd-FirstFalseElement);
464 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
465 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000466
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000467 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000468 // of this load, replace it with computation that does:
469 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000470 {
Craig Topperf40110f2014-04-25 05:29:35 +0000471 Type *Ty = nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000472
473 // Look for an appropriate type:
474 // - The type of Idx if the magic fits
475 // - The smallest fitting legal type if we have a DataLayout
476 // - Default to i32
477 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
478 Ty = Idx->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000479 else
480 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000481
Craig Topperf40110f2014-04-25 05:29:35 +0000482 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000483 Value *V = Builder->CreateIntCast(Idx, Ty, false);
484 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
485 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
486 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
487 }
Chris Lattner2188e402010-01-04 07:37:31 +0000488 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000489
Craig Topperf40110f2014-04-25 05:29:35 +0000490 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000491}
492
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000493/// Return a value that can be used to compare the *offset* implied by a GEP to
494/// zero. For example, if we have &A[i], we want to return 'i' for
495/// "icmp ne i, 0". Note that, in general, indices can be complex, and scales
496/// are involved. The above expression would also be legal to codegen as
497/// "icmp ne (i*4), 0" (assuming A is a pointer to i32).
498/// This latter form is less amenable to optimization though, and we are allowed
Chris Lattner2188e402010-01-04 07:37:31 +0000499/// to generate the first by knowing that pointer arithmetic doesn't overflow.
500///
501/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000502///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000503static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
504 const DataLayout &DL) {
Chris Lattner2188e402010-01-04 07:37:31 +0000505 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000506
Chris Lattner2188e402010-01-04 07:37:31 +0000507 // Check to see if this gep only has a single variable index. If so, and if
508 // any constant indices are a multiple of its scale, then we can compute this
509 // in terms of the scale of the variable index. For example, if the GEP
510 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
511 // because the expression will cross zero at the same point.
512 unsigned i, e = GEP->getNumOperands();
513 int64_t Offset = 0;
514 for (i = 1; i != e; ++i, ++GTI) {
515 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
516 // Compute the aggregate offset of constant indices.
517 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000518
Chris Lattner2188e402010-01-04 07:37:31 +0000519 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000520 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000521 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000522 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000523 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000524 Offset += Size*CI->getSExtValue();
525 }
526 } else {
527 // Found our variable index.
528 break;
529 }
530 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000531
Chris Lattner2188e402010-01-04 07:37:31 +0000532 // If there are no variable indices, we must have a constant offset, just
533 // evaluate it the general way.
Craig Topperf40110f2014-04-25 05:29:35 +0000534 if (i == e) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000535
Chris Lattner2188e402010-01-04 07:37:31 +0000536 Value *VariableIdx = GEP->getOperand(i);
537 // Determine the scale factor of the variable element. For example, this is
538 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000539 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000540
Chris Lattner2188e402010-01-04 07:37:31 +0000541 // Verify that there are no other variable indices. If so, emit the hard way.
542 for (++i, ++GTI; i != e; ++i, ++GTI) {
543 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000544 if (!CI) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000545
Chris Lattner2188e402010-01-04 07:37:31 +0000546 // Compute the aggregate offset of constant indices.
547 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000548
Chris Lattner2188e402010-01-04 07:37:31 +0000549 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000550 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000551 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000552 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000553 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000554 Offset += Size*CI->getSExtValue();
555 }
556 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000557
Chris Lattner2188e402010-01-04 07:37:31 +0000558 // Okay, we know we have a single variable index, which must be a
559 // pointer/array/vector index. If there is no offset, life is simple, return
560 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000561 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000562 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000563 if (Offset == 0) {
564 // Cast to intptrty in case a truncation occurs. If an extension is needed,
565 // we don't need to bother extending: the extension won't affect where the
566 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000567 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000568 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
569 }
Chris Lattner2188e402010-01-04 07:37:31 +0000570 return VariableIdx;
571 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000572
Chris Lattner2188e402010-01-04 07:37:31 +0000573 // Otherwise, there is an index. The computation we will do will be modulo
574 // the pointer size, so get it.
575 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000576
Chris Lattner2188e402010-01-04 07:37:31 +0000577 Offset &= PtrSizeMask;
578 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000579
Chris Lattner2188e402010-01-04 07:37:31 +0000580 // To do this transformation, any constant index must be a multiple of the
581 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
582 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
583 // multiple of the variable scale.
584 int64_t NewOffs = Offset / (int64_t)VariableScale;
585 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000586 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000587
Chris Lattner2188e402010-01-04 07:37:31 +0000588 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000589 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000590 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
591 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000592 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000593 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000594}
595
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000596/// Returns true if we can rewrite Start as a GEP with pointer Base
597/// and some integer offset. The nodes that need to be re-written
598/// for this transformation will be added to Explored.
599static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
600 const DataLayout &DL,
601 SetVector<Value *> &Explored) {
602 SmallVector<Value *, 16> WorkList(1, Start);
603 Explored.insert(Base);
604
605 // The following traversal gives us an order which can be used
606 // when doing the final transformation. Since in the final
607 // transformation we create the PHI replacement instructions first,
608 // we don't have to get them in any particular order.
609 //
610 // However, for other instructions we will have to traverse the
611 // operands of an instruction first, which means that we have to
612 // do a post-order traversal.
613 while (!WorkList.empty()) {
614 SetVector<PHINode *> PHIs;
615
616 while (!WorkList.empty()) {
617 if (Explored.size() >= 100)
618 return false;
619
620 Value *V = WorkList.back();
621
622 if (Explored.count(V) != 0) {
623 WorkList.pop_back();
624 continue;
625 }
626
627 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
628 !isa<GEPOperator>(V) && !isa<PHINode>(V))
629 // We've found some value that we can't explore which is different from
630 // the base. Therefore we can't do this transformation.
631 return false;
632
633 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
634 auto *CI = dyn_cast<CastInst>(V);
635 if (!CI->isNoopCast(DL))
636 return false;
637
638 if (Explored.count(CI->getOperand(0)) == 0)
639 WorkList.push_back(CI->getOperand(0));
640 }
641
642 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
643 // We're limiting the GEP to having one index. This will preserve
644 // the original pointer type. We could handle more cases in the
645 // future.
646 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
647 GEP->getType() != Start->getType())
648 return false;
649
650 if (Explored.count(GEP->getOperand(0)) == 0)
651 WorkList.push_back(GEP->getOperand(0));
652 }
653
654 if (WorkList.back() == V) {
655 WorkList.pop_back();
656 // We've finished visiting this node, mark it as such.
657 Explored.insert(V);
658 }
659
660 if (auto *PN = dyn_cast<PHINode>(V)) {
David Majnemercdf28732016-03-19 04:39:52 +0000661 // We cannot transform PHIs on unsplittable basic blocks.
662 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
663 return false;
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000664 Explored.insert(PN);
665 PHIs.insert(PN);
666 }
667 }
668
669 // Explore the PHI nodes further.
670 for (auto *PN : PHIs)
671 for (Value *Op : PN->incoming_values())
672 if (Explored.count(Op) == 0)
673 WorkList.push_back(Op);
674 }
675
676 // Make sure that we can do this. Since we can't insert GEPs in a basic
677 // block before a PHI node, we can't easily do this transformation if
678 // we have PHI node users of transformed instructions.
679 for (Value *Val : Explored) {
680 for (Value *Use : Val->uses()) {
681
682 auto *PHI = dyn_cast<PHINode>(Use);
683 auto *Inst = dyn_cast<Instruction>(Val);
684
685 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
686 Explored.count(PHI) == 0)
687 continue;
688
689 if (PHI->getParent() == Inst->getParent())
690 return false;
691 }
692 }
693 return true;
694}
695
696// Sets the appropriate insert point on Builder where we can add
697// a replacement Instruction for V (if that is possible).
698static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
699 bool Before = true) {
700 if (auto *PHI = dyn_cast<PHINode>(V)) {
701 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
702 return;
703 }
704 if (auto *I = dyn_cast<Instruction>(V)) {
705 if (!Before)
706 I = &*std::next(I->getIterator());
707 Builder.SetInsertPoint(I);
708 return;
709 }
710 if (auto *A = dyn_cast<Argument>(V)) {
711 // Set the insertion point in the entry block.
712 BasicBlock &Entry = A->getParent()->getEntryBlock();
713 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
714 return;
715 }
716 // Otherwise, this is a constant and we don't need to set a new
717 // insertion point.
718 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
719}
720
721/// Returns a re-written value of Start as an indexed GEP using Base as a
722/// pointer.
723static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
724 const DataLayout &DL,
725 SetVector<Value *> &Explored) {
726 // Perform all the substitutions. This is a bit tricky because we can
727 // have cycles in our use-def chains.
728 // 1. Create the PHI nodes without any incoming values.
729 // 2. Create all the other values.
730 // 3. Add the edges for the PHI nodes.
731 // 4. Emit GEPs to get the original pointers.
732 // 5. Remove the original instructions.
733 Type *IndexType = IntegerType::get(
734 Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType()));
735
736 DenseMap<Value *, Value *> NewInsts;
737 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
738
739 // Create the new PHI nodes, without adding any incoming values.
740 for (Value *Val : Explored) {
741 if (Val == Base)
742 continue;
743 // Create empty phi nodes. This avoids cyclic dependencies when creating
744 // the remaining instructions.
745 if (auto *PHI = dyn_cast<PHINode>(Val))
746 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
747 PHI->getName() + ".idx", PHI);
748 }
749 IRBuilder<> Builder(Base->getContext());
750
751 // Create all the other instructions.
752 for (Value *Val : Explored) {
753
754 if (NewInsts.find(Val) != NewInsts.end())
755 continue;
756
757 if (auto *CI = dyn_cast<CastInst>(Val)) {
758 NewInsts[CI] = NewInsts[CI->getOperand(0)];
759 continue;
760 }
761 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
762 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
763 : GEP->getOperand(1);
764 setInsertionPoint(Builder, GEP);
765 // Indices might need to be sign extended. GEPs will magically do
766 // this, but we need to do it ourselves here.
767 if (Index->getType()->getScalarSizeInBits() !=
768 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
769 Index = Builder.CreateSExtOrTrunc(
770 Index, NewInsts[GEP->getOperand(0)]->getType(),
771 GEP->getOperand(0)->getName() + ".sext");
772 }
773
774 auto *Op = NewInsts[GEP->getOperand(0)];
775 if (isa<ConstantInt>(Op) && dyn_cast<ConstantInt>(Op)->isZero())
776 NewInsts[GEP] = Index;
777 else
778 NewInsts[GEP] = Builder.CreateNSWAdd(
779 Op, Index, GEP->getOperand(0)->getName() + ".add");
780 continue;
781 }
782 if (isa<PHINode>(Val))
783 continue;
784
785 llvm_unreachable("Unexpected instruction type");
786 }
787
788 // Add the incoming values to the PHI nodes.
789 for (Value *Val : Explored) {
790 if (Val == Base)
791 continue;
792 // All the instructions have been created, we can now add edges to the
793 // phi nodes.
794 if (auto *PHI = dyn_cast<PHINode>(Val)) {
795 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
796 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
797 Value *NewIncoming = PHI->getIncomingValue(I);
798
799 if (NewInsts.find(NewIncoming) != NewInsts.end())
800 NewIncoming = NewInsts[NewIncoming];
801
802 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
803 }
804 }
805 }
806
807 for (Value *Val : Explored) {
808 if (Val == Base)
809 continue;
810
811 // Depending on the type, for external users we have to emit
812 // a GEP or a GEP + ptrtoint.
813 setInsertionPoint(Builder, Val, false);
814
815 // If required, create an inttoptr instruction for Base.
816 Value *NewBase = Base;
817 if (!Base->getType()->isPointerTy())
818 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
819 Start->getName() + "to.ptr");
820
821 Value *GEP = Builder.CreateInBoundsGEP(
822 Start->getType()->getPointerElementType(), NewBase,
823 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
824
825 if (!Val->getType()->isPointerTy()) {
826 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
827 Val->getName() + ".conv");
828 GEP = Cast;
829 }
830 Val->replaceAllUsesWith(GEP);
831 }
832
833 return NewInsts[Start];
834}
835
836/// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
837/// the input Value as a constant indexed GEP. Returns a pair containing
838/// the GEPs Pointer and Index.
839static std::pair<Value *, Value *>
840getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
841 Type *IndexType = IntegerType::get(V->getContext(),
842 DL.getPointerTypeSizeInBits(V->getType()));
843
844 Constant *Index = ConstantInt::getNullValue(IndexType);
845 while (true) {
846 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
847 // We accept only inbouds GEPs here to exclude the possibility of
848 // overflow.
849 if (!GEP->isInBounds())
850 break;
851 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
852 GEP->getType() == V->getType()) {
853 V = GEP->getOperand(0);
854 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
855 Index = ConstantExpr::getAdd(
856 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
857 continue;
858 }
859 break;
860 }
861 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
862 if (!CI->isNoopCast(DL))
863 break;
864 V = CI->getOperand(0);
865 continue;
866 }
867 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
868 if (!CI->isNoopCast(DL))
869 break;
870 V = CI->getOperand(0);
871 continue;
872 }
873 break;
874 }
875 return {V, Index};
876}
877
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000878/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
879/// We can look through PHIs, GEPs and casts in order to determine a common base
880/// between GEPLHS and RHS.
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000881static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
882 ICmpInst::Predicate Cond,
883 const DataLayout &DL) {
884 if (!GEPLHS->hasAllConstantIndices())
885 return nullptr;
886
887 Value *PtrBase, *Index;
888 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
889
890 // The set of nodes that will take part in this transformation.
891 SetVector<Value *> Nodes;
892
893 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
894 return nullptr;
895
896 // We know we can re-write this as
897 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
898 // Since we've only looked through inbouds GEPs we know that we
899 // can't have overflow on either side. We can therefore re-write
900 // this as:
901 // OFFSET1 cmp OFFSET2
902 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
903
904 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
905 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
906 // offset. Since Index is the offset of LHS to the base pointer, we will now
907 // compare the offsets instead of comparing the pointers.
908 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
909}
910
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000911/// Fold comparisons between a GEP instruction and something else. At this point
912/// we know that the GEP is on the LHS of the comparison.
Sanjay Patel43395062016-07-21 18:07:40 +0000913Instruction *InstCombiner::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000914 ICmpInst::Predicate Cond,
915 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000916 // Don't transform signed compares of GEPs into index compares. Even if the
917 // GEP is inbounds, the final add of the base pointer can have signed overflow
918 // and would change the result of the icmp.
919 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000920 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000921 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000922 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000923
Matt Arsenault44f60d02014-06-09 19:20:29 +0000924 // Look through bitcasts and addrspacecasts. We do not however want to remove
925 // 0 GEPs.
926 if (!isa<GetElementPtrInst>(RHS))
927 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000928
929 Value *PtrBase = GEPLHS->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000930 if (PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000931 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
932 // This transformation (ignoring the base and scales) is valid because we
933 // know pointers can't overflow since the gep is inbounds. See if we can
934 // output an optimized form.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000935 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this, DL);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000936
Chris Lattner2188e402010-01-04 07:37:31 +0000937 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000938 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000939 Offset = EmitGEPOffset(GEPLHS);
940 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
941 Constant::getNullValue(Offset->getType()));
942 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
943 // If the base pointers are different, but the indices are the same, just
944 // compare the base pointer.
945 if (PtrBase != GEPRHS->getOperand(0)) {
946 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
947 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
948 GEPRHS->getOperand(0)->getType();
949 if (IndicesTheSame)
950 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
951 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
952 IndicesTheSame = false;
953 break;
954 }
955
956 // If all indices are the same, just compare the base pointers.
957 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000958 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000959
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000960 // If we're comparing GEPs with two base pointers that only differ in type
961 // and both GEPs have only constant indices or just one use, then fold
962 // the compare with the adjusted indices.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000963 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000964 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
965 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
966 PtrBase->stripPointerCasts() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000967 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000968 Value *LOffset = EmitGEPOffset(GEPLHS);
969 Value *ROffset = EmitGEPOffset(GEPRHS);
970
971 // If we looked through an addrspacecast between different sized address
972 // spaces, the LHS and RHS pointers are different sized
973 // integers. Truncate to the smaller one.
974 Type *LHSIndexTy = LOffset->getType();
975 Type *RHSIndexTy = ROffset->getType();
976 if (LHSIndexTy != RHSIndexTy) {
977 if (LHSIndexTy->getPrimitiveSizeInBits() <
978 RHSIndexTy->getPrimitiveSizeInBits()) {
979 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
980 } else
981 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
982 }
983
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000984 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000985 LOffset, ROffset);
Sanjay Patel4b198802016-02-01 22:23:39 +0000986 return replaceInstUsesWith(I, Cmp);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000987 }
988
Chris Lattner2188e402010-01-04 07:37:31 +0000989 // Otherwise, the base pointers are different and the indices are
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000990 // different. Try convert this to an indexed compare by looking through
991 // PHIs/casts.
992 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +0000993 }
994
995 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +0000996 if (GEPLHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +0000997 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +0000998 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +0000999
1000 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001001 if (GEPRHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +00001002 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner2188e402010-01-04 07:37:31 +00001003
Stuart Hastings66a82b92011-05-14 05:55:10 +00001004 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +00001005 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
1006 // If the GEPs only differ by one index, compare it.
1007 unsigned NumDifferences = 0; // Keep track of # differences.
1008 unsigned DiffOperand = 0; // The operand that differs.
1009 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
1010 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
1011 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
1012 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
1013 // Irreconcilable differences.
1014 NumDifferences = 2;
1015 break;
1016 } else {
1017 if (NumDifferences++) break;
1018 DiffOperand = i;
1019 }
1020 }
1021
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +00001022 if (NumDifferences == 0) // SAME GEP?
Sanjay Patel4b198802016-02-01 22:23:39 +00001023 return replaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +00001024 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +00001025
Stuart Hastings66a82b92011-05-14 05:55:10 +00001026 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +00001027 Value *LHSV = GEPLHS->getOperand(DiffOperand);
1028 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1029 // Make sure we do a signed comparison here.
1030 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
1031 }
1032 }
1033
1034 // Only lower this if the icmp is the only user of the GEP or if we expect
1035 // the result to fold to a constant!
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001036 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner2188e402010-01-04 07:37:31 +00001037 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1038 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
1039 Value *L = EmitGEPOffset(GEPLHS);
1040 Value *R = EmitGEPOffset(GEPRHS);
1041 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1042 }
1043 }
Silviu Barangaf29dfd32016-01-15 15:52:05 +00001044
1045 // Try convert this to an indexed compare by looking through PHIs/casts as a
1046 // last resort.
1047 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +00001048}
1049
Pete Cooper980a9352016-08-12 17:13:28 +00001050Instruction *InstCombiner::foldAllocaCmp(ICmpInst &ICI,
1051 const AllocaInst *Alloca,
1052 const Value *Other) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001053 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1054
1055 // It would be tempting to fold away comparisons between allocas and any
1056 // pointer not based on that alloca (e.g. an argument). However, even
1057 // though such pointers cannot alias, they can still compare equal.
1058 //
1059 // But LLVM doesn't specify where allocas get their memory, so if the alloca
1060 // doesn't escape we can argue that it's impossible to guess its value, and we
1061 // can therefore act as if any such guesses are wrong.
1062 //
1063 // The code below checks that the alloca doesn't escape, and that it's only
1064 // used in a comparison once (the current instruction). The
1065 // single-comparison-use condition ensures that we're trivially folding all
1066 // comparisons against the alloca consistently, and avoids the risk of
1067 // erroneously folding a comparison of the pointer with itself.
1068
1069 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1070
Pete Cooper980a9352016-08-12 17:13:28 +00001071 SmallVector<const Use *, 32> Worklist;
1072 for (const Use &U : Alloca->uses()) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001073 if (Worklist.size() >= MaxIter)
1074 return nullptr;
1075 Worklist.push_back(&U);
1076 }
1077
1078 unsigned NumCmps = 0;
1079 while (!Worklist.empty()) {
1080 assert(Worklist.size() <= MaxIter);
Pete Cooper980a9352016-08-12 17:13:28 +00001081 const Use *U = Worklist.pop_back_val();
1082 const Value *V = U->getUser();
Hans Wennborgf1f36512015-10-07 00:20:07 +00001083 --MaxIter;
1084
1085 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1086 isa<SelectInst>(V)) {
1087 // Track the uses.
1088 } else if (isa<LoadInst>(V)) {
1089 // Loading from the pointer doesn't escape it.
1090 continue;
Pete Cooper980a9352016-08-12 17:13:28 +00001091 } else if (const auto *SI = dyn_cast<StoreInst>(V)) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001092 // Storing *to* the pointer is fine, but storing the pointer escapes it.
1093 if (SI->getValueOperand() == U->get())
1094 return nullptr;
1095 continue;
1096 } else if (isa<ICmpInst>(V)) {
1097 if (NumCmps++)
1098 return nullptr; // Found more than one cmp.
1099 continue;
Pete Cooper980a9352016-08-12 17:13:28 +00001100 } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001101 switch (Intrin->getIntrinsicID()) {
1102 // These intrinsics don't escape or compare the pointer. Memset is safe
1103 // because we don't allow ptrtoint. Memcpy and memmove are safe because
1104 // we don't allow stores, so src cannot point to V.
1105 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1106 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
1107 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1108 continue;
1109 default:
1110 return nullptr;
1111 }
1112 } else {
1113 return nullptr;
1114 }
Pete Cooper980a9352016-08-12 17:13:28 +00001115 for (const Use &U : V->uses()) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001116 if (Worklist.size() >= MaxIter)
1117 return nullptr;
1118 Worklist.push_back(&U);
1119 }
1120 }
1121
1122 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001123 return replaceInstUsesWith(
Hans Wennborgf1f36512015-10-07 00:20:07 +00001124 ICI,
1125 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1126}
1127
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001128/// Fold "icmp pred (X+CI), X".
Sanjay Patel43395062016-07-21 18:07:40 +00001129Instruction *InstCombiner::foldICmpAddOpConst(Instruction &ICI,
1130 Value *X, ConstantInt *CI,
1131 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +00001132 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001133 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +00001134 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +00001135
Chris Lattner8c92b572010-01-08 17:48:19 +00001136 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +00001137 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
1138 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
1139 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00001140 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +00001141 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +00001142 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1143 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001144
Chris Lattner2188e402010-01-04 07:37:31 +00001145 // (X+1) >u X --> X <u (0-1) --> X != 255
1146 // (X+2) >u X --> X <u (0-2) --> X <u 254
1147 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +00001148 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +00001149 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001150
Chris Lattner2188e402010-01-04 07:37:31 +00001151 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
1152 ConstantInt *SMax = ConstantInt::get(X->getContext(),
1153 APInt::getSignedMaxValue(BitWidth));
1154
1155 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1156 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1157 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1158 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1159 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1160 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +00001161 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +00001162 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001163
Chris Lattner2188e402010-01-04 07:37:31 +00001164 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1165 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1166 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1167 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1168 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1169 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +00001170
Chris Lattner2188e402010-01-04 07:37:31 +00001171 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +00001172 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +00001173 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
1174}
1175
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001176/// Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001177/// (icmp eq/ne A, Log2(const2/const1)) ->
1178/// (icmp eq/ne A, Log2(const2) - Log2(const1)).
Sanjay Patel43395062016-07-21 18:07:40 +00001179Instruction *InstCombiner::foldICmpCstShrConst(ICmpInst &I, Value *Op, Value *A,
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001180 ConstantInt *CI1,
1181 ConstantInt *CI2) {
1182 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1183
1184 auto getConstant = [&I, this](bool IsTrue) {
1185 if (I.getPredicate() == I.ICMP_NE)
1186 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001187 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001188 };
1189
1190 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1191 if (I.getPredicate() == I.ICMP_NE)
1192 Pred = CmpInst::getInversePredicate(Pred);
1193 return new ICmpInst(Pred, LHS, RHS);
1194 };
1195
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001196 const APInt &AP1 = CI1->getValue();
1197 const APInt &AP2 = CI2->getValue();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001198
David Majnemer2abb8182014-10-25 07:13:13 +00001199 // Don't bother doing any work for cases which InstSimplify handles.
1200 if (AP2 == 0)
1201 return nullptr;
1202 bool IsAShr = isa<AShrOperator>(Op);
1203 if (IsAShr) {
1204 if (AP2.isAllOnesValue())
1205 return nullptr;
1206 if (AP2.isNegative() != AP1.isNegative())
1207 return nullptr;
1208 if (AP2.sgt(AP1))
1209 return nullptr;
1210 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001211
David Majnemerd2056022014-10-21 19:51:55 +00001212 if (!AP1)
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001213 // 'A' must be large enough to shift out the highest set bit.
1214 return getICmp(I.ICMP_UGT, A,
1215 ConstantInt::get(A->getType(), AP2.logBase2()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001216
David Majnemerd2056022014-10-21 19:51:55 +00001217 if (AP1 == AP2)
1218 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001219
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001220 int Shift;
David Majnemerd2056022014-10-21 19:51:55 +00001221 if (IsAShr && AP1.isNegative())
David Majnemere5977eb2015-09-19 00:48:26 +00001222 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001223 else
David Majnemere5977eb2015-09-19 00:48:26 +00001224 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001225
David Majnemerd2056022014-10-21 19:51:55 +00001226 if (Shift > 0) {
David Majnemere5977eb2015-09-19 00:48:26 +00001227 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1228 // There are multiple solutions if we are comparing against -1 and the LHS
David Majnemer47ce0b82015-09-19 00:48:31 +00001229 // of the ashr is not a power of two.
David Majnemere5977eb2015-09-19 00:48:26 +00001230 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1231 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
David Majnemerd2056022014-10-21 19:51:55 +00001232 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
David Majnemere5977eb2015-09-19 00:48:26 +00001233 } else if (AP1 == AP2.lshr(Shift)) {
1234 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1235 }
David Majnemerd2056022014-10-21 19:51:55 +00001236 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001237 // Shifting const2 will never be equal to const1.
1238 return getConstant(false);
1239}
Chris Lattner2188e402010-01-04 07:37:31 +00001240
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001241/// Handle "(icmp eq/ne (shl const2, A), const1)" ->
David Majnemer59939ac2014-10-19 08:23:08 +00001242/// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)).
Sanjay Patel43395062016-07-21 18:07:40 +00001243Instruction *InstCombiner::foldICmpCstShlConst(ICmpInst &I, Value *Op, Value *A,
1244 ConstantInt *CI1,
1245 ConstantInt *CI2) {
David Majnemer59939ac2014-10-19 08:23:08 +00001246 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1247
1248 auto getConstant = [&I, this](bool IsTrue) {
1249 if (I.getPredicate() == I.ICMP_NE)
1250 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001251 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
David Majnemer59939ac2014-10-19 08:23:08 +00001252 };
1253
1254 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1255 if (I.getPredicate() == I.ICMP_NE)
1256 Pred = CmpInst::getInversePredicate(Pred);
1257 return new ICmpInst(Pred, LHS, RHS);
1258 };
1259
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001260 const APInt &AP1 = CI1->getValue();
1261 const APInt &AP2 = CI2->getValue();
David Majnemer59939ac2014-10-19 08:23:08 +00001262
David Majnemer2abb8182014-10-25 07:13:13 +00001263 // Don't bother doing any work for cases which InstSimplify handles.
1264 if (AP2 == 0)
1265 return nullptr;
David Majnemer59939ac2014-10-19 08:23:08 +00001266
1267 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1268
1269 if (!AP1 && AP2TrailingZeros != 0)
1270 return getICmp(I.ICMP_UGE, A,
1271 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1272
1273 if (AP1 == AP2)
1274 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1275
1276 // Get the distance between the lowest bits that are set.
1277 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1278
1279 if (Shift > 0 && AP2.shl(Shift) == AP1)
1280 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1281
1282 // Shifting const2 will never be equal to const1.
1283 return getConstant(false);
1284}
1285
Sanjay Patel06b127a2016-09-15 14:37:50 +00001286/// The caller has matched a pattern of the form:
1287/// I = icmp ugt (add (add A, B), CI2), CI1
1288/// If this is of the form:
1289/// sum = a + b
1290/// if (sum+128 >u 255)
1291/// Then replace it with llvm.sadd.with.overflow.i8.
1292///
1293static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1294 ConstantInt *CI2, ConstantInt *CI1,
1295 InstCombiner &IC) {
1296 // The transformation we're trying to do here is to transform this into an
1297 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1298 // with a narrower add, and discard the add-with-constant that is part of the
1299 // range check (if we can't eliminate it, this isn't profitable).
1300
1301 // In order to eliminate the add-with-constant, the compare can be its only
1302 // use.
1303 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1304 if (!AddWithCst->hasOneUse())
1305 return nullptr;
1306
1307 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1308 if (!CI2->getValue().isPowerOf2())
1309 return nullptr;
1310 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1311 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1312 return nullptr;
1313
1314 // The width of the new add formed is 1 more than the bias.
1315 ++NewWidth;
1316
1317 // Check to see that CI1 is an all-ones value with NewWidth bits.
1318 if (CI1->getBitWidth() == NewWidth ||
1319 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1320 return nullptr;
1321
1322 // This is only really a signed overflow check if the inputs have been
1323 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1324 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1325 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1326 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
1327 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
1328 return nullptr;
1329
1330 // In order to replace the original add with a narrower
1331 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1332 // and truncates that discard the high bits of the add. Verify that this is
1333 // the case.
1334 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1335 for (User *U : OrigAdd->users()) {
1336 if (U == AddWithCst)
1337 continue;
1338
1339 // Only accept truncates for now. We would really like a nice recursive
1340 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1341 // chain to see which bits of a value are actually demanded. If the
1342 // original add had another add which was then immediately truncated, we
1343 // could still do the transformation.
1344 TruncInst *TI = dyn_cast<TruncInst>(U);
1345 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1346 return nullptr;
1347 }
1348
1349 // If the pattern matches, truncate the inputs to the narrower type and
1350 // use the sadd_with_overflow intrinsic to efficiently compute both the
1351 // result and the overflow bit.
1352 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1353 Value *F = Intrinsic::getDeclaration(I.getModule(),
1354 Intrinsic::sadd_with_overflow, NewType);
1355
1356 InstCombiner::BuilderTy *Builder = IC.Builder;
1357
1358 // Put the new code above the original add, in case there are any uses of the
1359 // add between the add and the compare.
1360 Builder->SetInsertPoint(OrigAdd);
1361
1362 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName() + ".trunc");
1363 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName() + ".trunc");
1364 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
1365 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1366 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
1367
1368 // The inner add was the result of the narrow add, zero extended to the
1369 // wider type. Replace it with the result computed by the intrinsic.
1370 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1371
1372 // The original icmp gets replaced with the overflow value.
1373 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1374}
1375
1376// Fold icmp Pred X, C.
Sanjay Patel97459832016-09-15 15:11:12 +00001377Instruction *InstCombiner::foldICmpWithConstant(ICmpInst &Cmp) {
1378 CmpInst::Predicate Pred = Cmp.getPredicate();
Sanjay Patel40c53ea2016-09-15 16:23:20 +00001379 Value *X = Cmp.getOperand(0);
Sanjay Patel06b127a2016-09-15 14:37:50 +00001380
Sanjay Patel40c53ea2016-09-15 16:23:20 +00001381 const APInt *C;
1382 if (!match(Cmp.getOperand(1), m_APInt(C)))
Sanjay Patel97459832016-09-15 15:11:12 +00001383 return nullptr;
Sanjay Patel06b127a2016-09-15 14:37:50 +00001384
Sanjay Patel97459832016-09-15 15:11:12 +00001385 Value *A = nullptr, *B = nullptr;
Sanjay Patel06b127a2016-09-15 14:37:50 +00001386
Sanjay Patel97459832016-09-15 15:11:12 +00001387 // Match the following pattern, which is a common idiom when writing
1388 // overflow-safe integer arithmetic functions. The source performs an addition
1389 // in wider type and explicitly checks for overflow using comparisons against
1390 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1391 //
1392 // TODO: This could probably be generalized to handle other overflow-safe
1393 // operations if we worked out the formulas to compute the appropriate magic
1394 // constants.
1395 //
1396 // sum = a + b
1397 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1398 {
1399 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1400 if (Pred == ICmpInst::ICMP_UGT &&
1401 match(X, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Sanjay Patel40c53ea2016-09-15 16:23:20 +00001402 if (Instruction *Res = ProcessUGT_ADDCST_ADD(
1403 Cmp, A, B, CI2, cast<ConstantInt>(Cmp.getOperand(1)), *this))
Sanjay Patel97459832016-09-15 15:11:12 +00001404 return Res;
1405 }
Sanjay Patel06b127a2016-09-15 14:37:50 +00001406
Sanjay Patel97459832016-09-15 15:11:12 +00001407 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
Sanjay Patel40c53ea2016-09-15 16:23:20 +00001408 if (*C == 0 && Pred == ICmpInst::ICMP_SGT) {
1409 SelectPatternResult SPR = matchSelectPattern(X, A, B);
1410 if (SPR.Flavor == SPF_SMIN) {
1411 if (isKnownPositive(A, DL))
1412 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1413 if (isKnownPositive(B, DL))
1414 return new ICmpInst(Pred, A, Cmp.getOperand(1));
Sanjay Patel06b127a2016-09-15 14:37:50 +00001415 }
Sanjay Patel40c53ea2016-09-15 16:23:20 +00001416 }
1417
1418 // FIXME: Use m_APInt to allow folds for splat constants.
1419 ConstantInt *CI = dyn_cast<ConstantInt>(Cmp.getOperand(1));
1420 if (!CI)
1421 return nullptr;
Sanjay Patel06b127a2016-09-15 14:37:50 +00001422
Sanjay Patel97459832016-09-15 15:11:12 +00001423 // The following transforms are only worth it if the only user of the subtract
1424 // is the icmp.
1425 if (X->hasOneUse()) {
Sanjay Patel97459832016-09-15 15:11:12 +00001426 // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
1427 if (Pred == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
1428 match(X, m_NSWSub(m_Value(A), m_Value(B))))
1429 return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
1430
1431 // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
1432 if (Pred == ICmpInst::ICMP_SGT && CI->isZero() &&
1433 match(X, m_NSWSub(m_Value(A), m_Value(B))))
1434 return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
1435
1436 // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
1437 if (Pred == ICmpInst::ICMP_SLT && CI->isZero() &&
1438 match(X, m_NSWSub(m_Value(A), m_Value(B))))
1439 return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
1440
1441 // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
1442 if (Pred == ICmpInst::ICMP_SLT && CI->isOne() &&
1443 match(X, m_NSWSub(m_Value(A), m_Value(B))))
1444 return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
1445 }
1446
1447 if (Cmp.isEquality()) {
Sanjay Patel06b127a2016-09-15 14:37:50 +00001448 ConstantInt *CI2;
Sanjay Patel97459832016-09-15 15:11:12 +00001449 if (match(X, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
1450 match(X, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
1451 // (icmp eq/ne (ashr/lshr const2, A), const1)
1452 if (Instruction *Inst = foldICmpCstShrConst(Cmp, X, A, CI, CI2))
1453 return Inst;
1454 }
1455 if (match(X, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
1456 // (icmp eq/ne (shl const2, A), const1)
1457 if (Instruction *Inst = foldICmpCstShlConst(Cmp, X, A, CI, CI2))
1458 return Inst;
1459 }
1460 }
Sanjay Patel06b127a2016-09-15 14:37:50 +00001461
Sanjay Patel97459832016-09-15 15:11:12 +00001462 // Canonicalize icmp instructions based on dominating conditions.
1463 BasicBlock *Parent = Cmp.getParent();
1464 BasicBlock *Dom = Parent->getSinglePredecessor();
1465 auto *BI = Dom ? dyn_cast<BranchInst>(Dom->getTerminator()) : nullptr;
1466 ICmpInst::Predicate Pred2;
1467 BasicBlock *TrueBB, *FalseBB;
1468 ConstantInt *CI2;
1469 if (BI && match(BI, m_Br(m_ICmp(Pred2, m_Specific(X), m_ConstantInt(CI2)),
1470 TrueBB, FalseBB)) &&
1471 TrueBB != FalseBB) {
1472 ConstantRange CR =
1473 ConstantRange::makeAllowedICmpRegion(Pred, CI->getValue());
1474 ConstantRange DominatingCR =
1475 (Parent == TrueBB)
1476 ? ConstantRange::makeExactICmpRegion(Pred2, CI2->getValue())
1477 : ConstantRange::makeExactICmpRegion(
1478 CmpInst::getInversePredicate(Pred2), CI2->getValue());
1479 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1480 ConstantRange Difference = DominatingCR.difference(CR);
1481 if (Intersection.isEmptySet())
1482 return replaceInstUsesWith(Cmp, Builder->getFalse());
1483 if (Difference.isEmptySet())
1484 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel06b127a2016-09-15 14:37:50 +00001485
Sanjay Patel97459832016-09-15 15:11:12 +00001486 // If this is a normal comparison, it demands all bits. If it is a sign
1487 // bit comparison, it only demands the sign bit.
1488 bool UnusedBit;
1489 bool IsSignBit = isSignBitCheck(Pred, CI->getValue(), UnusedBit);
1490
1491 // Canonicalizing a sign bit comparison that gets used in a branch,
1492 // pessimizes codegen by generating branch on zero instruction instead
1493 // of a test and branch. So we avoid canonicalizing in such situations
1494 // because test and branch instruction has better branch displacement
1495 // than compare and branch instruction.
1496 if (!isBranchOnSignBitCheck(Cmp, IsSignBit) && !Cmp.isEquality()) {
1497 if (auto *AI = Intersection.getSingleElement())
1498 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder->getInt(*AI));
1499 if (auto *AD = Difference.getSingleElement())
1500 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder->getInt(*AD));
Sanjay Patel06b127a2016-09-15 14:37:50 +00001501 }
1502 }
1503
1504 return nullptr;
1505}
1506
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001507/// Fold icmp (trunc X, Y), C.
1508Instruction *InstCombiner::foldICmpTruncConstant(ICmpInst &Cmp,
1509 Instruction *Trunc,
1510 const APInt *C) {
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001511 ICmpInst::Predicate Pred = Cmp.getPredicate();
1512 Value *X = Trunc->getOperand(0);
Sanjay Patel40e8ca42016-08-18 20:28:54 +00001513 if (*C == 1 && C->getBitWidth() > 1) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001514 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1515 Value *V = nullptr;
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001516 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001517 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1518 ConstantInt::get(V->getType(), 1));
1519 }
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001520
1521 if (Cmp.isEquality() && Trunc->hasOneUse()) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001522 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1523 // of the high bits truncated out of x are known.
Sanjay Patel40e8ca42016-08-18 20:28:54 +00001524 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1525 SrcBits = X->getType()->getScalarSizeInBits();
Sanjay Patela3f4f082016-08-16 17:54:36 +00001526 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001527 computeKnownBits(X, KnownZero, KnownOne, 0, &Cmp);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001528
1529 // If all the high bits are known, we can do this xform.
1530 if ((KnownZero | KnownOne).countLeadingOnes() >= SrcBits - DstBits) {
1531 // Pull in the high bits from known-ones set.
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001532 APInt NewRHS = C->zext(SrcBits);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001533 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
Sanjay Patel40e8ca42016-08-18 20:28:54 +00001534 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), NewRHS));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001535 }
1536 }
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001537
Sanjay Patela3f4f082016-08-16 17:54:36 +00001538 return nullptr;
1539}
1540
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001541/// Fold icmp (xor X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001542Instruction *InstCombiner::foldICmpXorConstant(ICmpInst &Cmp,
1543 BinaryOperator *Xor,
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001544 const APInt *C) {
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001545 Value *X = Xor->getOperand(0);
1546 Value *Y = Xor->getOperand(1);
Sanjay Pateldaffec912016-08-17 19:45:18 +00001547 const APInt *XorC;
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001548 if (!match(Y, m_APInt(XorC)))
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001549 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001550
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001551 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1552 // fold the xor.
1553 ICmpInst::Predicate Pred = Cmp.getPredicate();
1554 if ((Pred == ICmpInst::ICMP_SLT && *C == 0) ||
1555 (Pred == ICmpInst::ICMP_SGT && C->isAllOnesValue())) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001556
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001557 // If the sign bit of the XorCst is not set, there is no change to
1558 // the operation, just stop using the Xor.
Sanjay Pateldaffec912016-08-17 19:45:18 +00001559 if (!XorC->isNegative()) {
1560 Cmp.setOperand(0, X);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001561 Worklist.Add(Xor);
1562 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001563 }
1564
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001565 // Was the old condition true if the operand is positive?
1566 bool isTrueIfPositive = Pred == ICmpInst::ICMP_SGT;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001567
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001568 // If so, the new one isn't.
1569 isTrueIfPositive ^= true;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001570
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001571 Constant *CmpConstant = cast<Constant>(Cmp.getOperand(1));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001572 if (isTrueIfPositive)
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001573 return new ICmpInst(ICmpInst::ICMP_SGT, X, SubOne(CmpConstant));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001574 else
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001575 return new ICmpInst(ICmpInst::ICMP_SLT, X, AddOne(CmpConstant));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001576 }
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001577
1578 if (Xor->hasOneUse()) {
Sanjay Pateldaffec912016-08-17 19:45:18 +00001579 // (icmp u/s (xor X SignBit), C) -> (icmp s/u X, (xor C SignBit))
1580 if (!Cmp.isEquality() && XorC->isSignBit()) {
1581 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1582 : Cmp.getSignedPredicate();
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001583 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001584 }
1585
Sanjay Pateldaffec912016-08-17 19:45:18 +00001586 // (icmp u/s (xor X ~SignBit), C) -> (icmp s/u X, (xor C ~SignBit))
1587 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1588 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1589 : Cmp.getSignedPredicate();
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001590 Pred = Cmp.getSwappedPredicate(Pred);
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001591 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001592 }
1593 }
1594
1595 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1596 // iff -C is a power of 2
Sanjay Pateldaffec912016-08-17 19:45:18 +00001597 if (Pred == ICmpInst::ICMP_UGT && *XorC == ~(*C) && (*C + 1).isPowerOf2())
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001598 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001599
1600 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1601 // iff -C is a power of 2
Sanjay Pateldaffec912016-08-17 19:45:18 +00001602 if (Pred == ICmpInst::ICMP_ULT && *XorC == -(*C) && C->isPowerOf2())
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001603 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001604
Sanjay Patela3f4f082016-08-16 17:54:36 +00001605 return nullptr;
1606}
1607
Sanjay Patel14e0e182016-08-26 18:28:46 +00001608/// Fold icmp (and (sh X, Y), C2), C1.
1609Instruction *InstCombiner::foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
Sanjay Patel9b40f982016-09-07 22:33:03 +00001610 const APInt *C1, const APInt *C2) {
1611 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1612 if (!Shift || !Shift->isShift())
Sanjay Patelda9c5622016-08-26 17:15:22 +00001613 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001614
Sanjay Patelda9c5622016-08-26 17:15:22 +00001615 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1616 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1617 // code produced by the clang front-end, for bitfield access.
Sanjay Patelda9c5622016-08-26 17:15:22 +00001618 // This seemingly simple opportunity to fold away a shift turns out to be
1619 // rather complicated. See PR17827 for details.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001620 unsigned ShiftOpcode = Shift->getOpcode();
1621 bool IsShl = ShiftOpcode == Instruction::Shl;
1622 const APInt *C3;
1623 if (match(Shift->getOperand(1), m_APInt(C3))) {
Sanjay Patelda9c5622016-08-26 17:15:22 +00001624 bool CanFold = false;
Sanjay Patelda9c5622016-08-26 17:15:22 +00001625 if (ShiftOpcode == Instruction::AShr) {
1626 // There may be some constraints that make this possible, but nothing
1627 // simple has been discovered yet.
1628 CanFold = false;
1629 } else if (ShiftOpcode == Instruction::Shl) {
1630 // For a left shift, we can fold if the comparison is not signed. We can
1631 // also fold a signed comparison if the mask value and comparison value
1632 // are not negative. These constraints may not be obvious, but we can
1633 // prove that they are correct using an SMT solver.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001634 if (!Cmp.isSigned() || (!C2->isNegative() && !C1->isNegative()))
Sanjay Patelda9c5622016-08-26 17:15:22 +00001635 CanFold = true;
1636 } else if (ShiftOpcode == Instruction::LShr) {
1637 // For a logical right shift, we can fold if the comparison is not signed.
1638 // We can also fold a signed comparison if the shifted mask value and the
1639 // shifted comparison value are not negative. These constraints may not be
1640 // obvious, but we can prove that they are correct using an SMT solver.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001641 if (!Cmp.isSigned() ||
1642 (!C2->shl(*C3).isNegative() && !C1->shl(*C3).isNegative()))
Sanjay Patelda9c5622016-08-26 17:15:22 +00001643 CanFold = true;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001644 }
1645
Sanjay Patelda9c5622016-08-26 17:15:22 +00001646 if (CanFold) {
Sanjay Patel9b40f982016-09-07 22:33:03 +00001647 APInt NewCst = IsShl ? C1->lshr(*C3) : C1->shl(*C3);
1648 APInt SameAsC1 = IsShl ? NewCst.shl(*C3) : NewCst.lshr(*C3);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001649 // Check to see if we are shifting out any of the bits being compared.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001650 if (SameAsC1 != *C1) {
Sanjay Patelda9c5622016-08-26 17:15:22 +00001651 // If we shifted bits out, the fold is not going to work out. As a
1652 // special case, check to see if this means that the result is always
1653 // true or false now.
1654 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
Sanjay Patel1c608f42016-09-08 16:54:02 +00001655 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
Sanjay Patelda9c5622016-08-26 17:15:22 +00001656 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
Sanjay Patel1c608f42016-09-08 16:54:02 +00001657 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001658 } else {
Sanjay Patel9b40f982016-09-07 22:33:03 +00001659 Cmp.setOperand(1, ConstantInt::get(And->getType(), NewCst));
1660 APInt NewAndCst = IsShl ? C2->lshr(*C3) : C2->shl(*C3);
1661 And->setOperand(1, ConstantInt::get(And->getType(), NewAndCst));
Sanjay Patelda9c5622016-08-26 17:15:22 +00001662 And->setOperand(0, Shift->getOperand(0));
1663 Worklist.Add(Shift); // Shift is dead.
1664 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001665 }
Sanjay Patelda9c5622016-08-26 17:15:22 +00001666 }
1667 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001668
Sanjay Patelda9c5622016-08-26 17:15:22 +00001669 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1670 // preferable because it allows the C2 << Y expression to be hoisted out of a
1671 // loop if Y is invariant and X is not.
Sanjay Patel14e0e182016-08-26 18:28:46 +00001672 if (Shift->hasOneUse() && *C1 == 0 && Cmp.isEquality() &&
Sanjay Patelda9c5622016-08-26 17:15:22 +00001673 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1674 // Compute C2 << Y.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001675 Value *NewShift =
1676 IsShl ? Builder->CreateLShr(And->getOperand(1), Shift->getOperand(1))
1677 : Builder->CreateShl(And->getOperand(1), Shift->getOperand(1));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001678
Sanjay Patelda9c5622016-08-26 17:15:22 +00001679 // Compute X & (C2 << Y).
Sanjay Patel9b40f982016-09-07 22:33:03 +00001680 Value *NewAnd = Builder->CreateAnd(Shift->getOperand(0), NewShift);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001681 Cmp.setOperand(0, NewAnd);
1682 return &Cmp;
1683 }
1684
Sanjay Patel14e0e182016-08-26 18:28:46 +00001685 return nullptr;
1686}
1687
1688/// Fold icmp (and X, C2), C1.
1689Instruction *InstCombiner::foldICmpAndConstConst(ICmpInst &Cmp,
1690 BinaryOperator *And,
1691 const APInt *C1) {
Sanjay Patel6b490972016-09-04 14:32:15 +00001692 const APInt *C2;
1693 if (!match(And->getOperand(1), m_APInt(C2)))
Sanjay Patel14e0e182016-08-26 18:28:46 +00001694 return nullptr;
1695
1696 if (!And->hasOneUse() || !And->getOperand(0)->hasOneUse())
1697 return nullptr;
1698
Sanjay Patel6b490972016-09-04 14:32:15 +00001699 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1700 // the input width without changing the value produced, eliminate the cast:
1701 //
1702 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1703 //
1704 // We can do this transformation if the constants do not have their sign bits
1705 // set or if it is an equality comparison. Extending a relational comparison
1706 // when we're checking the sign bit would not work.
1707 Value *W;
1708 if (match(And->getOperand(0), m_Trunc(m_Value(W))) &&
1709 (Cmp.isEquality() || (!C1->isNegative() && !C2->isNegative()))) {
1710 // TODO: Is this a good transform for vectors? Wider types may reduce
1711 // throughput. Should this transform be limited (even for scalars) by using
1712 // ShouldChangeType()?
1713 if (!Cmp.getType()->isVectorTy()) {
1714 Type *WideType = W->getType();
1715 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1716 Constant *ZextC1 = ConstantInt::get(WideType, C1->zext(WideScalarBits));
1717 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1718 Value *NewAnd = Builder->CreateAnd(W, ZextC2, And->getName());
1719 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
Sanjay Patel14e0e182016-08-26 18:28:46 +00001720 }
1721 }
1722
Sanjay Patel9b40f982016-09-07 22:33:03 +00001723 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, C2))
Sanjay Patel14e0e182016-08-26 18:28:46 +00001724 return I;
1725
Sanjay Patelda9c5622016-08-26 17:15:22 +00001726 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
Sanjay Patel6b490972016-09-04 14:32:15 +00001727 // (icmp pred (and A, (or (shl 1, B), 1), 0))
Sanjay Patelda9c5622016-08-26 17:15:22 +00001728 //
1729 // iff pred isn't signed
Sanjay Pateldef931e2016-09-07 20:50:44 +00001730 if (!Cmp.isSigned() && *C1 == 0 && match(And->getOperand(1), m_One())) {
1731 Constant *One = cast<Constant>(And->getOperand(1));
1732 Value *Or = And->getOperand(0);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001733 Value *A, *B, *LShr;
Sanjay Pateldef931e2016-09-07 20:50:44 +00001734 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1735 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1736 unsigned UsesRemoved = 0;
1737 if (And->hasOneUse())
1738 ++UsesRemoved;
1739 if (Or->hasOneUse())
1740 ++UsesRemoved;
1741 if (LShr->hasOneUse())
1742 ++UsesRemoved;
1743
1744 // Compute A & ((1 << B) | 1)
1745 Value *NewOr = nullptr;
1746 if (auto *C = dyn_cast<Constant>(B)) {
1747 if (UsesRemoved >= 1)
1748 NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1749 } else {
1750 if (UsesRemoved >= 3)
1751 NewOr = Builder->CreateOr(Builder->CreateShl(One, B, LShr->getName(),
Sanjay Patelda9c5622016-08-26 17:15:22 +00001752 /*HasNUW=*/true),
1753 One, Or->getName());
Sanjay Pateldef931e2016-09-07 20:50:44 +00001754 }
1755 if (NewOr) {
1756 Value *NewAnd = Builder->CreateAnd(A, NewOr, And->getName());
1757 Cmp.setOperand(0, NewAnd);
1758 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001759 }
1760 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001761 }
Sanjay Patelda9c5622016-08-26 17:15:22 +00001762
Sanjay Pateldef931e2016-09-07 20:50:44 +00001763 // (X & C2) > C1 --> (X & C2) != 0, if any bit set in (X & C2) will produce a
1764 // result greater than C1.
1765 unsigned NumTZ = C2->countTrailingZeros();
1766 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && NumTZ < C2->getBitWidth() &&
1767 APInt::getOneBitSet(C2->getBitWidth(), NumTZ).ugt(*C1)) {
1768 Constant *Zero = Constant::getNullValue(And->getType());
1769 return new ICmpInst(ICmpInst::ICMP_NE, And, Zero);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001770 }
1771
Sanjay Pateld3c7bb282016-08-26 16:42:33 +00001772 return nullptr;
1773}
1774
1775/// Fold icmp (and X, Y), C.
1776Instruction *InstCombiner::foldICmpAndConstant(ICmpInst &Cmp,
1777 BinaryOperator *And,
1778 const APInt *C) {
1779 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1780 return I;
1781
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001782 // TODO: These all require that Y is constant too, so refactor with the above.
Sanjay Patela3f4f082016-08-16 17:54:36 +00001783
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001784 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1785 Value *X = And->getOperand(0);
1786 Value *Y = And->getOperand(1);
1787 if (auto *LI = dyn_cast<LoadInst>(X))
1788 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1789 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001790 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001791 !LI->isVolatile() && isa<ConstantInt>(Y)) {
1792 ConstantInt *C2 = cast<ConstantInt>(Y);
1793 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C2))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001794 return Res;
1795 }
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001796
1797 if (!Cmp.isEquality())
1798 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001799
1800 // X & -C == -C -> X > u ~C
1801 // X & -C != -C -> X <= u ~C
1802 // iff C is a power of 2
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001803 if (Cmp.getOperand(1) == Y && (-(*C)).isPowerOf2()) {
1804 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT
1805 : CmpInst::ICMP_ULE;
1806 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1807 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001808
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001809 // (X & C2) == 0 -> (trunc X) >= 0
1810 // (X & C2) != 0 -> (trunc X) < 0
1811 // iff C2 is a power of 2 and it masks the sign bit of a legal integer type.
1812 const APInt *C2;
1813 if (And->hasOneUse() && *C == 0 && match(Y, m_APInt(C2))) {
1814 int32_t ExactLogBase2 = C2->exactLogBase2();
1815 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1816 Type *NTy = IntegerType::get(Cmp.getContext(), ExactLogBase2 + 1);
1817 if (And->getType()->isVectorTy())
1818 NTy = VectorType::get(NTy, And->getType()->getVectorNumElements());
1819 Value *Trunc = Builder->CreateTrunc(X, NTy);
1820 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_SGE
1821 : CmpInst::ICMP_SLT;
1822 return new ICmpInst(NewPred, Trunc, Constant::getNullValue(NTy));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001823 }
1824 }
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001825
Sanjay Patela3f4f082016-08-16 17:54:36 +00001826 return nullptr;
1827}
1828
Sanjay Patel943e92e2016-08-17 16:30:43 +00001829/// Fold icmp (or X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001830Instruction *InstCombiner::foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
Sanjay Patel943e92e2016-08-17 16:30:43 +00001831 const APInt *C) {
Sanjay Patel943e92e2016-08-17 16:30:43 +00001832 ICmpInst::Predicate Pred = Cmp.getPredicate();
1833 if (*C == 1) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001834 // icmp slt signum(V) 1 --> icmp slt V, 1
1835 Value *V = nullptr;
Sanjay Patel943e92e2016-08-17 16:30:43 +00001836 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001837 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1838 ConstantInt::get(V->getType(), 1));
1839 }
1840
Sanjay Patel943e92e2016-08-17 16:30:43 +00001841 if (!Cmp.isEquality() || *C != 0 || !Or->hasOneUse())
Sanjay Patela3f4f082016-08-16 17:54:36 +00001842 return nullptr;
1843
1844 Value *P, *Q;
Sanjay Patel943e92e2016-08-17 16:30:43 +00001845 if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001846 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1847 // -> and (icmp eq P, null), (icmp eq Q, null).
Reid Klecknera871d382016-08-19 16:53:18 +00001848 Value *CmpP =
1849 Builder->CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
1850 Value *CmpQ =
1851 Builder->CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
Sanjay Patel943e92e2016-08-17 16:30:43 +00001852 auto LogicOpc = Pred == ICmpInst::Predicate::ICMP_EQ ? Instruction::And
1853 : Instruction::Or;
1854 return BinaryOperator::Create(LogicOpc, CmpP, CmpQ);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001855 }
Sanjay Patel943e92e2016-08-17 16:30:43 +00001856
Sanjay Patela3f4f082016-08-16 17:54:36 +00001857 return nullptr;
1858}
1859
Sanjay Patel63478072016-08-18 15:44:44 +00001860/// Fold icmp (mul X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001861Instruction *InstCombiner::foldICmpMulConstant(ICmpInst &Cmp,
1862 BinaryOperator *Mul,
Sanjay Patel63478072016-08-18 15:44:44 +00001863 const APInt *C) {
1864 const APInt *MulC;
1865 if (!match(Mul->getOperand(1), m_APInt(MulC)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001866 return nullptr;
1867
Sanjay Patel63478072016-08-18 15:44:44 +00001868 // If this is a test of the sign bit and the multiply is sign-preserving with
1869 // a constant operand, use the multiply LHS operand instead.
1870 ICmpInst::Predicate Pred = Cmp.getPredicate();
Sanjay Patelc9196c42016-08-22 21:24:29 +00001871 if (isSignTest(Pred, *C) && Mul->hasNoSignedWrap()) {
Sanjay Patel63478072016-08-18 15:44:44 +00001872 if (MulC->isNegative())
1873 Pred = ICmpInst::getSwappedPredicate(Pred);
1874 return new ICmpInst(Pred, Mul->getOperand(0),
1875 Constant::getNullValue(Mul->getType()));
1876 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001877
1878 return nullptr;
1879}
1880
Sanjay Patel98cd99d2016-08-18 21:28:30 +00001881/// Fold icmp (shl 1, Y), C.
1882static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl,
1883 const APInt *C) {
1884 Value *Y;
1885 if (!match(Shl, m_Shl(m_One(), m_Value(Y))))
1886 return nullptr;
1887
1888 Type *ShiftType = Shl->getType();
1889 uint32_t TypeBits = C->getBitWidth();
1890 bool CIsPowerOf2 = C->isPowerOf2();
1891 ICmpInst::Predicate Pred = Cmp.getPredicate();
1892 if (Cmp.isUnsigned()) {
1893 // (1 << Y) pred C -> Y pred Log2(C)
1894 if (!CIsPowerOf2) {
1895 // (1 << Y) < 30 -> Y <= 4
1896 // (1 << Y) <= 30 -> Y <= 4
1897 // (1 << Y) >= 30 -> Y > 4
1898 // (1 << Y) > 30 -> Y > 4
1899 if (Pred == ICmpInst::ICMP_ULT)
1900 Pred = ICmpInst::ICMP_ULE;
1901 else if (Pred == ICmpInst::ICMP_UGE)
1902 Pred = ICmpInst::ICMP_UGT;
1903 }
1904
1905 // (1 << Y) >= 2147483648 -> Y >= 31 -> Y == 31
1906 // (1 << Y) < 2147483648 -> Y < 31 -> Y != 31
1907 unsigned CLog2 = C->logBase2();
1908 if (CLog2 == TypeBits - 1) {
1909 if (Pred == ICmpInst::ICMP_UGE)
1910 Pred = ICmpInst::ICMP_EQ;
1911 else if (Pred == ICmpInst::ICMP_ULT)
1912 Pred = ICmpInst::ICMP_NE;
1913 }
1914 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
1915 } else if (Cmp.isSigned()) {
1916 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
1917 if (C->isAllOnesValue()) {
1918 // (1 << Y) <= -1 -> Y == 31
1919 if (Pred == ICmpInst::ICMP_SLE)
1920 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
1921
1922 // (1 << Y) > -1 -> Y != 31
1923 if (Pred == ICmpInst::ICMP_SGT)
1924 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
1925 } else if (!(*C)) {
1926 // (1 << Y) < 0 -> Y == 31
1927 // (1 << Y) <= 0 -> Y == 31
1928 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1929 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
1930
1931 // (1 << Y) >= 0 -> Y != 31
1932 // (1 << Y) > 0 -> Y != 31
1933 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1934 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
1935 }
1936 } else if (Cmp.isEquality() && CIsPowerOf2) {
1937 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, C->logBase2()));
1938 }
1939
1940 return nullptr;
1941}
1942
Sanjay Patel38b75062016-08-19 17:20:37 +00001943/// Fold icmp (shl X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001944Instruction *InstCombiner::foldICmpShlConstant(ICmpInst &Cmp,
1945 BinaryOperator *Shl,
Sanjay Patel38b75062016-08-19 17:20:37 +00001946 const APInt *C) {
Sanjay Patelfa7de602016-08-19 22:33:26 +00001947 const APInt *ShiftAmt;
1948 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
Sanjay Patel38b75062016-08-19 17:20:37 +00001949 return foldICmpShlOne(Cmp, Shl, C);
Sanjay Patela867afe2016-08-19 16:12:16 +00001950
Sanjay Patel38b75062016-08-19 17:20:37 +00001951 // Check that the shift amount is in range. If not, don't perform undefined
1952 // shifts. When the shift is visited it will be simplified.
1953 unsigned TypeBits = C->getBitWidth();
Sanjay Patelfa7de602016-08-19 22:33:26 +00001954 if (ShiftAmt->uge(TypeBits))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001955 return nullptr;
1956
Sanjay Patele38e79c2016-08-19 17:34:05 +00001957 ICmpInst::Predicate Pred = Cmp.getPredicate();
1958 Value *X = Shl->getOperand(0);
Sanjay Patel38b75062016-08-19 17:20:37 +00001959 if (Cmp.isEquality()) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001960 // If the shift is NUW, then it is just shifting out zeros, no need for an
1961 // AND.
Sanjay Patelfa7de602016-08-19 22:33:26 +00001962 Constant *LShrC = ConstantInt::get(Shl->getType(), C->lshr(*ShiftAmt));
Sanjay Patelc9196c42016-08-22 21:24:29 +00001963 if (Shl->hasNoUnsignedWrap())
Sanjay Patelfa7de602016-08-19 22:33:26 +00001964 return new ICmpInst(Pred, X, LShrC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001965
1966 // If the shift is NSW and we compare to 0, then it is just shifting out
1967 // sign bits, no need for an AND either.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001968 if (Shl->hasNoSignedWrap() && *C == 0)
Sanjay Patelfa7de602016-08-19 22:33:26 +00001969 return new ICmpInst(Pred, X, LShrC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001970
Sanjay Patel38b75062016-08-19 17:20:37 +00001971 if (Shl->hasOneUse()) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001972 // Otherwise strength reduce the shift into an and.
Sanjay Patelfa7de602016-08-19 22:33:26 +00001973 Constant *Mask = ConstantInt::get(Shl->getType(),
1974 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001975
Sanjay Patele38e79c2016-08-19 17:34:05 +00001976 Value *And = Builder->CreateAnd(X, Mask, Shl->getName() + ".mask");
Sanjay Patelfa7de602016-08-19 22:33:26 +00001977 return new ICmpInst(Pred, And, LShrC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001978 }
1979 }
1980
1981 // If this is a signed comparison to 0 and the shift is sign preserving,
Sanjay Patele38e79c2016-08-19 17:34:05 +00001982 // use the shift LHS operand instead; isSignTest may change 'Pred', so only
1983 // do that if we're sure to not continue on in this function.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001984 if (Shl->hasNoSignedWrap() && isSignTest(Pred, *C))
Sanjay Patel7e09f132016-08-21 16:28:22 +00001985 return new ICmpInst(Pred, X, Constant::getNullValue(X->getType()));
1986
Sanjay Patela3f4f082016-08-16 17:54:36 +00001987 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1988 bool TrueIfSigned = false;
Sanjay Patel79263662016-08-21 15:07:45 +00001989 if (Shl->hasOneUse() && isSignBitCheck(Pred, *C, TrueIfSigned)) {
Sanjay Patel7ffcde72016-08-21 16:35:34 +00001990 // (X << 31) <s 0 --> (X & 1) != 0
Sanjay Patela3f4f082016-08-16 17:54:36 +00001991 Constant *Mask = ConstantInt::get(
Sanjay Patele38e79c2016-08-19 17:34:05 +00001992 X->getType(),
Sanjay Patelfa7de602016-08-19 22:33:26 +00001993 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
Sanjay Patele38e79c2016-08-19 17:34:05 +00001994 Value *And = Builder->CreateAnd(X, Mask, Shl->getName() + ".mask");
Sanjay Patela3f4f082016-08-16 17:54:36 +00001995 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1996 And, Constant::getNullValue(And->getType()));
1997 }
1998
Sanjay Patel643d21a2016-08-21 17:10:07 +00001999 // Transform (icmp pred iM (shl iM %v, N), C)
2000 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2001 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2002 // This enables us to get rid of the shift in favor of a trunc which can be
Sanjay Patela3f4f082016-08-16 17:54:36 +00002003 // free on the target. It has the additional benefit of comparing to a
2004 // smaller constant, which will be target friendly.
Sanjay Patelfa7de602016-08-19 22:33:26 +00002005 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
Sanjay Patel38b75062016-08-19 17:20:37 +00002006 if (Shl->hasOneUse() && Amt != 0 && C->countTrailingZeros() >= Amt) {
Sanjay Patel643d21a2016-08-21 17:10:07 +00002007 Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt);
2008 if (X->getType()->isVectorTy())
2009 TruncTy = VectorType::get(TruncTy, X->getType()->getVectorNumElements());
2010 Constant *NewC =
2011 ConstantInt::get(TruncTy, C->ashr(*ShiftAmt).trunc(TypeBits - Amt));
2012 return new ICmpInst(Pred, Builder->CreateTrunc(X, TruncTy), NewC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00002013 }
2014
2015 return nullptr;
2016}
2017
Sanjay Patela3920492016-08-22 20:45:06 +00002018/// Fold icmp ({al}shr X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00002019Instruction *InstCombiner::foldICmpShrConstant(ICmpInst &Cmp,
2020 BinaryOperator *Shr,
2021 const APInt *C) {
Sanjay Patela3920492016-08-22 20:45:06 +00002022 // An exact shr only shifts out zero bits, so:
2023 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
Sanjay Pateld64e9882016-08-23 22:05:55 +00002024 Value *X = Shr->getOperand(0);
Sanjay Patelc9196c42016-08-22 21:24:29 +00002025 CmpInst::Predicate Pred = Cmp.getPredicate();
2026 if (Cmp.isEquality() && Shr->isExact() && Shr->hasOneUse() && *C == 0)
Sanjay Pateld64e9882016-08-23 22:05:55 +00002027 return new ICmpInst(Pred, X, Cmp.getOperand(1));
Sanjay Patela3920492016-08-22 20:45:06 +00002028
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002029 const APInt *ShiftAmt;
2030 if (!match(Shr->getOperand(1), m_APInt(ShiftAmt)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00002031 return nullptr;
2032
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002033 // Check that the shift amount is in range. If not, don't perform undefined
2034 // shifts. When the shift is visited it will be simplified.
2035 unsigned TypeBits = C->getBitWidth();
2036 unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002037 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2038 return nullptr;
2039
Sanjay Pateld64e9882016-08-23 22:05:55 +00002040 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002041 if (!Cmp.isEquality()) {
2042 // If we have an unsigned comparison and an ashr, we can't simplify this.
2043 // Similarly for signed comparisons with lshr.
Sanjay Pateld64e9882016-08-23 22:05:55 +00002044 if (Cmp.isSigned() != IsAShr)
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002045 return nullptr;
2046
2047 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
2048 // by a power of 2. Since we already have logic to simplify these,
2049 // transform to div and then simplify the resultant comparison.
Sanjay Pateld64e9882016-08-23 22:05:55 +00002050 if (IsAShr && (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002051 return nullptr;
2052
2053 // Revisit the shift (to delete it).
2054 Worklist.Add(Shr);
2055
2056 Constant *DivCst = ConstantInt::get(
2057 Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
2058
Sanjay Pateld64e9882016-08-23 22:05:55 +00002059 Value *Tmp = IsAShr ? Builder->CreateSDiv(X, DivCst, "", Shr->isExact())
2060 : Builder->CreateUDiv(X, DivCst, "", Shr->isExact());
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002061
2062 Cmp.setOperand(0, Tmp);
2063
2064 // If the builder folded the binop, just return it.
2065 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
2066 if (!TheDiv)
2067 return &Cmp;
2068
2069 // Otherwise, fold this div/compare.
2070 assert(TheDiv->getOpcode() == Instruction::SDiv ||
2071 TheDiv->getOpcode() == Instruction::UDiv);
2072
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002073 Instruction *Res = foldICmpDivConstant(Cmp, TheDiv, C);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002074 assert(Res && "This div/cst should have folded!");
Sanjay Patela3920492016-08-22 20:45:06 +00002075 return Res;
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002076 }
2077
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002078 // Handle equality comparisons of shift-by-constant.
2079
Sanjay Patel8e297742016-08-24 13:55:55 +00002080 // If the comparison constant changes with the shift, the comparison cannot
2081 // succeed (bits of the comparison constant cannot match the shifted value).
2082 // This should be known by InstSimplify and already be folded to true/false.
2083 assert(((IsAShr && C->shl(ShAmtVal).ashr(ShAmtVal) == *C) ||
2084 (!IsAShr && C->shl(ShAmtVal).lshr(ShAmtVal) == *C)) &&
2085 "Expected icmp+shr simplify did not occur.");
2086
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002087 // Check if the bits shifted out are known to be zero. If so, we can compare
2088 // against the unshifted value:
2089 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002090 Constant *ShiftedCmpRHS = ConstantInt::get(Shr->getType(), *C << ShAmtVal);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002091 if (Shr->hasOneUse()) {
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002092 if (Shr->isExact())
2093 return new ICmpInst(Pred, X, ShiftedCmpRHS);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002094
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002095 // Otherwise strength reduce the shift into an 'and'.
2096 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2097 Constant *Mask = ConstantInt::get(Shr->getType(), Val);
Sanjay Pateld64e9882016-08-23 22:05:55 +00002098 Value *And = Builder->CreateAnd(X, Mask, Shr->getName() + ".mask");
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002099 return new ICmpInst(Pred, And, ShiftedCmpRHS);
2100 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002101
2102 return nullptr;
2103}
2104
Sanjay Patel12a41052016-08-18 17:37:26 +00002105/// Fold icmp (udiv X, Y), C.
2106Instruction *InstCombiner::foldICmpUDivConstant(ICmpInst &Cmp,
Sanjay Patelc9196c42016-08-22 21:24:29 +00002107 BinaryOperator *UDiv,
Sanjay Patel12a41052016-08-18 17:37:26 +00002108 const APInt *C) {
Sanjay Patelfa5ca2b2016-08-18 17:55:59 +00002109 const APInt *C2;
2110 if (!match(UDiv->getOperand(0), m_APInt(C2)))
2111 return nullptr;
2112
2113 assert(C2 != 0 && "udiv 0, X should have been simplified already.");
2114
2115 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2116 Value *Y = UDiv->getOperand(1);
2117 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT) {
2118 assert(!C->isMaxValue() &&
2119 "icmp ugt X, UINT_MAX should have been simplified already.");
2120 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2121 ConstantInt::get(Y->getType(), C2->udiv(*C + 1)));
2122 }
2123
2124 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2125 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT) {
2126 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2127 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2128 ConstantInt::get(Y->getType(), C2->udiv(*C)));
Sanjay Patela3f4f082016-08-16 17:54:36 +00002129 }
2130
2131 return nullptr;
2132}
2133
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002134/// Fold icmp ({su}div X, Y), C.
2135Instruction *InstCombiner::foldICmpDivConstant(ICmpInst &Cmp,
2136 BinaryOperator *Div,
2137 const APInt *C) {
Sanjay Patela7cb4772016-08-30 17:10:49 +00002138 // Fold: icmp pred ([us]div X, C2), C -> range test
Sanjay Patela3f4f082016-08-16 17:54:36 +00002139 // Fold this div into the comparison, producing a range check.
2140 // Determine, based on the divide type, what the range is being
2141 // checked. If there is an overflow on the low or high side, remember
2142 // it, otherwise compute the range [low, hi) bounding the new value.
2143 // See: InsertRangeTest above for the kinds of replacements possible.
Sanjay Patela7cb4772016-08-30 17:10:49 +00002144 const APInt *C2;
2145 if (!match(Div->getOperand(1), m_APInt(C2)))
Sanjay Patel16554142016-08-24 23:03:36 +00002146 return nullptr;
2147
Sanjay Patel16554142016-08-24 23:03:36 +00002148 // FIXME: If the operand types don't match the type of the divide
2149 // then don't attempt this transform. The code below doesn't have the
2150 // logic to deal with a signed divide and an unsigned compare (and
Sanjay Patela7cb4772016-08-30 17:10:49 +00002151 // vice versa). This is because (x /s C2) <s C produces different
2152 // results than (x /s C2) <u C or (x /u C2) <s C or even
2153 // (x /u C2) <u C. Simply casting the operands and result won't
Sanjay Patel16554142016-08-24 23:03:36 +00002154 // work. :( The if statement below tests that condition and bails
2155 // if it finds it.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002156 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2157 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
Sanjay Patel16554142016-08-24 23:03:36 +00002158 return nullptr;
Sanjay Patela7cb4772016-08-30 17:10:49 +00002159
Sanjay Pateleea2ef72016-09-05 23:38:22 +00002160 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2161 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2162 // division-by-constant cases should be present, we can not assert that they
2163 // have happened before we reach this icmp instruction.
2164 if (*C2 == 0 || *C2 == 1 || (DivIsSigned && C2->isAllOnesValue()))
2165 return nullptr;
Sanjay Patelb3714572016-08-30 17:31:34 +00002166
Sanjay Patel541aef42016-08-31 21:57:21 +00002167 // TODO: We could do all of the computations below using APInt.
2168 Constant *CmpRHS = cast<Constant>(Cmp.getOperand(1));
2169 Constant *DivRHS = cast<Constant>(Div->getOperand(1));
Sanjay Patelb3714572016-08-30 17:31:34 +00002170
Sanjay Patel541aef42016-08-31 21:57:21 +00002171 // Compute Prod = CmpRHS * DivRHS. We are essentially solving an equation of
2172 // form X / C2 = C. We solve for X by multiplying C2 (DivRHS) and C (CmpRHS).
2173 // By solving for X, we can turn this into a range check instead of computing
2174 // a divide.
2175 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Sanjay Patel16554142016-08-24 23:03:36 +00002176
Sanjay Patel541aef42016-08-31 21:57:21 +00002177 // Determine if the product overflows by seeing if the product is not equal to
2178 // the divide. Make sure we do the same kind of divide as in the LHS
2179 // instruction that we're folding.
2180 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS)
2181 : ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Sanjay Patel16554142016-08-24 23:03:36 +00002182
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002183 ICmpInst::Predicate Pred = Cmp.getPredicate();
Sanjay Patel16554142016-08-24 23:03:36 +00002184
2185 // If the division is known to be exact, then there is no remainder from the
2186 // divide, so the covered range size is unit, otherwise it is the divisor.
Sanjay Patel541aef42016-08-31 21:57:21 +00002187 Constant *RangeSize =
2188 Div->isExact() ? ConstantInt::get(Div->getType(), 1) : DivRHS;
Sanjay Patel16554142016-08-24 23:03:36 +00002189
2190 // Figure out the interval that is being checked. For example, a comparison
2191 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2192 // Compute this interval based on the constants involved and the signedness of
2193 // the compare/divide. This computes a half-open interval, keeping track of
2194 // whether either value in the interval overflows. After analysis each
2195 // overflow variable is set to 0 if it's corresponding bound variable is valid
2196 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2197 int LoOverflow = 0, HiOverflow = 0;
2198 Constant *LoBound = nullptr, *HiBound = nullptr;
2199
2200 if (!DivIsSigned) { // udiv
2201 // e.g. X/5 op 3 --> [15, 20)
2202 LoBound = Prod;
2203 HiOverflow = LoOverflow = ProdOV;
2204 if (!HiOverflow) {
2205 // If this is not an exact divide, then many values in the range collapse
2206 // to the same result value.
2207 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
2208 }
Sanjay Patel541aef42016-08-31 21:57:21 +00002209 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002210 if (*C == 0) { // (X / pos) op 0
Sanjay Patel16554142016-08-24 23:03:36 +00002211 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2212 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
2213 HiBound = RangeSize;
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002214 } else if (C->isStrictlyPositive()) { // (X / pos) op pos
Sanjay Patel16554142016-08-24 23:03:36 +00002215 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2216 HiOverflow = LoOverflow = ProdOV;
2217 if (!HiOverflow)
2218 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
2219 } else { // (X / pos) op neg
2220 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2221 HiBound = AddOne(Prod);
2222 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2223 if (!LoOverflow) {
Sanjay Patel541aef42016-08-31 21:57:21 +00002224 Constant *DivNeg = ConstantExpr::getNeg(RangeSize);
Sanjay Patel16554142016-08-24 23:03:36 +00002225 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2226 }
2227 }
Sanjay Patel541aef42016-08-31 21:57:21 +00002228 } else if (C2->isNegative()) { // Divisor is < 0.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002229 if (Div->isExact())
Sanjay Patel541aef42016-08-31 21:57:21 +00002230 RangeSize = ConstantExpr::getNeg(RangeSize);
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002231 if (*C == 0) { // (X / neg) op 0
Sanjay Patel16554142016-08-24 23:03:36 +00002232 // e.g. X/-5 op 0 --> [-4, 5)
2233 LoBound = AddOne(RangeSize);
Sanjay Patel541aef42016-08-31 21:57:21 +00002234 HiBound = ConstantExpr::getNeg(RangeSize);
Sanjay Patel16554142016-08-24 23:03:36 +00002235 if (HiBound == DivRHS) { // -INTMIN = INTMIN
2236 HiOverflow = 1; // [INTMIN+1, overflow)
2237 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
2238 }
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002239 } else if (C->isStrictlyPositive()) { // (X / neg) op pos
Sanjay Patel16554142016-08-24 23:03:36 +00002240 // e.g. X/-5 op 3 --> [-19, -14)
2241 HiBound = AddOne(Prod);
2242 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2243 if (!LoOverflow)
2244 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
2245 } else { // (X / neg) op neg
2246 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2247 LoOverflow = HiOverflow = ProdOV;
2248 if (!HiOverflow)
2249 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
2250 }
2251
2252 // Dividing by a negative swaps the condition. LT <-> GT
2253 Pred = ICmpInst::getSwappedPredicate(Pred);
2254 }
2255
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002256 Value *X = Div->getOperand(0);
Sanjay Patel16554142016-08-24 23:03:36 +00002257 switch (Pred) {
2258 default: llvm_unreachable("Unhandled icmp opcode!");
2259 case ICmpInst::ICMP_EQ:
2260 if (LoOverflow && HiOverflow)
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002261 return replaceInstUsesWith(Cmp, Builder->getFalse());
Sanjay Patel16554142016-08-24 23:03:36 +00002262 if (HiOverflow)
2263 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2264 ICmpInst::ICMP_UGE, X, LoBound);
2265 if (LoOverflow)
2266 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2267 ICmpInst::ICMP_ULT, X, HiBound);
Sanjay Patel85d79742016-08-31 19:49:56 +00002268 return replaceInstUsesWith(
Sanjay Patel541aef42016-08-31 21:57:21 +00002269 Cmp, insertRangeTest(X, LoBound->getUniqueInteger(),
2270 HiBound->getUniqueInteger(), DivIsSigned, true));
Sanjay Patel16554142016-08-24 23:03:36 +00002271 case ICmpInst::ICMP_NE:
2272 if (LoOverflow && HiOverflow)
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002273 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel16554142016-08-24 23:03:36 +00002274 if (HiOverflow)
2275 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2276 ICmpInst::ICMP_ULT, X, LoBound);
2277 if (LoOverflow)
2278 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2279 ICmpInst::ICMP_UGE, X, HiBound);
Sanjay Patel541aef42016-08-31 21:57:21 +00002280 return replaceInstUsesWith(Cmp,
2281 insertRangeTest(X, LoBound->getUniqueInteger(),
2282 HiBound->getUniqueInteger(),
2283 DivIsSigned, false));
Sanjay Patel16554142016-08-24 23:03:36 +00002284 case ICmpInst::ICMP_ULT:
2285 case ICmpInst::ICMP_SLT:
2286 if (LoOverflow == +1) // Low bound is greater than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002287 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel16554142016-08-24 23:03:36 +00002288 if (LoOverflow == -1) // Low bound is less than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002289 return replaceInstUsesWith(Cmp, Builder->getFalse());
Sanjay Patel16554142016-08-24 23:03:36 +00002290 return new ICmpInst(Pred, X, LoBound);
2291 case ICmpInst::ICMP_UGT:
2292 case ICmpInst::ICMP_SGT:
2293 if (HiOverflow == +1) // High bound greater than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002294 return replaceInstUsesWith(Cmp, Builder->getFalse());
Sanjay Patel16554142016-08-24 23:03:36 +00002295 if (HiOverflow == -1) // High bound less than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002296 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel16554142016-08-24 23:03:36 +00002297 if (Pred == ICmpInst::ICMP_UGT)
2298 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
2299 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
2300 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002301
2302 return nullptr;
2303}
2304
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002305/// Fold icmp (sub X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00002306Instruction *InstCombiner::foldICmpSubConstant(ICmpInst &Cmp,
2307 BinaryOperator *Sub,
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002308 const APInt *C) {
Sanjay Patele47df1a2016-08-16 21:53:19 +00002309 const APInt *C2;
2310 if (!match(Sub->getOperand(0), m_APInt(C2)) || !Sub->hasOneUse())
Sanjay Patela3f4f082016-08-16 17:54:36 +00002311 return nullptr;
2312
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002313 // C-X <u C2 -> (X|(C2-1)) == C
2314 // iff C & (C2-1) == C2-1
Sanjay Patela3f4f082016-08-16 17:54:36 +00002315 // C2 is a power of 2
Sanjay Patele47df1a2016-08-16 21:53:19 +00002316 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && C->isPowerOf2() &&
2317 (*C2 & (*C - 1)) == (*C - 1))
Sanjay Patela3f4f082016-08-16 17:54:36 +00002318 return new ICmpInst(ICmpInst::ICMP_EQ,
Sanjay Patele47df1a2016-08-16 21:53:19 +00002319 Builder->CreateOr(Sub->getOperand(1), *C - 1),
2320 Sub->getOperand(0));
Sanjay Patela3f4f082016-08-16 17:54:36 +00002321
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002322 // C-X >u C2 -> (X|C2) != C
2323 // iff C & C2 == C2
Sanjay Patela3f4f082016-08-16 17:54:36 +00002324 // C2+1 is a power of 2
Sanjay Patele47df1a2016-08-16 21:53:19 +00002325 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() &&
2326 (*C2 & *C) == *C)
Sanjay Patela3f4f082016-08-16 17:54:36 +00002327 return new ICmpInst(ICmpInst::ICMP_NE,
Sanjay Patele47df1a2016-08-16 21:53:19 +00002328 Builder->CreateOr(Sub->getOperand(1), *C),
2329 Sub->getOperand(0));
Sanjay Patela3f4f082016-08-16 17:54:36 +00002330
2331 return nullptr;
2332}
2333
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002334/// Fold icmp (add X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00002335Instruction *InstCombiner::foldICmpAddConstant(ICmpInst &Cmp,
2336 BinaryOperator *Add,
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002337 const APInt *C) {
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002338 Value *Y = Add->getOperand(1);
2339 const APInt *C2;
2340 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00002341 return nullptr;
2342
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002343 // Fold icmp pred (add X, C2), C.
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002344 Value *X = Add->getOperand(0);
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002345 Type *Ty = Add->getType();
2346 auto CR = Cmp.makeConstantRange(Cmp.getPredicate(), *C).subtract(*C2);
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002347 const APInt &Upper = CR.getUpper();
2348 const APInt &Lower = CR.getLower();
2349 if (Cmp.isSigned()) {
2350 if (Lower.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002351 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002352 if (Upper.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002353 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002354 } else {
2355 if (Lower.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002356 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002357 if (Upper.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002358 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002359 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002360
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002361 if (!Add->hasOneUse())
2362 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002363
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002364 // X+C <u C2 -> (X & -C2) == C
2365 // iff C & (C2-1) == 0
2366 // C2 is a power of 2
2367 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && C->isPowerOf2() &&
2368 (*C2 & (*C - 1)) == 0)
2369 return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateAnd(X, -(*C)),
2370 ConstantExpr::getNeg(cast<Constant>(Y)));
2371
2372 // X+C >u C2 -> (X & ~C2) != C
2373 // iff C & C2 == 0
2374 // C2+1 is a power of 2
2375 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() &&
2376 (*C2 & *C) == 0)
2377 return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateAnd(X, ~(*C)),
2378 ConstantExpr::getNeg(cast<Constant>(Y)));
2379
Sanjay Patela3f4f082016-08-16 17:54:36 +00002380 return nullptr;
2381}
2382
Sanjay Patelf58f68c2016-09-10 15:03:44 +00002383/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
2384/// where X is some kind of instruction.
2385Instruction *InstCombiner::foldICmpInstWithConstant(ICmpInst &Cmp) {
Sanjay Patelc9196c42016-08-22 21:24:29 +00002386 const APInt *C;
2387 if (!match(Cmp.getOperand(1), m_APInt(C)))
Sanjay Patel1e5b2d12016-08-16 16:08:11 +00002388 return nullptr;
2389
Sanjay Patelc9196c42016-08-22 21:24:29 +00002390 BinaryOperator *BO;
2391 if (match(Cmp.getOperand(0), m_BinOp(BO))) {
2392 switch (BO->getOpcode()) {
2393 case Instruction::Xor:
2394 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
2395 return I;
2396 break;
2397 case Instruction::And:
2398 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
2399 return I;
2400 break;
2401 case Instruction::Or:
2402 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
2403 return I;
2404 break;
2405 case Instruction::Mul:
2406 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
2407 return I;
2408 break;
2409 case Instruction::Shl:
2410 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
2411 return I;
2412 break;
2413 case Instruction::LShr:
2414 case Instruction::AShr:
2415 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
2416 return I;
2417 break;
2418 case Instruction::UDiv:
2419 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
2420 return I;
2421 LLVM_FALLTHROUGH;
2422 case Instruction::SDiv:
2423 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
2424 return I;
2425 break;
2426 case Instruction::Sub:
2427 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
2428 return I;
2429 break;
2430 case Instruction::Add:
2431 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
2432 return I;
2433 break;
2434 default:
2435 break;
2436 }
Sanjay Patelf58f68c2016-09-10 15:03:44 +00002437 // TODO: These folds could be refactored to be part of the above calls.
2438 if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, C))
2439 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002440 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002441
Sanjay Patelc9196c42016-08-22 21:24:29 +00002442 Instruction *LHSI;
2443 if (match(Cmp.getOperand(0), m_Instruction(LHSI)) &&
2444 LHSI->getOpcode() == Instruction::Trunc)
2445 if (Instruction *I = foldICmpTruncConstant(Cmp, LHSI, C))
2446 return I;
2447
Sanjay Patelf58f68c2016-09-10 15:03:44 +00002448 if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, C))
2449 return I;
2450
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002451 return nullptr;
2452}
Jim Grosbach129c52a2011-09-30 18:09:53 +00002453
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002454/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
2455/// icmp eq/ne BO, C.
2456Instruction *InstCombiner::foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
2457 BinaryOperator *BO,
2458 const APInt *C) {
2459 // TODO: Some of these folds could work with arbitrary constants, but this
2460 // function is limited to scalar and vector splat constants.
2461 if (!Cmp.isEquality())
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002462 return nullptr;
2463
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002464 ICmpInst::Predicate Pred = Cmp.getPredicate();
2465 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
2466 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
Sanjay Patel51a767c2016-08-03 17:23:08 +00002467 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002468
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002469 switch (BO->getOpcode()) {
2470 case Instruction::SRem:
2471 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002472 if (*C == 0 && BO->hasOneUse()) {
Sanjay Patel2e9675f2016-08-03 19:48:40 +00002473 const APInt *BOC;
2474 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002475 Value *NewRem = Builder->CreateURem(BOp0, BOp1, BO->getName());
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002476 return new ICmpInst(Pred, NewRem,
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002477 Constant::getNullValue(BO->getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002478 }
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002479 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002480 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002481 case Instruction::Add: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002482 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
Sanjay Patel00a324e2016-08-03 22:08:44 +00002483 const APInt *BOC;
2484 if (match(BOp1, m_APInt(BOC))) {
2485 if (BO->hasOneUse()) {
2486 Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1));
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002487 return new ICmpInst(Pred, BOp0, SubC);
Sanjay Patel00a324e2016-08-03 22:08:44 +00002488 }
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002489 } else if (*C == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002490 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2491 // efficiently invertible, or if the add has just this one use.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002492 if (Value *NegVal = dyn_castNegVal(BOp1))
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002493 return new ICmpInst(Pred, BOp0, NegVal);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002494 if (Value *NegVal = dyn_castNegVal(BOp0))
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002495 return new ICmpInst(Pred, NegVal, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002496 if (BO->hasOneUse()) {
2497 Value *Neg = Builder->CreateNeg(BOp1);
2498 Neg->takeName(BO);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002499 return new ICmpInst(Pred, BOp0, Neg);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002500 }
2501 }
2502 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002503 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002504 case Instruction::Xor:
2505 if (BO->hasOneUse()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002506 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002507 // For the xor case, we can xor two constants together, eliminating
2508 // the explicit xor.
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002509 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
2510 } else if (*C == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002511 // Replace ((xor A, B) != 0) with (A != B)
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002512 return new ICmpInst(Pred, BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002513 }
2514 }
2515 break;
2516 case Instruction::Sub:
2517 if (BO->hasOneUse()) {
Sanjay Patel9d591d12016-08-04 15:19:25 +00002518 const APInt *BOC;
2519 if (match(BOp0, m_APInt(BOC))) {
Sanjay Patel362ff5c2016-09-15 17:01:17 +00002520 // Replace ((sub BOC, B) != C) with (B != BOC-C).
Sanjay Patel9d591d12016-08-04 15:19:25 +00002521 Constant *SubC = ConstantExpr::getSub(cast<Constant>(BOp0), RHS);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002522 return new ICmpInst(Pred, BOp1, SubC);
2523 } else if (*C == 0) {
Sanjay Patel362ff5c2016-09-15 17:01:17 +00002524 // Replace ((sub A, B) != 0) with (A != B).
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002525 return new ICmpInst(Pred, BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002526 }
2527 }
2528 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002529 case Instruction::Or: {
2530 const APInt *BOC;
2531 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002532 // Comparing if all bits outside of a constant mask are set?
2533 // Replace (X | C) == -1 with (X & ~C) == ~C.
2534 // This removes the -1 constant.
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002535 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
2536 Value *And = Builder->CreateAnd(BOp0, NotBOC);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002537 return new ICmpInst(Pred, And, NotBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002538 }
2539 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002540 }
Sanjay Pateld938e882016-08-04 20:05:02 +00002541 case Instruction::And: {
2542 const APInt *BOC;
2543 if (match(BOp1, m_APInt(BOC))) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002544 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002545 if (C == BOC && C->isPowerOf2())
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002546 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
Sanjay Patelab50a932016-08-02 22:38:33 +00002547 BO, Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002548
2549 // Don't perform the following transforms if the AND has multiple uses
2550 if (!BO->hasOneUse())
2551 break;
2552
2553 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Sanjay Pateld938e882016-08-04 20:05:02 +00002554 if (BOC->isSignBit()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002555 Constant *Zero = Constant::getNullValue(BOp0->getType());
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002556 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
2557 return new ICmpInst(NewPred, BOp0, Zero);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002558 }
2559
2560 // ((X & ~7) == 0) --> X < 8
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002561 if (*C == 0 && (~(*BOC) + 1).isPowerOf2()) {
Sanjay Pateld938e882016-08-04 20:05:02 +00002562 Constant *NegBOC = ConstantExpr::getNeg(cast<Constant>(BOp1));
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002563 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
2564 return new ICmpInst(NewPred, BOp0, NegBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002565 }
2566 }
2567 break;
Sanjay Pateld938e882016-08-04 20:05:02 +00002568 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002569 case Instruction::Mul:
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002570 if (*C == 0 && BO->hasNoSignedWrap()) {
Sanjay Patel3bade132016-08-04 22:19:27 +00002571 const APInt *BOC;
2572 if (match(BOp1, m_APInt(BOC)) && *BOC != 0) {
2573 // The trivial case (mul X, 0) is handled by InstSimplify.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002574 // General case : (mul X, C) != 0 iff X != 0
2575 // (mul X, C) == 0 iff X == 0
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002576 return new ICmpInst(Pred, BOp0, Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002577 }
2578 }
2579 break;
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002580 case Instruction::UDiv:
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002581 if (*C == 0) {
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002582 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002583 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
2584 return new ICmpInst(NewPred, BOp1, BOp0);
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002585 }
2586 break;
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002587 default:
2588 break;
2589 }
2590 return nullptr;
2591}
2592
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002593/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
2594Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
2595 const APInt *C) {
2596 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0));
2597 if (!II || !Cmp.isEquality())
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002598 return nullptr;
2599
2600 // Handle icmp {eq|ne} <intrinsic>, intcst.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002601 switch (II->getIntrinsicID()) {
2602 case Intrinsic::bswap:
2603 Worklist.Add(II);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002604 Cmp.setOperand(0, II->getArgOperand(0));
2605 Cmp.setOperand(1, Builder->getInt(C->byteSwap()));
2606 return &Cmp;
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002607 case Intrinsic::ctlz:
2608 case Intrinsic::cttz:
Amaury Sechet6bea6742016-08-04 05:27:20 +00002609 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002610 if (*C == C->getBitWidth()) {
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002611 Worklist.Add(II);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002612 Cmp.setOperand(0, II->getArgOperand(0));
2613 Cmp.setOperand(1, ConstantInt::getNullValue(II->getType()));
2614 return &Cmp;
Chris Lattner2188e402010-01-04 07:37:31 +00002615 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002616 break;
Amaury Sechet6bea6742016-08-04 05:27:20 +00002617 case Intrinsic::ctpop: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002618 // popcount(A) == 0 -> A == 0 and likewise for !=
Amaury Sechet6bea6742016-08-04 05:27:20 +00002619 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002620 bool IsZero = *C == 0;
2621 if (IsZero || *C == C->getBitWidth()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002622 Worklist.Add(II);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002623 Cmp.setOperand(0, II->getArgOperand(0));
2624 auto *NewOp = IsZero ? Constant::getNullValue(II->getType())
2625 : Constant::getAllOnesValue(II->getType());
2626 Cmp.setOperand(1, NewOp);
2627 return &Cmp;
Amaury Sechet6bea6742016-08-04 05:27:20 +00002628 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002629 break;
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002630 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002631 default:
2632 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002633 }
Craig Topperf40110f2014-04-25 05:29:35 +00002634 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002635}
2636
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002637/// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so
2638/// far.
Sanjay Patel43395062016-07-21 18:07:40 +00002639Instruction *InstCombiner::foldICmpWithCastAndCast(ICmpInst &ICmp) {
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002640 const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00002641 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002642 Type *SrcTy = LHSCIOp->getType();
2643 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002644 Value *RHSCIOp;
2645
Jim Grosbach129c52a2011-09-30 18:09:53 +00002646 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00002647 // integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002648 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
2649 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002650 Value *RHSOp = nullptr;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002651 if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
Michael Liaod266b922015-02-13 04:51:26 +00002652 Value *RHSCIOp = RHSC->getOperand(0);
2653 if (RHSCIOp->getType()->getPointerAddressSpace() ==
2654 LHSCIOp->getType()->getPointerAddressSpace()) {
2655 RHSOp = RHSC->getOperand(0);
2656 // If the pointer types don't match, insert a bitcast.
2657 if (LHSCIOp->getType() != RHSOp->getType())
2658 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
2659 }
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002660 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002661 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002662 }
Chris Lattner2188e402010-01-04 07:37:31 +00002663
2664 if (RHSOp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002665 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002666 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002667
Chris Lattner2188e402010-01-04 07:37:31 +00002668 // The code below only handles extension cast instructions, so far.
2669 // Enforce this.
2670 if (LHSCI->getOpcode() != Instruction::ZExt &&
2671 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002672 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002673
2674 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002675 bool isSignedCmp = ICmp.isSigned();
Chris Lattner2188e402010-01-04 07:37:31 +00002676
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002677 if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002678 // Not an extension from the same type?
2679 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002680 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00002681 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002682
Chris Lattner2188e402010-01-04 07:37:31 +00002683 // If the signedness of the two casts doesn't agree (i.e. one is a sext
2684 // and the other is a zext), then we can't handle this.
2685 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00002686 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002687
2688 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002689 if (ICmp.isEquality())
2690 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002691
2692 // A signed comparison of sign extended values simplifies into a
2693 // signed comparison.
2694 if (isSignedCmp && isSignedExt)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002695 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002696
2697 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002698 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002699 }
2700
Sanjay Patel4c204232016-06-04 20:39:22 +00002701 // If we aren't dealing with a constant on the RHS, exit early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002702 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
2703 if (!C)
Craig Topperf40110f2014-04-25 05:29:35 +00002704 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002705
2706 // Compute the constant that would happen if we truncated to SrcTy then
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002707 // re-extended to DestTy.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002708 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002709 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattner2188e402010-01-04 07:37:31 +00002710
2711 // If the re-extended constant didn't change...
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002712 if (Res2 == C) {
Chris Lattner2188e402010-01-04 07:37:31 +00002713 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002714 if (ICmp.isEquality())
2715 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002716
2717 // A signed comparison of sign extended values simplifies into a
2718 // signed comparison.
2719 if (isSignedExt && isSignedCmp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002720 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002721
2722 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002723 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002724 }
2725
Sanjay Patel6a333c32016-06-06 16:56:57 +00002726 // The re-extended constant changed, partly changed (in the case of a vector),
2727 // or could not be determined to be equal (in the case of a constant
2728 // expression), so the constant cannot be represented in the shorter type.
2729 // Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002730 // All the cases that fold to true or false will have already been handled
2731 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00002732
Sanjay Patel6a333c32016-06-06 16:56:57 +00002733 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
Craig Topperf40110f2014-04-25 05:29:35 +00002734 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002735
2736 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
2737 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002738
2739 // We're performing an unsigned comp with a sign extended value.
2740 // This is true if the input is >= 0. [aka >s -1]
2741 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002742 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00002743
2744 // Finally, return the value computed.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002745 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
2746 return replaceInstUsesWith(ICmp, Result);
Chris Lattner2188e402010-01-04 07:37:31 +00002747
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002748 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00002749 return BinaryOperator::CreateNot(Result);
2750}
2751
Sanjoy Dasb0984472015-04-08 04:27:22 +00002752bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
2753 Value *RHS, Instruction &OrigI,
2754 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00002755 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
2756 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002757
2758 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
2759 Result = OpResult;
2760 Overflow = OverflowVal;
2761 if (ReuseName)
2762 Result->takeName(&OrigI);
2763 return true;
2764 };
2765
Sanjoy Das6f5dca72015-08-28 19:09:31 +00002766 // If the overflow check was an add followed by a compare, the insertion point
2767 // may be pointing to the compare. We want to insert the new instructions
2768 // before the add in case there are uses of the add between the add and the
2769 // compare.
2770 Builder->SetInsertPoint(&OrigI);
2771
Sanjoy Dasb0984472015-04-08 04:27:22 +00002772 switch (OCF) {
2773 case OCF_INVALID:
2774 llvm_unreachable("bad overflow check kind!");
2775
2776 case OCF_UNSIGNED_ADD: {
2777 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
2778 if (OR == OverflowResult::NeverOverflows)
2779 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
2780 true);
2781
2782 if (OR == OverflowResult::AlwaysOverflows)
2783 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002784
2785 // Fall through uadd into sadd
2786 LLVM_FALLTHROUGH;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002787 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00002788 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002789 // X + 0 -> {X, false}
2790 if (match(RHS, m_Zero()))
2791 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002792
2793 // We can strength reduce this signed add into a regular add if we can prove
2794 // that it will never overflow.
2795 if (OCF == OCF_SIGNED_ADD)
2796 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
2797 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
2798 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00002799 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002800 }
2801
2802 case OCF_UNSIGNED_SUB:
2803 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002804 // X - 0 -> {X, false}
2805 if (match(RHS, m_Zero()))
2806 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002807
2808 if (OCF == OCF_SIGNED_SUB) {
2809 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
2810 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
2811 true);
2812 } else {
2813 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
2814 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
2815 true);
2816 }
2817 break;
2818 }
2819
2820 case OCF_UNSIGNED_MUL: {
2821 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
2822 if (OR == OverflowResult::NeverOverflows)
2823 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
2824 true);
2825 if (OR == OverflowResult::AlwaysOverflows)
2826 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002827 LLVM_FALLTHROUGH;
2828 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00002829 case OCF_SIGNED_MUL:
2830 // X * undef -> undef
2831 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00002832 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002833
David Majnemer27e89ba2015-05-21 23:04:21 +00002834 // X * 0 -> {0, false}
2835 if (match(RHS, m_Zero()))
2836 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002837
David Majnemer27e89ba2015-05-21 23:04:21 +00002838 // X * 1 -> {X, false}
2839 if (match(RHS, m_One()))
2840 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002841
2842 if (OCF == OCF_SIGNED_MUL)
2843 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
2844 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
2845 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00002846 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002847 }
2848
2849 return false;
2850}
2851
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002852/// \brief Recognize and process idiom involving test for multiplication
2853/// overflow.
2854///
2855/// The caller has matched a pattern of the form:
2856/// I = cmp u (mul(zext A, zext B), V
2857/// The function checks if this is a test for overflow and if so replaces
2858/// multiplication with call to 'mul.with.overflow' intrinsic.
2859///
2860/// \param I Compare instruction.
2861/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2862/// the compare instruction. Must be of integer type.
2863/// \param OtherVal The other argument of compare instruction.
2864/// \returns Instruction which must replace the compare instruction, NULL if no
2865/// replacement required.
2866static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2867 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00002868 // Don't bother doing this transformation for pointers, don't do it for
2869 // vectors.
2870 if (!isa<IntegerType>(MulVal->getType()))
2871 return nullptr;
2872
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002873 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2874 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00002875 auto *MulInstr = dyn_cast<Instruction>(MulVal);
2876 if (!MulInstr)
2877 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002878 assert(MulInstr->getOpcode() == Instruction::Mul);
2879
David Majnemer634ca232014-11-01 23:46:05 +00002880 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
2881 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002882 assert(LHS->getOpcode() == Instruction::ZExt);
2883 assert(RHS->getOpcode() == Instruction::ZExt);
2884 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2885
2886 // Calculate type and width of the result produced by mul.with.overflow.
2887 Type *TyA = A->getType(), *TyB = B->getType();
2888 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2889 WidthB = TyB->getPrimitiveSizeInBits();
2890 unsigned MulWidth;
2891 Type *MulType;
2892 if (WidthB > WidthA) {
2893 MulWidth = WidthB;
2894 MulType = TyB;
2895 } else {
2896 MulWidth = WidthA;
2897 MulType = TyA;
2898 }
2899
2900 // In order to replace the original mul with a narrower mul.with.overflow,
2901 // all uses must ignore upper bits of the product. The number of used low
2902 // bits must be not greater than the width of mul.with.overflow.
2903 if (MulVal->hasNUsesOrMore(2))
2904 for (User *U : MulVal->users()) {
2905 if (U == &I)
2906 continue;
2907 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2908 // Check if truncation ignores bits above MulWidth.
2909 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2910 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002911 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002912 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2913 // Check if AND ignores bits above MulWidth.
2914 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00002915 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002916 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2917 const APInt &CVal = CI->getValue();
2918 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002919 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002920 }
2921 } else {
2922 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00002923 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002924 }
2925 }
2926
2927 // Recognize patterns
2928 switch (I.getPredicate()) {
2929 case ICmpInst::ICMP_EQ:
2930 case ICmpInst::ICMP_NE:
2931 // Recognize pattern:
2932 // mulval = mul(zext A, zext B)
2933 // cmp eq/neq mulval, zext trunc mulval
2934 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2935 if (Zext->hasOneUse()) {
2936 Value *ZextArg = Zext->getOperand(0);
2937 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2938 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2939 break; //Recognized
2940 }
2941
2942 // Recognize pattern:
2943 // mulval = mul(zext A, zext B)
2944 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2945 ConstantInt *CI;
2946 Value *ValToMask;
2947 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2948 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00002949 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002950 const APInt &CVal = CI->getValue() + 1;
2951 if (CVal.isPowerOf2()) {
2952 unsigned MaskWidth = CVal.logBase2();
2953 if (MaskWidth == MulWidth)
2954 break; // Recognized
2955 }
2956 }
Craig Topperf40110f2014-04-25 05:29:35 +00002957 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002958
2959 case ICmpInst::ICMP_UGT:
2960 // Recognize pattern:
2961 // mulval = mul(zext A, zext B)
2962 // cmp ugt mulval, max
2963 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2964 APInt MaxVal = APInt::getMaxValue(MulWidth);
2965 MaxVal = MaxVal.zext(CI->getBitWidth());
2966 if (MaxVal.eq(CI->getValue()))
2967 break; // Recognized
2968 }
Craig Topperf40110f2014-04-25 05:29:35 +00002969 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002970
2971 case ICmpInst::ICMP_UGE:
2972 // Recognize pattern:
2973 // mulval = mul(zext A, zext B)
2974 // cmp uge mulval, max+1
2975 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2976 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2977 if (MaxVal.eq(CI->getValue()))
2978 break; // Recognized
2979 }
Craig Topperf40110f2014-04-25 05:29:35 +00002980 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002981
2982 case ICmpInst::ICMP_ULE:
2983 // Recognize pattern:
2984 // mulval = mul(zext A, zext B)
2985 // cmp ule mulval, max
2986 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2987 APInt MaxVal = APInt::getMaxValue(MulWidth);
2988 MaxVal = MaxVal.zext(CI->getBitWidth());
2989 if (MaxVal.eq(CI->getValue()))
2990 break; // Recognized
2991 }
Craig Topperf40110f2014-04-25 05:29:35 +00002992 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002993
2994 case ICmpInst::ICMP_ULT:
2995 // Recognize pattern:
2996 // mulval = mul(zext A, zext B)
2997 // cmp ule mulval, max + 1
2998 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002999 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003000 if (MaxVal.eq(CI->getValue()))
3001 break; // Recognized
3002 }
Craig Topperf40110f2014-04-25 05:29:35 +00003003 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003004
3005 default:
Craig Topperf40110f2014-04-25 05:29:35 +00003006 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003007 }
3008
3009 InstCombiner::BuilderTy *Builder = IC.Builder;
3010 Builder->SetInsertPoint(MulInstr);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003011
3012 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
3013 Value *MulA = A, *MulB = B;
3014 if (WidthA < MulWidth)
3015 MulA = Builder->CreateZExt(A, MulType);
3016 if (WidthB < MulWidth)
3017 MulB = Builder->CreateZExt(B, MulType);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00003018 Value *F = Intrinsic::getDeclaration(I.getModule(),
3019 Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00003020 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003021 IC.Worklist.Add(MulInstr);
3022
3023 // If there are uses of mul result other than the comparison, we know that
3024 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00003025 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003026 if (MulVal->hasNUsesOrMore(2)) {
3027 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
3028 for (User *U : MulVal->users()) {
3029 if (U == &I || U == OtherVal)
3030 continue;
3031 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
3032 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
Sanjay Patel4b198802016-02-01 22:23:39 +00003033 IC.replaceInstUsesWith(*TI, Mul);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003034 else
3035 TI->setOperand(0, Mul);
3036 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
3037 assert(BO->getOpcode() == Instruction::And);
3038 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
3039 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
3040 APInt ShortMask = CI->getValue().trunc(MulWidth);
3041 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
3042 Instruction *Zext =
3043 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
3044 IC.Worklist.Add(Zext);
Sanjay Patel4b198802016-02-01 22:23:39 +00003045 IC.replaceInstUsesWith(*BO, Zext);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003046 } else {
3047 llvm_unreachable("Unexpected Binary operation");
3048 }
3049 IC.Worklist.Add(cast<Instruction>(U));
3050 }
3051 }
3052 if (isa<Instruction>(OtherVal))
3053 IC.Worklist.Add(cast<Instruction>(OtherVal));
3054
3055 // The original icmp gets replaced with the overflow value, maybe inverted
3056 // depending on predicate.
3057 bool Inverse = false;
3058 switch (I.getPredicate()) {
3059 case ICmpInst::ICMP_NE:
3060 break;
3061 case ICmpInst::ICMP_EQ:
3062 Inverse = true;
3063 break;
3064 case ICmpInst::ICMP_UGT:
3065 case ICmpInst::ICMP_UGE:
3066 if (I.getOperand(0) == MulVal)
3067 break;
3068 Inverse = true;
3069 break;
3070 case ICmpInst::ICMP_ULT:
3071 case ICmpInst::ICMP_ULE:
3072 if (I.getOperand(1) == MulVal)
3073 break;
3074 Inverse = true;
3075 break;
3076 default:
3077 llvm_unreachable("Unexpected predicate");
3078 }
3079 if (Inverse) {
3080 Value *Res = Builder->CreateExtractValue(Call, 1);
3081 return BinaryOperator::CreateNot(Res);
3082 }
3083
3084 return ExtractValueInst::Create(Call, 1);
3085}
3086
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003087/// When performing a comparison against a constant, it is possible that not all
3088/// the bits in the LHS are demanded. This helper method computes the mask that
3089/// IS demanded.
Owen Andersond490c2d2011-01-11 00:36:45 +00003090static APInt DemandedBitsLHSMask(ICmpInst &I,
3091 unsigned BitWidth, bool isSignCheck) {
3092 if (isSignCheck)
3093 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003094
Owen Andersond490c2d2011-01-11 00:36:45 +00003095 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3096 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00003097 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003098
Owen Andersond490c2d2011-01-11 00:36:45 +00003099 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003100 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00003101 // correspond to the trailing ones of the comparand. The value of these
3102 // bits doesn't impact the outcome of the comparison, because any value
3103 // greater than the RHS must differ in a bit higher than these due to carry.
3104 case ICmpInst::ICMP_UGT: {
3105 unsigned trailingOnes = RHS.countTrailingOnes();
3106 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
3107 return ~lowBitsSet;
3108 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003109
Owen Andersond490c2d2011-01-11 00:36:45 +00003110 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
3111 // Any value less than the RHS must differ in a higher bit because of carries.
3112 case ICmpInst::ICMP_ULT: {
3113 unsigned trailingZeros = RHS.countTrailingZeros();
3114 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
3115 return ~lowBitsSet;
3116 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003117
Owen Andersond490c2d2011-01-11 00:36:45 +00003118 default:
3119 return APInt::getAllOnesValue(BitWidth);
3120 }
Owen Andersond490c2d2011-01-11 00:36:45 +00003121}
Chris Lattner2188e402010-01-04 07:37:31 +00003122
Quentin Colombet5ab55552013-09-09 20:56:48 +00003123/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
3124/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00003125/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00003126/// as subtract operands and their positions in those instructions.
3127/// The rational is that several architectures use the same instruction for
3128/// both subtract and cmp, thus it is better if the order of those operands
3129/// match.
3130/// \return true if Op0 and Op1 should be swapped.
3131static bool swapMayExposeCSEOpportunities(const Value * Op0,
3132 const Value * Op1) {
3133 // Filter out pointer value as those cannot appears directly in subtract.
3134 // FIXME: we may want to go through inttoptrs or bitcasts.
3135 if (Op0->getType()->isPointerTy())
3136 return false;
3137 // Count every uses of both Op0 and Op1 in a subtract.
3138 // Each time Op0 is the first operand, count -1: swapping is bad, the
3139 // subtract has already the same layout as the compare.
3140 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00003141 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003142 // At the end, if the benefit is greater than 0, Op0 should come second to
3143 // expose more CSE opportunities.
3144 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003145 for (const User *U : Op0->users()) {
3146 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003147 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
3148 continue;
3149 // If Op0 is the first argument, this is not beneficial to swap the
3150 // arguments.
3151 int LocalSwapBenefits = -1;
3152 unsigned Op1Idx = 1;
3153 if (BinOp->getOperand(Op1Idx) == Op0) {
3154 Op1Idx = 0;
3155 LocalSwapBenefits = 1;
3156 }
3157 if (BinOp->getOperand(Op1Idx) != Op1)
3158 continue;
3159 GlobalSwapBenefits += LocalSwapBenefits;
3160 }
3161 return GlobalSwapBenefits > 0;
3162}
3163
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003164/// \brief Check that one use is in the same block as the definition and all
Sanjay Patel53523312016-09-12 14:25:46 +00003165/// other uses are in blocks dominated by a given block.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003166///
3167/// \param DI Definition
3168/// \param UI Use
3169/// \param DB Block that must dominate all uses of \p DI outside
3170/// the parent block
3171/// \return true when \p UI is the only use of \p DI in the parent block
3172/// and all other uses of \p DI are in blocks dominated by \p DB.
3173///
3174bool InstCombiner::dominatesAllUses(const Instruction *DI,
3175 const Instruction *UI,
3176 const BasicBlock *DB) const {
3177 assert(DI && UI && "Instruction not defined\n");
Sanjay Patel53523312016-09-12 14:25:46 +00003178 // Ignore incomplete definitions.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003179 if (!DI->getParent())
3180 return false;
Sanjay Patel53523312016-09-12 14:25:46 +00003181 // DI and UI must be in the same block.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003182 if (DI->getParent() != UI->getParent())
3183 return false;
Sanjay Patel53523312016-09-12 14:25:46 +00003184 // Protect from self-referencing blocks.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003185 if (DI->getParent() == DB)
3186 return false;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003187 for (const User *U : DI->users()) {
3188 auto *Usr = cast<Instruction>(U);
Justin Bogner99798402016-08-05 01:06:44 +00003189 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003190 return false;
3191 }
3192 return true;
3193}
3194
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003195/// Return true when the instruction sequence within a block is select-cmp-br.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003196static bool isChainSelectCmpBranch(const SelectInst *SI) {
3197 const BasicBlock *BB = SI->getParent();
3198 if (!BB)
3199 return false;
3200 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
3201 if (!BI || BI->getNumSuccessors() != 2)
3202 return false;
3203 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
3204 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
3205 return false;
3206 return true;
3207}
3208
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003209/// \brief True when a select result is replaced by one of its operands
3210/// in select-icmp sequence. This will eventually result in the elimination
3211/// of the select.
3212///
3213/// \param SI Select instruction
3214/// \param Icmp Compare instruction
3215/// \param SIOpd Operand that replaces the select
3216///
3217/// Notes:
3218/// - The replacement is global and requires dominator information
3219/// - The caller is responsible for the actual replacement
3220///
3221/// Example:
3222///
3223/// entry:
3224/// %4 = select i1 %3, %C* %0, %C* null
3225/// %5 = icmp eq %C* %4, null
3226/// br i1 %5, label %9, label %7
3227/// ...
3228/// ; <label>:7 ; preds = %entry
3229/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
3230/// ...
3231///
3232/// can be transformed to
3233///
3234/// %5 = icmp eq %C* %0, null
3235/// %6 = select i1 %3, i1 %5, i1 true
3236/// br i1 %6, label %9, label %7
3237/// ...
3238/// ; <label>:7 ; preds = %entry
3239/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
3240///
3241/// Similar when the first operand of the select is a constant or/and
3242/// the compare is for not equal rather than equal.
3243///
3244/// NOTE: The function is only called when the select and compare constants
3245/// are equal, the optimization can work only for EQ predicates. This is not a
3246/// major restriction since a NE compare should be 'normalized' to an equal
3247/// compare, which usually happens in the combiner and test case
Sanjay Patel53523312016-09-12 14:25:46 +00003248/// select-cmp-br.ll checks for it.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003249bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
3250 const ICmpInst *Icmp,
3251 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00003252 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003253 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
3254 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
3255 // The check for the unique predecessor is not the best that can be
Sanjay Patel53523312016-09-12 14:25:46 +00003256 // done. But it protects efficiently against cases like when SI's
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003257 // home block has two successors, Succ and Succ1, and Succ1 predecessor
3258 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
3259 // replaced can be reached on either path. So the uniqueness check
3260 // guarantees that the path all uses of SI (outside SI's parent) are on
3261 // is disjoint from all other paths out of SI. But that information
3262 // is more expensive to compute, and the trade-off here is in favor
3263 // of compile-time.
3264 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
3265 NumSel++;
3266 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
3267 return true;
3268 }
3269 }
3270 return false;
3271}
3272
Sanjay Patel3151dec2016-09-12 15:24:31 +00003273/// Try to fold the comparison based on range information we can get by checking
3274/// whether bits are known to be zero or one in the inputs.
3275Instruction *InstCombiner::foldICmpUsingKnownBits(ICmpInst &I) {
3276 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3277 Type *Ty = Op0->getType();
Sanjay Patel0531f0a2016-09-12 15:52:28 +00003278 ICmpInst::Predicate Pred = I.getPredicate();
Sanjay Patel3151dec2016-09-12 15:24:31 +00003279
3280 // Get scalar or pointer size.
3281 unsigned BitWidth = Ty->isIntOrIntVectorTy()
3282 ? Ty->getScalarSizeInBits()
3283 : DL.getTypeSizeInBits(Ty->getScalarType());
3284
3285 if (!BitWidth)
3286 return nullptr;
3287
3288 // If this is a normal comparison, it demands all bits. If it is a sign bit
3289 // comparison, it only demands the sign bit.
3290 bool IsSignBit = false;
Sanjay Patelf5887f12016-09-12 16:25:41 +00003291 const APInt *CmpC;
3292 if (match(Op1, m_APInt(CmpC))) {
Sanjay Patel3151dec2016-09-12 15:24:31 +00003293 bool UnusedBit;
Sanjay Patelf5887f12016-09-12 16:25:41 +00003294 IsSignBit = isSignBitCheck(Pred, *CmpC, UnusedBit);
Sanjay Patel3151dec2016-09-12 15:24:31 +00003295 }
3296
3297 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
3298 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
3299
3300 if (SimplifyDemandedBits(I.getOperandUse(0),
3301 DemandedBitsLHSMask(I, BitWidth, IsSignBit),
3302 Op0KnownZero, Op0KnownOne, 0))
3303 return &I;
3304
3305 if (SimplifyDemandedBits(I.getOperandUse(1), APInt::getAllOnesValue(BitWidth),
3306 Op1KnownZero, Op1KnownOne, 0))
3307 return &I;
3308
3309 // Given the known and unknown bits, compute a range that the LHS could be
3310 // in. Compute the Min, Max and RHS values based on the known bits. For the
3311 // EQ and NE we use unsigned values.
3312 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
3313 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
3314 if (I.isSigned()) {
3315 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, Op0Min,
3316 Op0Max);
3317 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, Op1Min,
3318 Op1Max);
3319 } else {
3320 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, Op0Min,
3321 Op0Max);
3322 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, Op1Min,
3323 Op1Max);
3324 }
3325
3326 // If Min and Max are known to be the same, then SimplifyDemandedBits
Sanjay Patel0531f0a2016-09-12 15:52:28 +00003327 // figured out that the LHS is a constant. Constant fold this now, so that
3328 // code below can assume that Min != Max.
Sanjay Patel3151dec2016-09-12 15:24:31 +00003329 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Sanjay Patel0531f0a2016-09-12 15:52:28 +00003330 return new ICmpInst(Pred, ConstantInt::get(Op0->getType(), Op0Min), Op1);
Sanjay Patel3151dec2016-09-12 15:24:31 +00003331 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Sanjay Patel0531f0a2016-09-12 15:52:28 +00003332 return new ICmpInst(Pred, Op0, ConstantInt::get(Op1->getType(), Op1Min));
Sanjay Patel3151dec2016-09-12 15:24:31 +00003333
3334 // Based on the range information we know about the LHS, see if we can
3335 // simplify this comparison. For example, (x&4) < 8 is always true.
Sanjay Patel0531f0a2016-09-12 15:52:28 +00003336 switch (Pred) {
Sanjay Patel3151dec2016-09-12 15:24:31 +00003337 default:
3338 llvm_unreachable("Unknown icmp opcode!");
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003339 case ICmpInst::ICMP_EQ:
Sanjay Patel3151dec2016-09-12 15:24:31 +00003340 case ICmpInst::ICMP_NE: {
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003341 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) {
3342 return Pred == CmpInst::ICMP_EQ
3343 ? replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()))
3344 : replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3345 }
Sanjay Patel3151dec2016-09-12 15:24:31 +00003346
Sanjay Patel0531f0a2016-09-12 15:52:28 +00003347 // If all bits are known zero except for one, then we know at most one bit
3348 // is set. If the comparison is against zero, then this is a check to see if
3349 // *that* bit is set.
Sanjay Patel3151dec2016-09-12 15:24:31 +00003350 APInt Op0KnownZeroInverted = ~Op0KnownZero;
3351 if (~Op1KnownZero == 0) {
3352 // If the LHS is an AND with the same constant, look through it.
3353 Value *LHS = nullptr;
Sanjay Patel7577a3d2016-09-15 14:15:47 +00003354 const APInt *LHSC;
3355 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
3356 *LHSC != Op0KnownZeroInverted)
Sanjay Patel3151dec2016-09-12 15:24:31 +00003357 LHS = Op0;
3358
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003359 Value *X;
Sanjay Patel3151dec2016-09-12 15:24:31 +00003360 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
3361 APInt ValToCheck = Op0KnownZeroInverted;
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003362 Type *XTy = X->getType();
Sanjay Patel3151dec2016-09-12 15:24:31 +00003363 if (ValToCheck.isPowerOf2()) {
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003364 // ((1 << X) & 8) == 0 -> X != 3
3365 // ((1 << X) & 8) != 0 -> X == 3
3366 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros());
3367 auto NewPred = ICmpInst::getInversePredicate(Pred);
3368 return new ICmpInst(NewPred, X, CmpC);
Sanjay Patel3151dec2016-09-12 15:24:31 +00003369 } else if ((++ValToCheck).isPowerOf2()) {
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003370 // ((1 << X) & 7) == 0 -> X >= 3
3371 // ((1 << X) & 7) != 0 -> X < 3
3372 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros());
3373 auto NewPred =
3374 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
3375 return new ICmpInst(NewPred, X, CmpC);
Sanjay Patel3151dec2016-09-12 15:24:31 +00003376 }
3377 }
3378
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003379 // Check if the LHS is 8 >>u x and the result is a power of 2 like 1.
Sanjay Patel3151dec2016-09-12 15:24:31 +00003380 const APInt *CI;
3381 if (Op0KnownZeroInverted == 1 &&
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003382 match(LHS, m_LShr(m_Power2(CI), m_Value(X)))) {
3383 // ((8 >>u X) & 1) == 0 -> X != 3
3384 // ((8 >>u X) & 1) != 0 -> X == 3
3385 unsigned CmpVal = CI->countTrailingZeros();
3386 auto NewPred = ICmpInst::getInversePredicate(Pred);
3387 return new ICmpInst(NewPred, X, ConstantInt::get(X->getType(), CmpVal));
3388 }
Sanjay Patel3151dec2016-09-12 15:24:31 +00003389 }
3390 break;
3391 }
3392 case ICmpInst::ICMP_ULT: {
3393 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
3394 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3395 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
3396 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3397 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
3398 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3399
3400 const APInt *CmpC;
3401 if (match(Op1, m_APInt(CmpC))) {
3402 // A <u C -> A == C-1 if min(A)+1 == C
3403 if (Op1Max == Op0Min + 1) {
3404 Constant *CMinus1 = ConstantInt::get(Op0->getType(), *CmpC - 1);
3405 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, CMinus1);
3406 }
3407 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
3408 if (CmpC->isMinSignedValue()) {
3409 Constant *AllOnes = Constant::getAllOnesValue(Op0->getType());
3410 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
3411 }
3412 }
3413 break;
3414 }
3415 case ICmpInst::ICMP_UGT: {
3416 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
3417 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3418
3419 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
3420 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3421
3422 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
3423 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3424
3425 const APInt *CmpC;
3426 if (match(Op1, m_APInt(CmpC))) {
3427 // A >u C -> A == C+1 if max(a)-1 == C
3428 if (*CmpC == Op0Max - 1)
3429 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
3430 ConstantInt::get(Op1->getType(), *CmpC + 1));
3431
3432 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
3433 if (CmpC->isMaxSignedValue())
3434 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
3435 Constant::getNullValue(Op0->getType()));
3436 }
3437 break;
3438 }
3439 case ICmpInst::ICMP_SLT:
3440 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
3441 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3442 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
3443 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3444 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
3445 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3446 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3447 if (Op1Max == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
3448 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
3449 Builder->getInt(CI->getValue() - 1));
3450 }
3451 break;
3452 case ICmpInst::ICMP_SGT:
3453 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
3454 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3455 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
3456 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3457
3458 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
3459 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3460 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3461 if (Op1Min == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
3462 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
3463 Builder->getInt(CI->getValue() + 1));
3464 }
3465 break;
3466 case ICmpInst::ICMP_SGE:
3467 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
3468 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
3469 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3470 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
3471 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3472 break;
3473 case ICmpInst::ICMP_SLE:
3474 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
3475 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
3476 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3477 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
3478 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3479 break;
3480 case ICmpInst::ICMP_UGE:
3481 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
3482 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
3483 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3484 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
3485 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3486 break;
3487 case ICmpInst::ICMP_ULE:
3488 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
3489 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
3490 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3491 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
3492 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3493 break;
3494 }
3495
3496 // Turn a signed comparison into an unsigned one if both operands are known to
3497 // have the same sign.
3498 if (I.isSigned() &&
3499 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
3500 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
3501 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
3502
3503 return nullptr;
3504}
3505
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003506/// If we have an icmp le or icmp ge instruction with a constant operand, turn
3507/// it into the appropriate icmp lt or icmp gt instruction. This transform
3508/// allows them to be folded in visitICmpInst.
Sanjay Patele9b2c322016-05-17 00:57:57 +00003509static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
3510 ICmpInst::Predicate Pred = I.getPredicate();
3511 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE &&
3512 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE)
3513 return nullptr;
3514
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003515 Value *Op0 = I.getOperand(0);
3516 Value *Op1 = I.getOperand(1);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003517 auto *Op1C = dyn_cast<Constant>(Op1);
3518 if (!Op1C)
3519 return nullptr;
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003520
Sanjay Patele9b2c322016-05-17 00:57:57 +00003521 // Check if the constant operand can be safely incremented/decremented without
3522 // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled
3523 // the edge cases for us, so we just assert on them. For vectors, we must
3524 // handle the edge cases.
3525 Type *Op1Type = Op1->getType();
3526 bool IsSigned = I.isSigned();
3527 bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE);
Sanjay Patel18254932016-05-17 01:12:31 +00003528 auto *CI = dyn_cast<ConstantInt>(Op1C);
3529 if (CI) {
Sanjay Patele9b2c322016-05-17 00:57:57 +00003530 // A <= MAX -> TRUE ; A >= MIN -> TRUE
3531 assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned));
3532 } else if (Op1Type->isVectorTy()) {
Sanjay Patelb79ab272016-05-13 15:10:46 +00003533 // TODO? If the edge cases for vectors were guaranteed to be handled as they
Sanjay Patele9b2c322016-05-17 00:57:57 +00003534 // are for scalar, we could remove the min/max checks. However, to do that,
3535 // we would have to use insertelement/shufflevector to replace edge values.
3536 unsigned NumElts = Op1Type->getVectorNumElements();
3537 for (unsigned i = 0; i != NumElts; ++i) {
3538 Constant *Elt = Op1C->getAggregateElement(i);
Benjamin Kramerca9a0fe2016-05-17 12:08:55 +00003539 if (!Elt)
3540 return nullptr;
3541
Sanjay Patele9b2c322016-05-17 00:57:57 +00003542 if (isa<UndefValue>(Elt))
3543 continue;
Sanjay Patel06b127a2016-09-15 14:37:50 +00003544
Sanjay Patele9b2c322016-05-17 00:57:57 +00003545 // Bail out if we can't determine if this constant is min/max or if we
3546 // know that this constant is min/max.
3547 auto *CI = dyn_cast<ConstantInt>(Elt);
3548 if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned)))
3549 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003550 }
Sanjay Patele9b2c322016-05-17 00:57:57 +00003551 } else {
3552 // ConstantExpr?
3553 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003554 }
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003555
Sanjay Patele9b2c322016-05-17 00:57:57 +00003556 // Increment or decrement the constant and set the new comparison predicate:
3557 // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT
Sanjay Patel22b01fe2016-05-17 20:20:40 +00003558 Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003559 CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT;
3560 NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred;
3561 return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne));
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003562}
3563
Chris Lattner2188e402010-01-04 07:37:31 +00003564Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
3565 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00003566 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003567 unsigned Op0Cplxity = getComplexity(Op0);
3568 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003569
Chris Lattner2188e402010-01-04 07:37:31 +00003570 /// Orders the operands of the compare so that they are listed from most
3571 /// complex to least complex. This puts constants before unary operators,
3572 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003573 if (Op0Cplxity < Op1Cplxity ||
Sanjay Patel4c204232016-06-04 20:39:22 +00003574 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003575 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00003576 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003577 Changed = true;
3578 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003579
Jingyue Wu5e34ce32015-06-25 20:14:47 +00003580 if (Value *V =
Justin Bogner99798402016-08-05 01:06:44 +00003581 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00003582 return replaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003583
Pete Cooperbc5c5242011-12-01 03:58:40 +00003584 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00003585 // ie, abs(val) != 0 -> val != 0
Sanjay Patel4c204232016-06-04 20:39:22 +00003586 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003587 Value *Cond, *SelectTrue, *SelectFalse;
3588 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00003589 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003590 if (Value *V = dyn_castNegVal(SelectTrue)) {
3591 if (V == SelectFalse)
3592 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
3593 }
3594 else if (Value *V = dyn_castNegVal(SelectFalse)) {
3595 if (V == SelectTrue)
3596 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00003597 }
3598 }
3599 }
3600
Chris Lattner229907c2011-07-18 04:54:35 +00003601 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00003602
3603 // icmp's with boolean values can always be turned into bitwise operations
Sanjay Patela6fbc822016-06-05 17:49:45 +00003604 if (Ty->getScalarType()->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00003605 switch (I.getPredicate()) {
3606 default: llvm_unreachable("Invalid icmp instruction!");
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003607 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
3608 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003609 return BinaryOperator::CreateNot(Xor);
3610 }
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003611 case ICmpInst::ICMP_NE: // icmp ne i1 A, B -> A^B
Chris Lattner2188e402010-01-04 07:37:31 +00003612 return BinaryOperator::CreateXor(Op0, Op1);
3613
3614 case ICmpInst::ICMP_UGT:
3615 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003616 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003617 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
3618 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003619 return BinaryOperator::CreateAnd(Not, Op1);
3620 }
3621 case ICmpInst::ICMP_SGT:
3622 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003623 LLVM_FALLTHROUGH;
Chris Lattner2188e402010-01-04 07:37:31 +00003624 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003625 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003626 return BinaryOperator::CreateAnd(Not, Op0);
3627 }
3628 case ICmpInst::ICMP_UGE:
3629 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003630 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003631 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
3632 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003633 return BinaryOperator::CreateOr(Not, Op1);
3634 }
3635 case ICmpInst::ICMP_SGE:
3636 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003637 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003638 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
3639 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003640 return BinaryOperator::CreateOr(Not, Op0);
3641 }
3642 }
3643 }
3644
Sanjay Patele9b2c322016-05-17 00:57:57 +00003645 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003646 return NewICmp;
3647
Sanjay Patel06b127a2016-09-15 14:37:50 +00003648 if (Instruction *Res = foldICmpWithConstant(I))
3649 return Res;
Chris Lattner2188e402010-01-04 07:37:31 +00003650
Sanjay Patel3151dec2016-09-12 15:24:31 +00003651 if (Instruction *Res = foldICmpUsingKnownBits(I))
3652 return Res;
Chris Lattner2188e402010-01-04 07:37:31 +00003653
3654 // Test if the ICmpInst instruction is used exclusively by a select as
3655 // part of a minimum or maximum operation. If so, refrain from doing
3656 // any other folding. This helps out other analyses which understand
3657 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
3658 // and CodeGen. And in this case, at least one of the comparison
3659 // operands has at least one user besides the compare (the select),
3660 // which would often largely negate the benefit of folding anyway.
3661 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00003662 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00003663 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
3664 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00003665 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003666
Sanjay Patelf58f68c2016-09-10 15:03:44 +00003667 if (Instruction *Res = foldICmpInstWithConstant(I))
Sanjay Patel1271bf92016-07-23 13:06:49 +00003668 return Res;
3669
Chris Lattner2188e402010-01-04 07:37:31 +00003670 // Handle icmp with constant (but not simple integer constant) RHS
3671 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3672 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3673 switch (LHSI->getOpcode()) {
3674 case Instruction::GetElementPtr:
3675 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3676 if (RHSC->isNullValue() &&
3677 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3678 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3679 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3680 break;
3681 case Instruction::PHI:
3682 // Only fold icmp into the PHI if the phi and icmp are in the same
3683 // block. If in the same block, we're encouraging jump threading. If
3684 // not, we are just pessimizing the code by making an i1 phi.
3685 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003686 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003687 return NV;
3688 break;
3689 case Instruction::Select: {
3690 // If either operand of the select is a constant, we can fold the
3691 // comparison into the select arms, which will cause one to be
3692 // constant folded and the select turned into a bitwise or.
Craig Topperf40110f2014-04-25 05:29:35 +00003693 Value *Op1 = nullptr, *Op2 = nullptr;
Hans Wennborg083ca9b2015-10-06 23:24:35 +00003694 ConstantInt *CI = nullptr;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003695 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003696 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003697 CI = dyn_cast<ConstantInt>(Op1);
3698 }
3699 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003700 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003701 CI = dyn_cast<ConstantInt>(Op2);
3702 }
Chris Lattner2188e402010-01-04 07:37:31 +00003703
3704 // We only want to perform this transformation if it will not lead to
3705 // additional code. This is true if either both sides of the select
3706 // fold to a constant (in which case the icmp is replaced with a select
3707 // which will usually simplify) or this is the only user of the
3708 // select (in which case we are trading a select+icmp for a simpler
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003709 // select+icmp) or all uses of the select can be replaced based on
3710 // dominance information ("Global cases").
3711 bool Transform = false;
3712 if (Op1 && Op2)
3713 Transform = true;
3714 else if (Op1 || Op2) {
3715 // Local case
3716 if (LHSI->hasOneUse())
3717 Transform = true;
3718 // Global cases
3719 else if (CI && !CI->isZero())
3720 // When Op1 is constant try replacing select with second operand.
3721 // Otherwise Op2 is constant and try replacing select with first
3722 // operand.
3723 Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
3724 Op1 ? 2 : 1);
3725 }
3726 if (Transform) {
Chris Lattner2188e402010-01-04 07:37:31 +00003727 if (!Op1)
3728 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3729 RHSC, I.getName());
3730 if (!Op2)
3731 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3732 RHSC, I.getName());
3733 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3734 }
3735 break;
3736 }
Chris Lattner2188e402010-01-04 07:37:31 +00003737 case Instruction::IntToPtr:
3738 // icmp pred inttoptr(X), null -> icmp pred X, 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003739 if (RHSC->isNullValue() &&
3740 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
Chris Lattner2188e402010-01-04 07:37:31 +00003741 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3742 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3743 break;
3744
3745 case Instruction::Load:
3746 // Try to optimize things like "A[i] > 4" to index computations.
3747 if (GetElementPtrInst *GEP =
3748 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3749 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3750 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3751 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00003752 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Chris Lattner2188e402010-01-04 07:37:31 +00003753 return Res;
3754 }
3755 break;
3756 }
3757 }
3758
3759 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3760 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Sanjay Patel43395062016-07-21 18:07:40 +00003761 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner2188e402010-01-04 07:37:31 +00003762 return NI;
3763 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00003764 if (Instruction *NI = foldGEPICmp(GEP, Op0,
Chris Lattner2188e402010-01-04 07:37:31 +00003765 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3766 return NI;
3767
Hans Wennborgf1f36512015-10-07 00:20:07 +00003768 // Try to optimize equality comparisons against alloca-based pointers.
3769 if (Op0->getType()->isPointerTy() && I.isEquality()) {
3770 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
3771 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00003772 if (Instruction *New = foldAllocaCmp(I, Alloca, Op1))
Hans Wennborgf1f36512015-10-07 00:20:07 +00003773 return New;
3774 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00003775 if (Instruction *New = foldAllocaCmp(I, Alloca, Op0))
Hans Wennborgf1f36512015-10-07 00:20:07 +00003776 return New;
3777 }
3778
Chris Lattner2188e402010-01-04 07:37:31 +00003779 // Test to see if the operands of the icmp are casted versions of other
3780 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3781 // now.
3782 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003783 if (Op0->getType()->isPointerTy() &&
3784 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003785 // We keep moving the cast from the left operand over to the right
3786 // operand, where it can often be eliminated completely.
3787 Op0 = CI->getOperand(0);
3788
3789 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3790 // so eliminate it as well.
3791 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3792 Op1 = CI2->getOperand(0);
3793
3794 // If Op1 is a constant, we can fold the cast into the constant.
3795 if (Op0->getType() != Op1->getType()) {
3796 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3797 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3798 } else {
3799 // Otherwise, cast the RHS right before the icmp
3800 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3801 }
3802 }
3803 return new ICmpInst(I.getPredicate(), Op0, Op1);
3804 }
3805 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003806
Chris Lattner2188e402010-01-04 07:37:31 +00003807 if (isa<CastInst>(Op0)) {
3808 // Handle the special case of: icmp (cast bool to X), <cst>
3809 // This comes up when you have code like
3810 // int X = A < B;
3811 // if (X) ...
3812 // For generality, we handle any zero-extension of any operand comparison
3813 // with a constant or another cast from the same type.
3814 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00003815 if (Instruction *R = foldICmpWithCastAndCast(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003816 return R;
3817 }
Chris Lattner2188e402010-01-04 07:37:31 +00003818
Duncan Sandse5220012011-02-17 07:46:37 +00003819 // Special logic for binary operators.
3820 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3821 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3822 if (BO0 || BO1) {
3823 CmpInst::Predicate Pred = I.getPredicate();
3824 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3825 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3826 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3827 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3828 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3829 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3830 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3831 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3832 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3833
3834 // Analyze the case when either Op0 or Op1 is an add instruction.
3835 // 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 +00003836 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +00003837 if (BO0 && BO0->getOpcode() == Instruction::Add) {
3838 A = BO0->getOperand(0);
3839 B = BO0->getOperand(1);
3840 }
3841 if (BO1 && BO1->getOpcode() == Instruction::Add) {
3842 C = BO1->getOperand(0);
3843 D = BO1->getOperand(1);
3844 }
Duncan Sandse5220012011-02-17 07:46:37 +00003845
David Majnemer549f4f22014-11-01 09:09:51 +00003846 // icmp (X+cst) < 0 --> X < -cst
3847 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
3848 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
3849 if (!RHSC->isMinValue(/*isSigned=*/true))
3850 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
3851
Duncan Sandse5220012011-02-17 07:46:37 +00003852 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3853 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3854 return new ICmpInst(Pred, A == Op1 ? B : A,
3855 Constant::getNullValue(Op1->getType()));
3856
3857 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3858 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3859 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3860 C == Op0 ? D : C);
3861
Duncan Sands84653b32011-02-18 16:25:37 +00003862 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003863 if (A && C && (A == C || A == D || B == C || B == D) &&
3864 NoOp0WrapProblem && NoOp1WrapProblem &&
3865 // Try not to increase register pressure.
3866 BO0->hasOneUse() && BO1->hasOneUse()) {
3867 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003868 Value *Y, *Z;
3869 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003870 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003871 Y = B;
3872 Z = D;
3873 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003874 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003875 Y = B;
3876 Z = C;
3877 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003878 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003879 Y = A;
3880 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003881 } else {
3882 assert(B == D);
3883 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003884 Y = A;
3885 Z = C;
3886 }
Duncan Sandse5220012011-02-17 07:46:37 +00003887 return new ICmpInst(Pred, Y, Z);
3888 }
3889
David Majnemerb81cd632013-04-11 20:05:46 +00003890 // icmp slt (X + -1), Y -> icmp sle X, Y
3891 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3892 match(B, m_AllOnes()))
3893 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3894
3895 // icmp sge (X + -1), Y -> icmp sgt X, Y
3896 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3897 match(B, m_AllOnes()))
3898 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3899
3900 // icmp sle (X + 1), Y -> icmp slt X, Y
3901 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3902 match(B, m_One()))
3903 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3904
3905 // icmp sgt (X + 1), Y -> icmp sge X, Y
3906 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3907 match(B, m_One()))
3908 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3909
Michael Liaoc65d3862015-10-19 22:08:14 +00003910 // icmp sgt X, (Y + -1) -> icmp sge X, Y
3911 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3912 match(D, m_AllOnes()))
3913 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3914
3915 // icmp sle X, (Y + -1) -> icmp slt X, Y
3916 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3917 match(D, m_AllOnes()))
3918 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3919
3920 // icmp sge X, (Y + 1) -> icmp sgt X, Y
3921 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE &&
3922 match(D, m_One()))
3923 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3924
3925 // icmp slt X, (Y + 1) -> icmp sle X, Y
3926 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT &&
3927 match(D, m_One()))
3928 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3929
David Majnemerb81cd632013-04-11 20:05:46 +00003930 // if C1 has greater magnitude than C2:
3931 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3932 // s.t. C3 = C1 - C2
3933 //
3934 // if C2 has greater magnitude than C1:
3935 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3936 // s.t. C3 = C2 - C1
3937 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3938 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3939 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3940 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3941 const APInt &AP1 = C1->getValue();
3942 const APInt &AP2 = C2->getValue();
3943 if (AP1.isNegative() == AP2.isNegative()) {
3944 APInt AP1Abs = C1->getValue().abs();
3945 APInt AP2Abs = C2->getValue().abs();
3946 if (AP1Abs.uge(AP2Abs)) {
3947 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
3948 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
3949 return new ICmpInst(Pred, NewAdd, C);
3950 } else {
3951 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
3952 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
3953 return new ICmpInst(Pred, A, NewAdd);
3954 }
3955 }
3956 }
3957
3958
Duncan Sandse5220012011-02-17 07:46:37 +00003959 // Analyze the case when either Op0 or Op1 is a sub instruction.
3960 // 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 +00003961 A = nullptr;
3962 B = nullptr;
3963 C = nullptr;
3964 D = nullptr;
3965 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
3966 A = BO0->getOperand(0);
3967 B = BO0->getOperand(1);
3968 }
3969 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3970 C = BO1->getOperand(0);
3971 D = BO1->getOperand(1);
3972 }
Duncan Sandse5220012011-02-17 07:46:37 +00003973
Duncan Sands84653b32011-02-18 16:25:37 +00003974 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3975 if (A == Op1 && NoOp0WrapProblem)
3976 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3977
3978 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
3979 if (C == Op0 && NoOp1WrapProblem)
3980 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3981
3982 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003983 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
3984 // Try not to increase register pressure.
3985 BO0->hasOneUse() && BO1->hasOneUse())
3986 return new ICmpInst(Pred, A, C);
3987
Duncan Sands84653b32011-02-18 16:25:37 +00003988 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
3989 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3990 // Try not to increase register pressure.
3991 BO0->hasOneUse() && BO1->hasOneUse())
3992 return new ICmpInst(Pred, D, B);
3993
David Majnemer186c9422014-05-15 00:02:20 +00003994 // icmp (0-X) < cst --> x > -cst
3995 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3996 Value *X;
3997 if (match(BO0, m_Neg(m_Value(X))))
3998 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
3999 if (!RHSC->isMinValue(/*isSigned=*/true))
4000 return new ICmpInst(I.getSwappedPredicate(), X,
4001 ConstantExpr::getNeg(RHSC));
4002 }
4003
Craig Topperf40110f2014-04-25 05:29:35 +00004004 BinaryOperator *SRem = nullptr;
Nick Lewyckyafc80982011-03-08 06:29:47 +00004005 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00004006 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
4007 Op1 == BO0->getOperand(1))
4008 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00004009 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00004010 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
4011 Op0 == BO1->getOperand(1))
4012 SRem = BO1;
4013 if (SRem) {
4014 // We don't check hasOneUse to avoid increasing register pressure because
4015 // the value we use is the same value this instruction was already using.
4016 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
4017 default: break;
4018 case ICmpInst::ICMP_EQ:
Sanjay Patel4b198802016-02-01 22:23:39 +00004019 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00004020 case ICmpInst::ICMP_NE:
Sanjay Patel4b198802016-02-01 22:23:39 +00004021 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00004022 case ICmpInst::ICMP_SGT:
4023 case ICmpInst::ICMP_SGE:
4024 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
4025 Constant::getAllOnesValue(SRem->getType()));
4026 case ICmpInst::ICMP_SLT:
4027 case ICmpInst::ICMP_SLE:
4028 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
4029 Constant::getNullValue(SRem->getType()));
4030 }
4031 }
4032
Duncan Sandse5220012011-02-17 07:46:37 +00004033 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
4034 BO0->hasOneUse() && BO1->hasOneUse() &&
4035 BO0->getOperand(1) == BO1->getOperand(1)) {
4036 switch (BO0->getOpcode()) {
4037 default: break;
4038 case Instruction::Add:
4039 case Instruction::Sub:
4040 case Instruction::Xor:
4041 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
4042 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4043 BO1->getOperand(0));
4044 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
4045 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4046 if (CI->getValue().isSignBit()) {
4047 ICmpInst::Predicate Pred = I.isSigned()
4048 ? I.getUnsignedPredicate()
4049 : I.getSignedPredicate();
4050 return new ICmpInst(Pred, BO0->getOperand(0),
4051 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00004052 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004053
David Majnemerf8853ae2016-02-01 17:37:56 +00004054 if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00004055 ICmpInst::Predicate Pred = I.isSigned()
4056 ? I.getUnsignedPredicate()
4057 : I.getSignedPredicate();
4058 Pred = I.getSwappedPredicate(Pred);
4059 return new ICmpInst(Pred, BO0->getOperand(0),
4060 BO1->getOperand(0));
4061 }
Chris Lattner2188e402010-01-04 07:37:31 +00004062 }
Duncan Sandse5220012011-02-17 07:46:37 +00004063 break;
4064 case Instruction::Mul:
4065 if (!I.isEquality())
4066 break;
4067
4068 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4069 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
4070 // Mask = -1 >> count-trailing-zeros(Cst).
4071 if (!CI->isZero() && !CI->isOne()) {
4072 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004073 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00004074 APInt::getLowBitsSet(AP.getBitWidth(),
4075 AP.getBitWidth() -
4076 AP.countTrailingZeros()));
4077 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
4078 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
4079 return new ICmpInst(I.getPredicate(), And1, And2);
4080 }
4081 }
4082 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00004083 case Instruction::UDiv:
4084 case Instruction::LShr:
4085 if (I.isSigned())
4086 break;
Justin Bognerb03fd122016-08-17 05:10:15 +00004087 LLVM_FALLTHROUGH;
Nick Lewycky9719a712011-03-05 05:19:11 +00004088 case Instruction::SDiv:
4089 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00004090 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00004091 break;
4092 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4093 BO1->getOperand(0));
4094 case Instruction::Shl: {
4095 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
4096 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
4097 if (!NUW && !NSW)
4098 break;
4099 if (!NSW && I.isSigned())
4100 break;
4101 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4102 BO1->getOperand(0));
4103 }
Chris Lattner2188e402010-01-04 07:37:31 +00004104 }
4105 }
Sanjoy Dasc86c1622015-08-21 22:22:37 +00004106
4107 if (BO0) {
4108 // Transform A & (L - 1) `ult` L --> L != 0
4109 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
4110 auto BitwiseAnd =
4111 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
4112
4113 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
4114 auto *Zero = Constant::getNullValue(BO0->getType());
4115 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
4116 }
4117 }
Chris Lattner2188e402010-01-04 07:37:31 +00004118 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004119
Chris Lattner2188e402010-01-04 07:37:31 +00004120 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00004121 // Transform (A & ~B) == 0 --> (A & B) != 0
4122 // and (A & ~B) != 0 --> (A & B) == 0
4123 // if A is a power of 2.
4124 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00004125 match(Op1, m_Zero()) &&
Justin Bogner99798402016-08-05 01:06:44 +00004126 isKnownToBeAPowerOfTwo(A, DL, false, 0, &AC, &I, &DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00004127 return new ICmpInst(I.getInversePredicate(),
4128 Builder->CreateAnd(A, B),
4129 Op1);
4130
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004131 // ~x < ~y --> y < x
4132 // ~x < cst --> ~cst < x
4133 if (match(Op0, m_Not(m_Value(A)))) {
4134 if (match(Op1, m_Not(m_Value(B))))
4135 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00004136 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004137 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
4138 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00004139
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004140 Instruction *AddI = nullptr;
4141 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
4142 m_Instruction(AddI))) &&
4143 isa<IntegerType>(A->getType())) {
4144 Value *Result;
4145 Constant *Overflow;
4146 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
4147 Overflow)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004148 replaceInstUsesWith(*AddI, Result);
4149 return replaceInstUsesWith(I, Overflow);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004150 }
4151 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004152
4153 // (zext a) * (zext b) --> llvm.umul.with.overflow.
4154 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4155 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
4156 return R;
4157 }
4158 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4159 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
4160 return R;
4161 }
Chris Lattner2188e402010-01-04 07:37:31 +00004162 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004163
Chris Lattner2188e402010-01-04 07:37:31 +00004164 if (I.isEquality()) {
4165 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00004166
Chris Lattner2188e402010-01-04 07:37:31 +00004167 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4168 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4169 Value *OtherVal = A == Op1 ? B : A;
4170 return new ICmpInst(I.getPredicate(), OtherVal,
4171 Constant::getNullValue(A->getType()));
4172 }
4173
4174 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4175 // A^c1 == C^c2 --> A == C^(c1^c2)
4176 ConstantInt *C1, *C2;
4177 if (match(B, m_ConstantInt(C1)) &&
4178 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00004179 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004180 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00004181 return new ICmpInst(I.getPredicate(), A, Xor);
4182 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004183
Chris Lattner2188e402010-01-04 07:37:31 +00004184 // A^B == A^D -> B == D
4185 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4186 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4187 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4188 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4189 }
4190 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004191
Chris Lattner2188e402010-01-04 07:37:31 +00004192 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4193 (A == Op0 || B == Op0)) {
4194 // A == (A^B) -> B == 0
4195 Value *OtherVal = A == Op0 ? B : A;
4196 return new ICmpInst(I.getPredicate(), OtherVal,
4197 Constant::getNullValue(A->getType()));
4198 }
4199
Chris Lattner2188e402010-01-04 07:37:31 +00004200 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00004201 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00004202 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Craig Topperf40110f2014-04-25 05:29:35 +00004203 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004204
Chris Lattner2188e402010-01-04 07:37:31 +00004205 if (A == C) {
4206 X = B; Y = D; Z = A;
4207 } else if (A == D) {
4208 X = B; Y = C; Z = A;
4209 } else if (B == C) {
4210 X = A; Y = D; Z = B;
4211 } else if (B == D) {
4212 X = A; Y = C; Z = B;
4213 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004214
Chris Lattner2188e402010-01-04 07:37:31 +00004215 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004216 Op1 = Builder->CreateXor(X, Y);
4217 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00004218 I.setOperand(0, Op1);
4219 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4220 return &I;
4221 }
4222 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004223
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004224 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00004225 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004226 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00004227 if ((Op0->hasOneUse() &&
4228 match(Op0, m_ZExt(m_Value(A))) &&
4229 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
4230 (Op1->hasOneUse() &&
4231 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
4232 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004233 APInt Pow2 = Cst1->getValue() + 1;
4234 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
4235 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
4236 return new ICmpInst(I.getPredicate(), A,
4237 Builder->CreateTrunc(B, A->getType()));
4238 }
4239
Benjamin Kramer03f3e242013-11-16 16:00:48 +00004240 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
4241 // For lshr and ashr pairs.
4242 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4243 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
4244 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4245 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
4246 unsigned TypeBits = Cst1->getBitWidth();
4247 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4248 if (ShAmt < TypeBits && ShAmt != 0) {
4249 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
4250 ? ICmpInst::ICMP_UGE
4251 : ICmpInst::ICMP_ULT;
4252 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4253 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
4254 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
4255 }
4256 }
4257
Benjamin Kramer7fa8c432015-03-26 17:12:06 +00004258 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
4259 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
4260 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
4261 unsigned TypeBits = Cst1->getBitWidth();
4262 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4263 if (ShAmt < TypeBits && ShAmt != 0) {
4264 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4265 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
4266 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
4267 I.getName() + ".mask");
4268 return new ICmpInst(I.getPredicate(), And,
4269 Constant::getNullValue(Cst1->getType()));
4270 }
4271 }
4272
Chris Lattner1b06c712011-04-26 20:18:20 +00004273 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
4274 // "icmp (and X, mask), cst"
4275 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00004276 if (Op0->hasOneUse() &&
4277 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
4278 m_ConstantInt(ShAmt))))) &&
4279 match(Op1, m_ConstantInt(Cst1)) &&
4280 // Only do this when A has multiple uses. This is most important to do
4281 // when it exposes other optimizations.
4282 !A->hasOneUse()) {
4283 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004284
Chris Lattner1b06c712011-04-26 20:18:20 +00004285 if (ShAmt < ASize) {
4286 APInt MaskV =
4287 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
4288 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004289
Chris Lattner1b06c712011-04-26 20:18:20 +00004290 APInt CmpV = Cst1->getValue().zext(ASize);
4291 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004292
Chris Lattner1b06c712011-04-26 20:18:20 +00004293 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
4294 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
4295 }
4296 }
Chris Lattner2188e402010-01-04 07:37:31 +00004297 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004298
David Majnemerc1eca5a2014-11-06 23:23:30 +00004299 // The 'cmpxchg' instruction returns an aggregate containing the old value and
4300 // an i1 which indicates whether or not we successfully did the swap.
4301 //
4302 // Replace comparisons between the old value and the expected value with the
4303 // indicator that 'cmpxchg' returns.
4304 //
4305 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
4306 // spuriously fail. In those cases, the old value may equal the expected
4307 // value but it is possible for the swap to not occur.
4308 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4309 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4310 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4311 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4312 !ACXI->isWeak())
4313 return ExtractValueInst::Create(ACXI, 1);
4314
Chris Lattner2188e402010-01-04 07:37:31 +00004315 {
4316 Value *X; ConstantInt *Cst;
4317 // icmp X+Cst, X
4318 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004319 return foldICmpAddOpConst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004320
4321 // icmp X, X+Cst
4322 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004323 return foldICmpAddOpConst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004324 }
Craig Topperf40110f2014-04-25 05:29:35 +00004325 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004326}
4327
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004328/// Fold fcmp ([us]itofp x, cst) if possible.
Sanjay Patel43395062016-07-21 18:07:40 +00004329Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
Chris Lattner2188e402010-01-04 07:37:31 +00004330 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00004331 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004332 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004333
Chris Lattner2188e402010-01-04 07:37:31 +00004334 // Get the width of the mantissa. We don't want to hack on conversions that
4335 // might lose information from the integer, e.g. "i64 -> float"
4336 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00004337 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004338
Matt Arsenault55e73122015-01-06 15:50:59 +00004339 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4340
Chris Lattner2188e402010-01-04 07:37:31 +00004341 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004342
Matt Arsenault55e73122015-01-06 15:50:59 +00004343 if (I.isEquality()) {
4344 FCmpInst::Predicate P = I.getPredicate();
4345 bool IsExact = false;
4346 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
4347 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
4348
4349 // If the floating point constant isn't an integer value, we know if we will
4350 // ever compare equal / not equal to it.
4351 if (!IsExact) {
4352 // TODO: Can never be -0.0 and other non-representable values
4353 APFloat RHSRoundInt(RHS);
4354 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
4355 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
4356 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00004357 return replaceInstUsesWith(I, Builder->getFalse());
Matt Arsenault55e73122015-01-06 15:50:59 +00004358
4359 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
Sanjay Patel4b198802016-02-01 22:23:39 +00004360 return replaceInstUsesWith(I, Builder->getTrue());
Matt Arsenault55e73122015-01-06 15:50:59 +00004361 }
4362 }
4363
4364 // TODO: If the constant is exactly representable, is it always OK to do
4365 // equality compares as integer?
4366 }
4367
Arch D. Robison8ed08542015-09-15 17:51:59 +00004368 // Check to see that the input is converted from an integer type that is small
4369 // enough that preserves all bits. TODO: check here for "known" sign bits.
4370 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4371 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00004372
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004373 // Following test does NOT adjust InputSize downwards for signed inputs,
4374 // because the most negative value still requires all the mantissa bits
Arch D. Robison8ed08542015-09-15 17:51:59 +00004375 // to distinguish it from one less than that value.
4376 if ((int)InputSize > MantissaWidth) {
4377 // Conversion would lose accuracy. Check if loss can impact comparison.
4378 int Exp = ilogb(RHS);
4379 if (Exp == APFloat::IEK_Inf) {
4380 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004381 if (MaxExponent < (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004382 // Conversion could create infinity.
4383 return nullptr;
4384 } else {
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004385 // Note that if RHS is zero or NaN, then Exp is negative
Arch D. Robison8ed08542015-09-15 17:51:59 +00004386 // and first condition is trivially false.
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004387 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004388 // Conversion could affect comparison.
4389 return nullptr;
4390 }
4391 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004392
Chris Lattner2188e402010-01-04 07:37:31 +00004393 // Otherwise, we can potentially simplify the comparison. We know that it
4394 // will always come through as an integer value and we know the constant is
4395 // not a NAN (it would have been previously simplified).
4396 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00004397
Chris Lattner2188e402010-01-04 07:37:31 +00004398 ICmpInst::Predicate Pred;
4399 switch (I.getPredicate()) {
4400 default: llvm_unreachable("Unexpected predicate!");
4401 case FCmpInst::FCMP_UEQ:
4402 case FCmpInst::FCMP_OEQ:
4403 Pred = ICmpInst::ICMP_EQ;
4404 break;
4405 case FCmpInst::FCMP_UGT:
4406 case FCmpInst::FCMP_OGT:
4407 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4408 break;
4409 case FCmpInst::FCMP_UGE:
4410 case FCmpInst::FCMP_OGE:
4411 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4412 break;
4413 case FCmpInst::FCMP_ULT:
4414 case FCmpInst::FCMP_OLT:
4415 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4416 break;
4417 case FCmpInst::FCMP_ULE:
4418 case FCmpInst::FCMP_OLE:
4419 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4420 break;
4421 case FCmpInst::FCMP_UNE:
4422 case FCmpInst::FCMP_ONE:
4423 Pred = ICmpInst::ICMP_NE;
4424 break;
4425 case FCmpInst::FCMP_ORD:
Sanjay Patel4b198802016-02-01 22:23:39 +00004426 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004427 case FCmpInst::FCMP_UNO:
Sanjay Patel4b198802016-02-01 22:23:39 +00004428 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004429 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004430
Chris Lattner2188e402010-01-04 07:37:31 +00004431 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004432
Chris Lattner2188e402010-01-04 07:37:31 +00004433 // See if the FP constant is too large for the integer. For example,
4434 // comparing an i8 to 300.0.
4435 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004436
Chris Lattner2188e402010-01-04 07:37:31 +00004437 if (!LHSUnsigned) {
4438 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4439 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004440 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004441 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4442 APFloat::rmNearestTiesToEven);
4443 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4444 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4445 Pred == ICmpInst::ICMP_SLE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004446 return replaceInstUsesWith(I, Builder->getTrue());
4447 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004448 }
4449 } else {
4450 // If the RHS value is > UnsignedMax, fold the comparison. This handles
4451 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004452 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004453 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4454 APFloat::rmNearestTiesToEven);
4455 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
4456 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
4457 Pred == ICmpInst::ICMP_ULE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004458 return replaceInstUsesWith(I, Builder->getTrue());
4459 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004460 }
4461 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004462
Chris Lattner2188e402010-01-04 07:37:31 +00004463 if (!LHSUnsigned) {
4464 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004465 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004466 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4467 APFloat::rmNearestTiesToEven);
4468 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4469 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4470 Pred == ICmpInst::ICMP_SGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004471 return replaceInstUsesWith(I, Builder->getTrue());
4472 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004473 }
Devang Patel698452b2012-02-13 23:05:18 +00004474 } else {
4475 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004476 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00004477 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
4478 APFloat::rmNearestTiesToEven);
4479 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
4480 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
4481 Pred == ICmpInst::ICMP_UGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004482 return replaceInstUsesWith(I, Builder->getTrue());
4483 return replaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00004484 }
Chris Lattner2188e402010-01-04 07:37:31 +00004485 }
4486
4487 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4488 // [0, UMAX], but it may still be fractional. See if it is fractional by
4489 // casting the FP value to the integer value and back, checking for equality.
4490 // Don't do this for zero, because -0.0 is not fractional.
4491 Constant *RHSInt = LHSUnsigned
4492 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4493 : ConstantExpr::getFPToSI(RHSC, IntTy);
4494 if (!RHS.isZero()) {
4495 bool Equal = LHSUnsigned
4496 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4497 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4498 if (!Equal) {
4499 // If we had a comparison against a fractional value, we have to adjust
4500 // the compare predicate and sometimes the value. RHSC is rounded towards
4501 // zero at this point.
4502 switch (Pred) {
4503 default: llvm_unreachable("Unexpected integer comparison!");
4504 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Sanjay Patel4b198802016-02-01 22:23:39 +00004505 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004506 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Sanjay Patel4b198802016-02-01 22:23:39 +00004507 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004508 case ICmpInst::ICMP_ULE:
4509 // (float)int <= 4.4 --> int <= 4
4510 // (float)int <= -4.4 --> false
4511 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004512 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004513 break;
4514 case ICmpInst::ICMP_SLE:
4515 // (float)int <= 4.4 --> int <= 4
4516 // (float)int <= -4.4 --> int < -4
4517 if (RHS.isNegative())
4518 Pred = ICmpInst::ICMP_SLT;
4519 break;
4520 case ICmpInst::ICMP_ULT:
4521 // (float)int < -4.4 --> false
4522 // (float)int < 4.4 --> int <= 4
4523 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004524 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004525 Pred = ICmpInst::ICMP_ULE;
4526 break;
4527 case ICmpInst::ICMP_SLT:
4528 // (float)int < -4.4 --> int < -4
4529 // (float)int < 4.4 --> int <= 4
4530 if (!RHS.isNegative())
4531 Pred = ICmpInst::ICMP_SLE;
4532 break;
4533 case ICmpInst::ICMP_UGT:
4534 // (float)int > 4.4 --> int > 4
4535 // (float)int > -4.4 --> true
4536 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004537 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004538 break;
4539 case ICmpInst::ICMP_SGT:
4540 // (float)int > 4.4 --> int > 4
4541 // (float)int > -4.4 --> int >= -4
4542 if (RHS.isNegative())
4543 Pred = ICmpInst::ICMP_SGE;
4544 break;
4545 case ICmpInst::ICMP_UGE:
4546 // (float)int >= -4.4 --> true
4547 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00004548 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004549 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004550 Pred = ICmpInst::ICMP_UGT;
4551 break;
4552 case ICmpInst::ICMP_SGE:
4553 // (float)int >= -4.4 --> int >= -4
4554 // (float)int >= 4.4 --> int > 4
4555 if (!RHS.isNegative())
4556 Pred = ICmpInst::ICMP_SGT;
4557 break;
4558 }
4559 }
4560 }
4561
4562 // Lower this FP comparison into an appropriate integer version of the
4563 // comparison.
4564 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4565}
4566
4567Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4568 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004569
Chris Lattner2188e402010-01-04 07:37:31 +00004570 /// Orders the operands of the compare so that they are listed from most
4571 /// complex to least complex. This puts constants before unary operators,
4572 /// before binary operators.
4573 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4574 I.swapOperands();
4575 Changed = true;
4576 }
4577
4578 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004579
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004580 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
Justin Bogner99798402016-08-05 01:06:44 +00004581 I.getFastMathFlags(), DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004582 return replaceInstUsesWith(I, V);
Chris Lattner2188e402010-01-04 07:37:31 +00004583
4584 // Simplify 'fcmp pred X, X'
4585 if (Op0 == Op1) {
4586 switch (I.getPredicate()) {
4587 default: llvm_unreachable("Unknown predicate!");
4588 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4589 case FCmpInst::FCMP_ULT: // True if unordered or less than
4590 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4591 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4592 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4593 I.setPredicate(FCmpInst::FCMP_UNO);
4594 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4595 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004596
Chris Lattner2188e402010-01-04 07:37:31 +00004597 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4598 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4599 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4600 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4601 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4602 I.setPredicate(FCmpInst::FCMP_ORD);
4603 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4604 return &I;
4605 }
4606 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004607
James Molloy2b21a7c2015-05-20 18:41:25 +00004608 // Test if the FCmpInst instruction is used exclusively by a select as
4609 // part of a minimum or maximum operation. If so, refrain from doing
4610 // any other folding. This helps out other analyses which understand
4611 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4612 // and CodeGen. And in this case, at least one of the comparison
4613 // operands has at least one user besides the compare (the select),
4614 // which would often largely negate the benefit of folding anyway.
4615 if (I.hasOneUse())
4616 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4617 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4618 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4619 return nullptr;
4620
Chris Lattner2188e402010-01-04 07:37:31 +00004621 // Handle fcmp with constant RHS
4622 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4623 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4624 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004625 case Instruction::FPExt: {
4626 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4627 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4628 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4629 if (!RHSF)
4630 break;
4631
4632 const fltSemantics *Sem;
4633 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004634 if (LHSExt->getSrcTy()->isHalfTy())
4635 Sem = &APFloat::IEEEhalf;
4636 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004637 Sem = &APFloat::IEEEsingle;
4638 else if (LHSExt->getSrcTy()->isDoubleTy())
4639 Sem = &APFloat::IEEEdouble;
4640 else if (LHSExt->getSrcTy()->isFP128Ty())
4641 Sem = &APFloat::IEEEquad;
4642 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
4643 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004644 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
4645 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004646 else
4647 break;
4648
4649 bool Lossy;
4650 APFloat F = RHSF->getValueAPF();
4651 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4652
Jim Grosbach24ff8342011-09-30 18:45:50 +00004653 // Avoid lossy conversions and denormals. Zero is a special case
4654 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004655 APFloat Fabs = F;
4656 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004657 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004658 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4659 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004660
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004661 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4662 ConstantFP::get(RHSC->getContext(), F));
4663 break;
4664 }
Chris Lattner2188e402010-01-04 07:37:31 +00004665 case Instruction::PHI:
4666 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4667 // block. If in the same block, we're encouraging jump threading. If
4668 // not, we are just pessimizing the code by making an i1 phi.
4669 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004670 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004671 return NV;
4672 break;
4673 case Instruction::SIToFP:
4674 case Instruction::UIToFP:
Sanjay Patel43395062016-07-21 18:07:40 +00004675 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
Chris Lattner2188e402010-01-04 07:37:31 +00004676 return NV;
4677 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004678 case Instruction::FSub: {
4679 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4680 Value *Op;
4681 if (match(LHSI, m_FNeg(m_Value(Op))))
4682 return new FCmpInst(I.getSwappedPredicate(), Op,
4683 ConstantExpr::getFNeg(RHSC));
4684 break;
4685 }
Dan Gohman94732022010-02-24 06:46:09 +00004686 case Instruction::Load:
4687 if (GetElementPtrInst *GEP =
4688 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4689 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4690 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4691 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00004692 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Dan Gohman94732022010-02-24 06:46:09 +00004693 return Res;
4694 }
4695 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004696 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004697 if (!RHSC->isNullValue())
4698 break;
4699
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004700 CallInst *CI = cast<CallInst>(LHSI);
Justin Bogner99798402016-08-05 01:06:44 +00004701 Intrinsic::ID IID = getIntrinsicForCallSite(CI, &TLI);
David Majnemer2e02ba72016-04-15 17:21:03 +00004702 if (IID != Intrinsic::fabs)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004703 break;
4704
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004705 // Various optimization for fabs compared with zero.
David Majnemer2e02ba72016-04-15 17:21:03 +00004706 switch (I.getPredicate()) {
4707 default:
4708 break;
4709 // fabs(x) < 0 --> false
4710 case FCmpInst::FCMP_OLT:
4711 llvm_unreachable("handled by SimplifyFCmpInst");
4712 // fabs(x) > 0 --> x != 0
4713 case FCmpInst::FCMP_OGT:
4714 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
4715 // fabs(x) <= 0 --> x == 0
4716 case FCmpInst::FCMP_OLE:
4717 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
4718 // fabs(x) >= 0 --> !isnan(x)
4719 case FCmpInst::FCMP_OGE:
4720 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
4721 // fabs(x) == 0 --> x == 0
4722 // fabs(x) != 0 --> x != 0
4723 case FCmpInst::FCMP_OEQ:
4724 case FCmpInst::FCMP_UEQ:
4725 case FCmpInst::FCMP_ONE:
4726 case FCmpInst::FCMP_UNE:
4727 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004728 }
4729 }
Chris Lattner2188e402010-01-04 07:37:31 +00004730 }
Chris Lattner2188e402010-01-04 07:37:31 +00004731 }
4732
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004733 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004734 Value *X, *Y;
4735 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004736 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004737
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004738 // fcmp (fpext x), (fpext y) -> fcmp x, y
4739 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4740 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4741 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4742 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4743 RHSExt->getOperand(0));
4744
Craig Topperf40110f2014-04-25 05:29:35 +00004745 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004746}