blob: ce11e470d05a0572460f196e3449c213c930e5e7 [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
Sanjay Pateld93c4c02016-09-15 18:22:25 +000039static ConstantInt *extractElement(Constant *V, Constant *Idx) {
Chris Lattner2188e402010-01-04 07:37:31 +000040 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
41}
42
Sanjay Pateld93c4c02016-09-15 18:22:25 +000043static bool hasAddOverflow(ConstantInt *Result,
Chris Lattner2188e402010-01-04 07:37:31 +000044 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.
Sanjay Pateld93c4c02016-09-15 18:22:25 +000056static bool addWithOverflow(Constant *&Result, Constant *In1,
Chris Lattner2188e402010-01-04 07:37:31 +000057 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);
Sanjay Pateld93c4c02016-09-15 18:22:25 +000063 if (hasAddOverflow(extractElement(Result, Idx),
64 extractElement(In1, Idx),
65 extractElement(In2, Idx),
Chris Lattner2188e402010-01-04 07:37:31 +000066 IsSigned))
67 return true;
68 }
69 return false;
70 }
71
Sanjay Pateld93c4c02016-09-15 18:22:25 +000072 return hasAddOverflow(cast<ConstantInt>(Result),
Chris Lattner2188e402010-01-04 07:37:31 +000073 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
74 IsSigned);
75}
76
Sanjay Pateld93c4c02016-09-15 18:22:25 +000077static bool hasSubOverflow(ConstantInt *Result,
Chris Lattner2188e402010-01-04 07:37:31 +000078 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.
Sanjay Pateld93c4c02016-09-15 18:22:25 +000091static bool subWithOverflow(Constant *&Result, Constant *In1,
Chris Lattner2188e402010-01-04 07:37:31 +000092 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);
Sanjay Pateld93c4c02016-09-15 18:22:25 +000098 if (hasSubOverflow(extractElement(Result, Idx),
99 extractElement(In1, Idx),
100 extractElement(In2, Idx),
Chris Lattner2188e402010-01-04 07:37:31 +0000101 IsSigned))
102 return true;
103 }
104 return false;
105 }
106
Sanjay Pateld93c4c02016-09-15 18:22:25 +0000107 return hasSubOverflow(cast<ConstantInt>(Result),
Chris Lattner2188e402010-01-04 07:37:31 +0000108 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.
Sanjay Pateld93c4c02016-09-15 18:22:25 +0000178static void computeSignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000179 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.
Sanjay Pateld93c4c02016-09-15 18:22:25 +0000201static void computeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattner2188e402010-01-04 07:37:31 +0000202 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();
Davide Italiano2133bf52017-02-07 17:56:50 +0000233 // Don't blow up on huge arrays.
234 if (ArrayElementCount > MaxArraySizeForCombine)
235 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000236
Chris Lattner2188e402010-01-04 07:37:31 +0000237 // There are many forms of this optimization we can handle, for now, just do
238 // the simple index into a single-dimensional array.
239 //
240 // Require: GEP GV, 0, i {{, constant indices}}
241 if (GEP->getNumOperands() < 3 ||
242 !isa<ConstantInt>(GEP->getOperand(1)) ||
243 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
244 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000245 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000246
247 // Check that indices after the variable are constants and in-range for the
248 // type they index. Collect the indices. This is typically for arrays of
249 // structs.
250 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000251
Chris Lattnerfe741762012-01-31 02:55:06 +0000252 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000253 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
254 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000255 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000256
Chris Lattner2188e402010-01-04 07:37:31 +0000257 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000258 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000259
Chris Lattner229907c2011-07-18 04:54:35 +0000260 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000261 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000262 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000263 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000264 EltTy = ATy->getElementType();
265 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000266 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000267 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000268
Chris Lattner2188e402010-01-04 07:37:31 +0000269 LaterIndices.push_back(IdxVal);
270 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000271
Chris Lattner2188e402010-01-04 07:37:31 +0000272 enum { Overdefined = -3, Undefined = -2 };
273
274 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000275
Chris Lattner2188e402010-01-04 07:37:31 +0000276 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
277 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
278 // and 87 is the second (and last) index. FirstTrueElement is -2 when
279 // undefined, otherwise set to the first true element. SecondTrueElement is
280 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
281 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
282
283 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
284 // form "i != 47 & i != 87". Same state transitions as for true elements.
285 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000286
Chris Lattner2188e402010-01-04 07:37:31 +0000287 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
288 /// define a state machine that triggers for ranges of values that the index
289 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
290 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
291 /// index in the range (inclusive). We use -2 for undefined here because we
292 /// use relative comparisons and don't want 0-1 to match -1.
293 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000294
Chris Lattner2188e402010-01-04 07:37:31 +0000295 // MagicBitvector - This is a magic bitvector where we set a bit if the
296 // comparison is true for element 'i'. If there are 64 elements or less in
297 // the array, this will fully represent all the comparison results.
298 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000299
Chris Lattner2188e402010-01-04 07:37:31 +0000300 // Scan the array and see if one of our patterns matches.
301 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000302 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
303 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000304 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000305
Chris Lattner2188e402010-01-04 07:37:31 +0000306 // If this is indexing an array of structures, get the structure element.
307 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000308 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000309
Chris Lattner2188e402010-01-04 07:37:31 +0000310 // If the element is masked, handle it.
311 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000312
Chris Lattner2188e402010-01-04 07:37:31 +0000313 // Find out if the comparison would be true or false for the i'th element.
314 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Justin Bogner99798402016-08-05 01:06:44 +0000315 CompareRHS, DL, &TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000316 // If the result is undef for this element, ignore it.
317 if (isa<UndefValue>(C)) {
318 // Extend range state machines to cover this element in case there is an
319 // undef in the middle of the range.
320 if (TrueRangeEnd == (int)i-1)
321 TrueRangeEnd = i;
322 if (FalseRangeEnd == (int)i-1)
323 FalseRangeEnd = i;
324 continue;
325 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000326
Chris Lattner2188e402010-01-04 07:37:31 +0000327 // If we can't compute the result for any of the elements, we have to give
328 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000329 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000330
Chris Lattner2188e402010-01-04 07:37:31 +0000331 // Otherwise, we know if the comparison is true or false for this element,
332 // update our state machines.
333 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000334
Chris Lattner2188e402010-01-04 07:37:31 +0000335 // State machine for single/double/range index comparison.
336 if (IsTrueForElt) {
337 // Update the TrueElement state machine.
338 if (FirstTrueElement == Undefined)
339 FirstTrueElement = TrueRangeEnd = i; // First true element.
340 else {
341 // Update double-compare state machine.
342 if (SecondTrueElement == Undefined)
343 SecondTrueElement = i;
344 else
345 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000346
Chris Lattner2188e402010-01-04 07:37:31 +0000347 // Update range state machine.
348 if (TrueRangeEnd == (int)i-1)
349 TrueRangeEnd = i;
350 else
351 TrueRangeEnd = Overdefined;
352 }
353 } else {
354 // Update the FalseElement state machine.
355 if (FirstFalseElement == Undefined)
356 FirstFalseElement = FalseRangeEnd = i; // First false element.
357 else {
358 // Update double-compare state machine.
359 if (SecondFalseElement == Undefined)
360 SecondFalseElement = i;
361 else
362 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000363
Chris Lattner2188e402010-01-04 07:37:31 +0000364 // Update range state machine.
365 if (FalseRangeEnd == (int)i-1)
366 FalseRangeEnd = i;
367 else
368 FalseRangeEnd = Overdefined;
369 }
370 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000371
Chris Lattner2188e402010-01-04 07:37:31 +0000372 // If this element is in range, update our magic bitvector.
373 if (i < 64 && IsTrueForElt)
374 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000375
Chris Lattner2188e402010-01-04 07:37:31 +0000376 // If all of our states become overdefined, bail out early. Since the
377 // predicate is expensive, only check it every 8 elements. This is only
378 // really useful for really huge arrays.
379 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
380 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
381 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000382 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000383 }
384
385 // Now that we've scanned the entire array, emit our new comparison(s). We
386 // order the state machines in complexity of the generated code.
387 Value *Idx = GEP->getOperand(2);
388
Matt Arsenault5aeae182013-08-19 21:40:31 +0000389 // If the index is larger than the pointer size of the target, truncate the
390 // index down like the GEP would do implicitly. We don't have to do this for
391 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000392 if (!GEP->isInBounds()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000393 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000394 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
395 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
396 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
397 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000398
Chris Lattner2188e402010-01-04 07:37:31 +0000399 // If the comparison is only true for one or two elements, emit direct
400 // comparisons.
401 if (SecondTrueElement != Overdefined) {
402 // None true -> false.
403 if (FirstTrueElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000404 return replaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000405
Chris Lattner2188e402010-01-04 07:37:31 +0000406 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000407
Chris Lattner2188e402010-01-04 07:37:31 +0000408 // True for one element -> 'i == 47'.
409 if (SecondTrueElement == Undefined)
410 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000411
Chris Lattner2188e402010-01-04 07:37:31 +0000412 // True for two elements -> 'i == 47 | i == 72'.
413 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
414 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
415 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
416 return BinaryOperator::CreateOr(C1, C2);
417 }
418
419 // If the comparison is only false for one or two elements, emit direct
420 // comparisons.
421 if (SecondFalseElement != Overdefined) {
422 // None false -> true.
423 if (FirstFalseElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000424 return replaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000425
Chris Lattner2188e402010-01-04 07:37:31 +0000426 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
427
428 // False for one element -> 'i != 47'.
429 if (SecondFalseElement == Undefined)
430 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000431
Chris Lattner2188e402010-01-04 07:37:31 +0000432 // False for two elements -> 'i != 47 & i != 72'.
433 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
434 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
435 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
436 return BinaryOperator::CreateAnd(C1, C2);
437 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000438
Chris Lattner2188e402010-01-04 07:37:31 +0000439 // If the comparison can be replaced with a range comparison for the elements
440 // where it is true, emit the range check.
441 if (TrueRangeEnd != Overdefined) {
442 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000443
Chris Lattner2188e402010-01-04 07:37:31 +0000444 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
445 if (FirstTrueElement) {
446 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
447 Idx = Builder->CreateAdd(Idx, Offs);
448 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000449
Chris Lattner2188e402010-01-04 07:37:31 +0000450 Value *End = ConstantInt::get(Idx->getType(),
451 TrueRangeEnd-FirstTrueElement+1);
452 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
453 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000454
Chris Lattner2188e402010-01-04 07:37:31 +0000455 // False range check.
456 if (FalseRangeEnd != Overdefined) {
457 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
458 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
459 if (FirstFalseElement) {
460 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
461 Idx = Builder->CreateAdd(Idx, Offs);
462 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000463
Chris Lattner2188e402010-01-04 07:37:31 +0000464 Value *End = ConstantInt::get(Idx->getType(),
465 FalseRangeEnd-FirstFalseElement);
466 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
467 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000468
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000469 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000470 // of this load, replace it with computation that does:
471 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000472 {
Craig Topperf40110f2014-04-25 05:29:35 +0000473 Type *Ty = nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000474
475 // Look for an appropriate type:
476 // - The type of Idx if the magic fits
477 // - The smallest fitting legal type if we have a DataLayout
478 // - Default to i32
479 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
480 Ty = Idx->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000481 else
482 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000483
Craig Topperf40110f2014-04-25 05:29:35 +0000484 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000485 Value *V = Builder->CreateIntCast(Idx, Ty, false);
486 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
487 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
488 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
489 }
Chris Lattner2188e402010-01-04 07:37:31 +0000490 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000491
Craig Topperf40110f2014-04-25 05:29:35 +0000492 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000493}
494
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000495/// Return a value that can be used to compare the *offset* implied by a GEP to
496/// zero. For example, if we have &A[i], we want to return 'i' for
497/// "icmp ne i, 0". Note that, in general, indices can be complex, and scales
498/// are involved. The above expression would also be legal to codegen as
499/// "icmp ne (i*4), 0" (assuming A is a pointer to i32).
500/// This latter form is less amenable to optimization though, and we are allowed
Chris Lattner2188e402010-01-04 07:37:31 +0000501/// to generate the first by knowing that pointer arithmetic doesn't overflow.
502///
503/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000504///
Sanjay Pateld93c4c02016-09-15 18:22:25 +0000505static Value *evaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000506 const DataLayout &DL) {
Chris Lattner2188e402010-01-04 07:37:31 +0000507 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000508
Chris Lattner2188e402010-01-04 07:37:31 +0000509 // Check to see if this gep only has a single variable index. If so, and if
510 // any constant indices are a multiple of its scale, then we can compute this
511 // in terms of the scale of the variable index. For example, if the GEP
512 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
513 // because the expression will cross zero at the same point.
514 unsigned i, e = GEP->getNumOperands();
515 int64_t Offset = 0;
516 for (i = 1; i != e; ++i, ++GTI) {
517 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
518 // Compute the aggregate offset of constant indices.
519 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000520
Chris Lattner2188e402010-01-04 07:37:31 +0000521 // Handle a struct index, which adds its field offset to the pointer.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000522 if (StructType *STy = GTI.getStructTypeOrNull()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000523 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000524 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000525 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000526 Offset += Size*CI->getSExtValue();
527 }
528 } else {
529 // Found our variable index.
530 break;
531 }
532 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000533
Chris Lattner2188e402010-01-04 07:37:31 +0000534 // If there are no variable indices, we must have a constant offset, just
535 // evaluate it the general way.
Craig Topperf40110f2014-04-25 05:29:35 +0000536 if (i == e) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000537
Chris Lattner2188e402010-01-04 07:37:31 +0000538 Value *VariableIdx = GEP->getOperand(i);
539 // Determine the scale factor of the variable element. For example, this is
540 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000541 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000542
Chris Lattner2188e402010-01-04 07:37:31 +0000543 // Verify that there are no other variable indices. If so, emit the hard way.
544 for (++i, ++GTI; i != e; ++i, ++GTI) {
545 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000546 if (!CI) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000547
Chris Lattner2188e402010-01-04 07:37:31 +0000548 // Compute the aggregate offset of constant indices.
549 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000550
Chris Lattner2188e402010-01-04 07:37:31 +0000551 // Handle a struct index, which adds its field offset to the pointer.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000552 if (StructType *STy = GTI.getStructTypeOrNull()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000553 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000554 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000555 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000556 Offset += Size*CI->getSExtValue();
557 }
558 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000559
Chris Lattner2188e402010-01-04 07:37:31 +0000560 // Okay, we know we have a single variable index, which must be a
561 // pointer/array/vector index. If there is no offset, life is simple, return
562 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000563 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000564 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000565 if (Offset == 0) {
566 // Cast to intptrty in case a truncation occurs. If an extension is needed,
567 // we don't need to bother extending: the extension won't affect where the
568 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000569 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000570 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
571 }
Chris Lattner2188e402010-01-04 07:37:31 +0000572 return VariableIdx;
573 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000574
Chris Lattner2188e402010-01-04 07:37:31 +0000575 // Otherwise, there is an index. The computation we will do will be modulo
576 // the pointer size, so get it.
577 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000578
Chris Lattner2188e402010-01-04 07:37:31 +0000579 Offset &= PtrSizeMask;
580 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000581
Chris Lattner2188e402010-01-04 07:37:31 +0000582 // To do this transformation, any constant index must be a multiple of the
583 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
584 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
585 // multiple of the variable scale.
586 int64_t NewOffs = Offset / (int64_t)VariableScale;
587 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000588 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000589
Chris Lattner2188e402010-01-04 07:37:31 +0000590 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000591 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000592 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
593 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000594 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000595 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000596}
597
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000598/// Returns true if we can rewrite Start as a GEP with pointer Base
599/// and some integer offset. The nodes that need to be re-written
600/// for this transformation will be added to Explored.
601static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
602 const DataLayout &DL,
603 SetVector<Value *> &Explored) {
604 SmallVector<Value *, 16> WorkList(1, Start);
605 Explored.insert(Base);
606
607 // The following traversal gives us an order which can be used
608 // when doing the final transformation. Since in the final
609 // transformation we create the PHI replacement instructions first,
610 // we don't have to get them in any particular order.
611 //
612 // However, for other instructions we will have to traverse the
613 // operands of an instruction first, which means that we have to
614 // do a post-order traversal.
615 while (!WorkList.empty()) {
616 SetVector<PHINode *> PHIs;
617
618 while (!WorkList.empty()) {
619 if (Explored.size() >= 100)
620 return false;
621
622 Value *V = WorkList.back();
623
624 if (Explored.count(V) != 0) {
625 WorkList.pop_back();
626 continue;
627 }
628
629 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
David Majnemer8b16da82016-09-15 20:10:09 +0000630 !isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000631 // We've found some value that we can't explore which is different from
632 // the base. Therefore we can't do this transformation.
633 return false;
634
635 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
636 auto *CI = dyn_cast<CastInst>(V);
637 if (!CI->isNoopCast(DL))
638 return false;
639
640 if (Explored.count(CI->getOperand(0)) == 0)
641 WorkList.push_back(CI->getOperand(0));
642 }
643
644 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
645 // We're limiting the GEP to having one index. This will preserve
646 // the original pointer type. We could handle more cases in the
647 // future.
648 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
649 GEP->getType() != Start->getType())
650 return false;
651
652 if (Explored.count(GEP->getOperand(0)) == 0)
653 WorkList.push_back(GEP->getOperand(0));
654 }
655
656 if (WorkList.back() == V) {
657 WorkList.pop_back();
658 // We've finished visiting this node, mark it as such.
659 Explored.insert(V);
660 }
661
662 if (auto *PN = dyn_cast<PHINode>(V)) {
David Majnemercdf28732016-03-19 04:39:52 +0000663 // We cannot transform PHIs on unsplittable basic blocks.
664 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
665 return false;
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000666 Explored.insert(PN);
667 PHIs.insert(PN);
668 }
669 }
670
671 // Explore the PHI nodes further.
672 for (auto *PN : PHIs)
673 for (Value *Op : PN->incoming_values())
674 if (Explored.count(Op) == 0)
675 WorkList.push_back(Op);
676 }
677
678 // Make sure that we can do this. Since we can't insert GEPs in a basic
679 // block before a PHI node, we can't easily do this transformation if
680 // we have PHI node users of transformed instructions.
681 for (Value *Val : Explored) {
682 for (Value *Use : Val->uses()) {
683
684 auto *PHI = dyn_cast<PHINode>(Use);
685 auto *Inst = dyn_cast<Instruction>(Val);
686
687 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
688 Explored.count(PHI) == 0)
689 continue;
690
691 if (PHI->getParent() == Inst->getParent())
692 return false;
693 }
694 }
695 return true;
696}
697
698// Sets the appropriate insert point on Builder where we can add
699// a replacement Instruction for V (if that is possible).
700static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
701 bool Before = true) {
702 if (auto *PHI = dyn_cast<PHINode>(V)) {
703 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
704 return;
705 }
706 if (auto *I = dyn_cast<Instruction>(V)) {
707 if (!Before)
708 I = &*std::next(I->getIterator());
709 Builder.SetInsertPoint(I);
710 return;
711 }
712 if (auto *A = dyn_cast<Argument>(V)) {
713 // Set the insertion point in the entry block.
714 BasicBlock &Entry = A->getParent()->getEntryBlock();
715 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
716 return;
717 }
718 // Otherwise, this is a constant and we don't need to set a new
719 // insertion point.
720 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
721}
722
723/// Returns a re-written value of Start as an indexed GEP using Base as a
724/// pointer.
725static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
726 const DataLayout &DL,
727 SetVector<Value *> &Explored) {
728 // Perform all the substitutions. This is a bit tricky because we can
729 // have cycles in our use-def chains.
730 // 1. Create the PHI nodes without any incoming values.
731 // 2. Create all the other values.
732 // 3. Add the edges for the PHI nodes.
733 // 4. Emit GEPs to get the original pointers.
734 // 5. Remove the original instructions.
735 Type *IndexType = IntegerType::get(
736 Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType()));
737
738 DenseMap<Value *, Value *> NewInsts;
739 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
740
741 // Create the new PHI nodes, without adding any incoming values.
742 for (Value *Val : Explored) {
743 if (Val == Base)
744 continue;
745 // Create empty phi nodes. This avoids cyclic dependencies when creating
746 // the remaining instructions.
747 if (auto *PHI = dyn_cast<PHINode>(Val))
748 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
749 PHI->getName() + ".idx", PHI);
750 }
751 IRBuilder<> Builder(Base->getContext());
752
753 // Create all the other instructions.
754 for (Value *Val : Explored) {
755
756 if (NewInsts.find(Val) != NewInsts.end())
757 continue;
758
759 if (auto *CI = dyn_cast<CastInst>(Val)) {
760 NewInsts[CI] = NewInsts[CI->getOperand(0)];
761 continue;
762 }
763 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
764 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
765 : GEP->getOperand(1);
766 setInsertionPoint(Builder, GEP);
767 // Indices might need to be sign extended. GEPs will magically do
768 // this, but we need to do it ourselves here.
769 if (Index->getType()->getScalarSizeInBits() !=
770 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
771 Index = Builder.CreateSExtOrTrunc(
772 Index, NewInsts[GEP->getOperand(0)]->getType(),
773 GEP->getOperand(0)->getName() + ".sext");
774 }
775
776 auto *Op = NewInsts[GEP->getOperand(0)];
777 if (isa<ConstantInt>(Op) && dyn_cast<ConstantInt>(Op)->isZero())
778 NewInsts[GEP] = Index;
779 else
780 NewInsts[GEP] = Builder.CreateNSWAdd(
781 Op, Index, GEP->getOperand(0)->getName() + ".add");
782 continue;
783 }
784 if (isa<PHINode>(Val))
785 continue;
786
787 llvm_unreachable("Unexpected instruction type");
788 }
789
790 // Add the incoming values to the PHI nodes.
791 for (Value *Val : Explored) {
792 if (Val == Base)
793 continue;
794 // All the instructions have been created, we can now add edges to the
795 // phi nodes.
796 if (auto *PHI = dyn_cast<PHINode>(Val)) {
797 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
798 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
799 Value *NewIncoming = PHI->getIncomingValue(I);
800
801 if (NewInsts.find(NewIncoming) != NewInsts.end())
802 NewIncoming = NewInsts[NewIncoming];
803
804 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
805 }
806 }
807 }
808
809 for (Value *Val : Explored) {
810 if (Val == Base)
811 continue;
812
813 // Depending on the type, for external users we have to emit
814 // a GEP or a GEP + ptrtoint.
815 setInsertionPoint(Builder, Val, false);
816
817 // If required, create an inttoptr instruction for Base.
818 Value *NewBase = Base;
819 if (!Base->getType()->isPointerTy())
820 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
821 Start->getName() + "to.ptr");
822
823 Value *GEP = Builder.CreateInBoundsGEP(
824 Start->getType()->getPointerElementType(), NewBase,
825 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
826
827 if (!Val->getType()->isPointerTy()) {
828 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
829 Val->getName() + ".conv");
830 GEP = Cast;
831 }
832 Val->replaceAllUsesWith(GEP);
833 }
834
835 return NewInsts[Start];
836}
837
838/// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
839/// the input Value as a constant indexed GEP. Returns a pair containing
840/// the GEPs Pointer and Index.
841static std::pair<Value *, Value *>
842getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
843 Type *IndexType = IntegerType::get(V->getContext(),
844 DL.getPointerTypeSizeInBits(V->getType()));
845
846 Constant *Index = ConstantInt::getNullValue(IndexType);
847 while (true) {
848 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
849 // We accept only inbouds GEPs here to exclude the possibility of
850 // overflow.
851 if (!GEP->isInBounds())
852 break;
853 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
854 GEP->getType() == V->getType()) {
855 V = GEP->getOperand(0);
856 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
857 Index = ConstantExpr::getAdd(
858 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
859 continue;
860 }
861 break;
862 }
863 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
864 if (!CI->isNoopCast(DL))
865 break;
866 V = CI->getOperand(0);
867 continue;
868 }
869 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
870 if (!CI->isNoopCast(DL))
871 break;
872 V = CI->getOperand(0);
873 continue;
874 }
875 break;
876 }
877 return {V, Index};
878}
879
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000880/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
881/// We can look through PHIs, GEPs and casts in order to determine a common base
882/// between GEPLHS and RHS.
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000883static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
884 ICmpInst::Predicate Cond,
885 const DataLayout &DL) {
886 if (!GEPLHS->hasAllConstantIndices())
887 return nullptr;
888
Silviu Barangac6d21eb2017-01-31 14:04:15 +0000889 // Make sure the pointers have the same type.
890 if (GEPLHS->getType() != RHS->getType())
891 return nullptr;
892
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000893 Value *PtrBase, *Index;
894 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
895
896 // The set of nodes that will take part in this transformation.
897 SetVector<Value *> Nodes;
898
899 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
900 return nullptr;
901
902 // We know we can re-write this as
903 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
904 // Since we've only looked through inbouds GEPs we know that we
905 // can't have overflow on either side. We can therefore re-write
906 // this as:
907 // OFFSET1 cmp OFFSET2
908 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
909
910 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
911 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
912 // offset. Since Index is the offset of LHS to the base pointer, we will now
913 // compare the offsets instead of comparing the pointers.
914 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
915}
916
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000917/// Fold comparisons between a GEP instruction and something else. At this point
918/// we know that the GEP is on the LHS of the comparison.
Sanjay Patel43395062016-07-21 18:07:40 +0000919Instruction *InstCombiner::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000920 ICmpInst::Predicate Cond,
921 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000922 // Don't transform signed compares of GEPs into index compares. Even if the
923 // GEP is inbounds, the final add of the base pointer can have signed overflow
924 // and would change the result of the icmp.
925 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000926 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000927 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000928 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000929
Matt Arsenault44f60d02014-06-09 19:20:29 +0000930 // Look through bitcasts and addrspacecasts. We do not however want to remove
931 // 0 GEPs.
932 if (!isa<GetElementPtrInst>(RHS))
933 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000934
935 Value *PtrBase = GEPLHS->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000936 if (PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000937 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
938 // This transformation (ignoring the base and scales) is valid because we
939 // know pointers can't overflow since the gep is inbounds. See if we can
940 // output an optimized form.
Sanjay Pateld93c4c02016-09-15 18:22:25 +0000941 Value *Offset = evaluateGEPOffsetExpression(GEPLHS, *this, DL);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000942
Chris Lattner2188e402010-01-04 07:37:31 +0000943 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000944 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000945 Offset = EmitGEPOffset(GEPLHS);
946 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
947 Constant::getNullValue(Offset->getType()));
948 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
949 // If the base pointers are different, but the indices are the same, just
950 // compare the base pointer.
951 if (PtrBase != GEPRHS->getOperand(0)) {
952 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
953 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
954 GEPRHS->getOperand(0)->getType();
955 if (IndicesTheSame)
956 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
957 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
958 IndicesTheSame = false;
959 break;
960 }
961
962 // If all indices are the same, just compare the base pointers.
963 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000964 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000965
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000966 // If we're comparing GEPs with two base pointers that only differ in type
967 // and both GEPs have only constant indices or just one use, then fold
968 // the compare with the adjusted indices.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000969 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000970 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
971 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
972 PtrBase->stripPointerCasts() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000973 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000974 Value *LOffset = EmitGEPOffset(GEPLHS);
975 Value *ROffset = EmitGEPOffset(GEPRHS);
976
977 // If we looked through an addrspacecast between different sized address
978 // spaces, the LHS and RHS pointers are different sized
979 // integers. Truncate to the smaller one.
980 Type *LHSIndexTy = LOffset->getType();
981 Type *RHSIndexTy = ROffset->getType();
982 if (LHSIndexTy != RHSIndexTy) {
983 if (LHSIndexTy->getPrimitiveSizeInBits() <
984 RHSIndexTy->getPrimitiveSizeInBits()) {
985 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
986 } else
987 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
988 }
989
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000990 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000991 LOffset, ROffset);
Sanjay Patel4b198802016-02-01 22:23:39 +0000992 return replaceInstUsesWith(I, Cmp);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000993 }
994
Chris Lattner2188e402010-01-04 07:37:31 +0000995 // Otherwise, the base pointers are different and the indices are
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000996 // different. Try convert this to an indexed compare by looking through
997 // PHIs/casts.
998 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +0000999 }
1000
1001 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001002 if (GEPLHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +00001003 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +00001004 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +00001005
1006 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001007 if (GEPRHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +00001008 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner2188e402010-01-04 07:37:31 +00001009
Stuart Hastings66a82b92011-05-14 05:55:10 +00001010 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +00001011 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
1012 // If the GEPs only differ by one index, compare it.
1013 unsigned NumDifferences = 0; // Keep track of # differences.
1014 unsigned DiffOperand = 0; // The operand that differs.
1015 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
1016 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
1017 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
1018 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
1019 // Irreconcilable differences.
1020 NumDifferences = 2;
1021 break;
1022 } else {
1023 if (NumDifferences++) break;
1024 DiffOperand = i;
1025 }
1026 }
1027
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +00001028 if (NumDifferences == 0) // SAME GEP?
Sanjay Patel4b198802016-02-01 22:23:39 +00001029 return replaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +00001030 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +00001031
Stuart Hastings66a82b92011-05-14 05:55:10 +00001032 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +00001033 Value *LHSV = GEPLHS->getOperand(DiffOperand);
1034 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1035 // Make sure we do a signed comparison here.
1036 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
1037 }
1038 }
1039
1040 // Only lower this if the icmp is the only user of the GEP or if we expect
1041 // the result to fold to a constant!
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001042 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner2188e402010-01-04 07:37:31 +00001043 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1044 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
1045 Value *L = EmitGEPOffset(GEPLHS);
1046 Value *R = EmitGEPOffset(GEPRHS);
1047 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1048 }
1049 }
Silviu Barangaf29dfd32016-01-15 15:52:05 +00001050
1051 // Try convert this to an indexed compare by looking through PHIs/casts as a
1052 // last resort.
1053 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +00001054}
1055
Pete Cooper980a9352016-08-12 17:13:28 +00001056Instruction *InstCombiner::foldAllocaCmp(ICmpInst &ICI,
1057 const AllocaInst *Alloca,
1058 const Value *Other) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001059 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1060
1061 // It would be tempting to fold away comparisons between allocas and any
1062 // pointer not based on that alloca (e.g. an argument). However, even
1063 // though such pointers cannot alias, they can still compare equal.
1064 //
1065 // But LLVM doesn't specify where allocas get their memory, so if the alloca
1066 // doesn't escape we can argue that it's impossible to guess its value, and we
1067 // can therefore act as if any such guesses are wrong.
1068 //
1069 // The code below checks that the alloca doesn't escape, and that it's only
1070 // used in a comparison once (the current instruction). The
1071 // single-comparison-use condition ensures that we're trivially folding all
1072 // comparisons against the alloca consistently, and avoids the risk of
1073 // erroneously folding a comparison of the pointer with itself.
1074
1075 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1076
Pete Cooper980a9352016-08-12 17:13:28 +00001077 SmallVector<const Use *, 32> Worklist;
1078 for (const Use &U : Alloca->uses()) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001079 if (Worklist.size() >= MaxIter)
1080 return nullptr;
1081 Worklist.push_back(&U);
1082 }
1083
1084 unsigned NumCmps = 0;
1085 while (!Worklist.empty()) {
1086 assert(Worklist.size() <= MaxIter);
Pete Cooper980a9352016-08-12 17:13:28 +00001087 const Use *U = Worklist.pop_back_val();
1088 const Value *V = U->getUser();
Hans Wennborgf1f36512015-10-07 00:20:07 +00001089 --MaxIter;
1090
1091 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1092 isa<SelectInst>(V)) {
1093 // Track the uses.
1094 } else if (isa<LoadInst>(V)) {
1095 // Loading from the pointer doesn't escape it.
1096 continue;
Pete Cooper980a9352016-08-12 17:13:28 +00001097 } else if (const auto *SI = dyn_cast<StoreInst>(V)) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001098 // Storing *to* the pointer is fine, but storing the pointer escapes it.
1099 if (SI->getValueOperand() == U->get())
1100 return nullptr;
1101 continue;
1102 } else if (isa<ICmpInst>(V)) {
1103 if (NumCmps++)
1104 return nullptr; // Found more than one cmp.
1105 continue;
Pete Cooper980a9352016-08-12 17:13:28 +00001106 } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001107 switch (Intrin->getIntrinsicID()) {
1108 // These intrinsics don't escape or compare the pointer. Memset is safe
1109 // because we don't allow ptrtoint. Memcpy and memmove are safe because
1110 // we don't allow stores, so src cannot point to V.
1111 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1112 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
1113 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1114 continue;
1115 default:
1116 return nullptr;
1117 }
1118 } else {
1119 return nullptr;
1120 }
Pete Cooper980a9352016-08-12 17:13:28 +00001121 for (const Use &U : V->uses()) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001122 if (Worklist.size() >= MaxIter)
1123 return nullptr;
1124 Worklist.push_back(&U);
1125 }
1126 }
1127
1128 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001129 return replaceInstUsesWith(
Hans Wennborgf1f36512015-10-07 00:20:07 +00001130 ICI,
1131 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1132}
1133
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001134/// Fold "icmp pred (X+CI), X".
Sanjay Patel43395062016-07-21 18:07:40 +00001135Instruction *InstCombiner::foldICmpAddOpConst(Instruction &ICI,
1136 Value *X, ConstantInt *CI,
1137 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +00001138 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001139 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +00001140 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +00001141
Chris Lattner8c92b572010-01-08 17:48:19 +00001142 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +00001143 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
1144 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
1145 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00001146 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +00001147 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +00001148 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1149 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001150
Chris Lattner2188e402010-01-04 07:37:31 +00001151 // (X+1) >u X --> X <u (0-1) --> X != 255
1152 // (X+2) >u X --> X <u (0-2) --> X <u 254
1153 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +00001154 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +00001155 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001156
Chris Lattner2188e402010-01-04 07:37:31 +00001157 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
1158 ConstantInt *SMax = ConstantInt::get(X->getContext(),
1159 APInt::getSignedMaxValue(BitWidth));
1160
1161 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1162 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1163 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1164 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1165 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1166 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +00001167 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +00001168 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001169
Chris Lattner2188e402010-01-04 07:37:31 +00001170 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1171 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1172 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1173 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1174 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1175 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +00001176
Chris Lattner2188e402010-01-04 07:37:31 +00001177 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +00001178 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +00001179 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
1180}
1181
Sanjay Patel8da42cc2016-09-15 22:26:31 +00001182/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
1183/// (icmp eq/ne A, Log2(AP2/AP1)) ->
1184/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
1185Instruction *InstCombiner::foldICmpShrConstConst(ICmpInst &I, Value *A,
1186 const APInt &AP1,
1187 const APInt &AP2) {
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001188 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1189
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001190 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
David Majnemer2abb8182014-10-25 07:13:13 +00001196 // Don't bother doing any work for cases which InstSimplify handles.
1197 if (AP2 == 0)
1198 return nullptr;
Sanjay Patel8da42cc2016-09-15 22:26:31 +00001199
1200 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
David Majnemer2abb8182014-10-25 07:13:13 +00001201 if (IsAShr) {
1202 if (AP2.isAllOnesValue())
1203 return nullptr;
1204 if (AP2.isNegative() != AP1.isNegative())
1205 return nullptr;
1206 if (AP2.sgt(AP1))
1207 return nullptr;
1208 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001209
David Majnemerd2056022014-10-21 19:51:55 +00001210 if (!AP1)
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001211 // 'A' must be large enough to shift out the highest set bit.
1212 return getICmp(I.ICMP_UGT, A,
1213 ConstantInt::get(A->getType(), AP2.logBase2()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001214
David Majnemerd2056022014-10-21 19:51:55 +00001215 if (AP1 == AP2)
1216 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001217
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001218 int Shift;
David Majnemerd2056022014-10-21 19:51:55 +00001219 if (IsAShr && AP1.isNegative())
David Majnemere5977eb2015-09-19 00:48:26 +00001220 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001221 else
David Majnemere5977eb2015-09-19 00:48:26 +00001222 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001223
David Majnemerd2056022014-10-21 19:51:55 +00001224 if (Shift > 0) {
David Majnemere5977eb2015-09-19 00:48:26 +00001225 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1226 // There are multiple solutions if we are comparing against -1 and the LHS
David Majnemer47ce0b82015-09-19 00:48:31 +00001227 // of the ashr is not a power of two.
David Majnemere5977eb2015-09-19 00:48:26 +00001228 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1229 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
David Majnemerd2056022014-10-21 19:51:55 +00001230 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
David Majnemere5977eb2015-09-19 00:48:26 +00001231 } else if (AP1 == AP2.lshr(Shift)) {
1232 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1233 }
David Majnemerd2056022014-10-21 19:51:55 +00001234 }
Sanjay Patel524fcdf2016-09-15 19:04:55 +00001235
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001236 // Shifting const2 will never be equal to const1.
Sanjay Patel524fcdf2016-09-15 19:04:55 +00001237 // FIXME: This should always be handled by InstSimplify?
1238 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1239 return replaceInstUsesWith(I, TorF);
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001240}
Chris Lattner2188e402010-01-04 07:37:31 +00001241
Sanjay Patel8da42cc2016-09-15 22:26:31 +00001242/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1243/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1244Instruction *InstCombiner::foldICmpShlConstConst(ICmpInst &I, Value *A,
1245 const APInt &AP1,
1246 const APInt &AP2) {
David Majnemer59939ac2014-10-19 08:23:08 +00001247 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1248
David Majnemer59939ac2014-10-19 08:23:08 +00001249 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1250 if (I.getPredicate() == I.ICMP_NE)
1251 Pred = CmpInst::getInversePredicate(Pred);
1252 return new ICmpInst(Pred, LHS, RHS);
1253 };
1254
David Majnemer2abb8182014-10-25 07:13:13 +00001255 // Don't bother doing any work for cases which InstSimplify handles.
1256 if (AP2 == 0)
1257 return nullptr;
David Majnemer59939ac2014-10-19 08:23:08 +00001258
1259 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1260
1261 if (!AP1 && AP2TrailingZeros != 0)
Sanjay Patelaf91d1f2016-09-15 21:35:30 +00001262 return getICmp(
1263 I.ICMP_UGE, A,
1264 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
David Majnemer59939ac2014-10-19 08:23:08 +00001265
1266 if (AP1 == AP2)
1267 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1268
1269 // Get the distance between the lowest bits that are set.
1270 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1271
1272 if (Shift > 0 && AP2.shl(Shift) == AP1)
1273 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1274
1275 // Shifting const2 will never be equal to const1.
Sanjay Patel524fcdf2016-09-15 19:04:55 +00001276 // FIXME: This should always be handled by InstSimplify?
1277 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1278 return replaceInstUsesWith(I, TorF);
David Majnemer59939ac2014-10-19 08:23:08 +00001279}
1280
Sanjay Patel06b127a2016-09-15 14:37:50 +00001281/// The caller has matched a pattern of the form:
1282/// I = icmp ugt (add (add A, B), CI2), CI1
1283/// If this is of the form:
1284/// sum = a + b
1285/// if (sum+128 >u 255)
1286/// Then replace it with llvm.sadd.with.overflow.i8.
1287///
Sanjay Pateld93c4c02016-09-15 18:22:25 +00001288static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
Sanjay Patel06b127a2016-09-15 14:37:50 +00001289 ConstantInt *CI2, ConstantInt *CI1,
1290 InstCombiner &IC) {
1291 // The transformation we're trying to do here is to transform this into an
1292 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1293 // with a narrower add, and discard the add-with-constant that is part of the
1294 // range check (if we can't eliminate it, this isn't profitable).
1295
1296 // In order to eliminate the add-with-constant, the compare can be its only
1297 // use.
1298 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1299 if (!AddWithCst->hasOneUse())
1300 return nullptr;
1301
1302 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1303 if (!CI2->getValue().isPowerOf2())
1304 return nullptr;
1305 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1306 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1307 return nullptr;
1308
1309 // The width of the new add formed is 1 more than the bias.
1310 ++NewWidth;
1311
1312 // Check to see that CI1 is an all-ones value with NewWidth bits.
1313 if (CI1->getBitWidth() == NewWidth ||
1314 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1315 return nullptr;
1316
1317 // This is only really a signed overflow check if the inputs have been
1318 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1319 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1320 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1321 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
1322 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
1323 return nullptr;
1324
1325 // In order to replace the original add with a narrower
1326 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1327 // and truncates that discard the high bits of the add. Verify that this is
1328 // the case.
1329 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1330 for (User *U : OrigAdd->users()) {
1331 if (U == AddWithCst)
1332 continue;
1333
1334 // Only accept truncates for now. We would really like a nice recursive
1335 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1336 // chain to see which bits of a value are actually demanded. If the
1337 // original add had another add which was then immediately truncated, we
1338 // could still do the transformation.
1339 TruncInst *TI = dyn_cast<TruncInst>(U);
1340 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1341 return nullptr;
1342 }
1343
1344 // If the pattern matches, truncate the inputs to the narrower type and
1345 // use the sadd_with_overflow intrinsic to efficiently compute both the
1346 // result and the overflow bit.
1347 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1348 Value *F = Intrinsic::getDeclaration(I.getModule(),
1349 Intrinsic::sadd_with_overflow, NewType);
1350
1351 InstCombiner::BuilderTy *Builder = IC.Builder;
1352
1353 // Put the new code above the original add, in case there are any uses of the
1354 // add between the add and the compare.
1355 Builder->SetInsertPoint(OrigAdd);
1356
1357 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName() + ".trunc");
1358 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName() + ".trunc");
1359 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
1360 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1361 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
1362
1363 // The inner add was the result of the narrow add, zero extended to the
1364 // wider type. Replace it with the result computed by the intrinsic.
1365 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1366
1367 // The original icmp gets replaced with the overflow value.
1368 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1369}
1370
1371// Fold icmp Pred X, C.
Sanjay Patel97459832016-09-15 15:11:12 +00001372Instruction *InstCombiner::foldICmpWithConstant(ICmpInst &Cmp) {
1373 CmpInst::Predicate Pred = Cmp.getPredicate();
Sanjay Patel40c53ea2016-09-15 16:23:20 +00001374 Value *X = Cmp.getOperand(0);
Sanjay Patel06b127a2016-09-15 14:37:50 +00001375
Sanjay Patel40c53ea2016-09-15 16:23:20 +00001376 const APInt *C;
1377 if (!match(Cmp.getOperand(1), m_APInt(C)))
Sanjay Patel97459832016-09-15 15:11:12 +00001378 return nullptr;
Sanjay Patel06b127a2016-09-15 14:37:50 +00001379
Sanjay Patel97459832016-09-15 15:11:12 +00001380 Value *A = nullptr, *B = nullptr;
Sanjay Patel06b127a2016-09-15 14:37:50 +00001381
Sanjay Patel97459832016-09-15 15:11:12 +00001382 // Match the following pattern, which is a common idiom when writing
1383 // overflow-safe integer arithmetic functions. The source performs an addition
1384 // in wider type and explicitly checks for overflow using comparisons against
1385 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1386 //
1387 // TODO: This could probably be generalized to handle other overflow-safe
1388 // operations if we worked out the formulas to compute the appropriate magic
1389 // constants.
1390 //
1391 // sum = a + b
1392 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1393 {
1394 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1395 if (Pred == ICmpInst::ICMP_UGT &&
1396 match(X, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Sanjay Pateld93c4c02016-09-15 18:22:25 +00001397 if (Instruction *Res = processUGT_ADDCST_ADD(
Sanjay Patel40c53ea2016-09-15 16:23:20 +00001398 Cmp, A, B, CI2, cast<ConstantInt>(Cmp.getOperand(1)), *this))
Sanjay Patel97459832016-09-15 15:11:12 +00001399 return Res;
1400 }
Sanjay Patel06b127a2016-09-15 14:37:50 +00001401
Sanjay Patel97459832016-09-15 15:11:12 +00001402 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
Sanjay Patel40c53ea2016-09-15 16:23:20 +00001403 if (*C == 0 && Pred == ICmpInst::ICMP_SGT) {
1404 SelectPatternResult SPR = matchSelectPattern(X, A, B);
1405 if (SPR.Flavor == SPF_SMIN) {
1406 if (isKnownPositive(A, DL))
1407 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1408 if (isKnownPositive(B, DL))
1409 return new ICmpInst(Pred, A, Cmp.getOperand(1));
Sanjay Patel06b127a2016-09-15 14:37:50 +00001410 }
Sanjay Patel40c53ea2016-09-15 16:23:20 +00001411 }
1412
1413 // FIXME: Use m_APInt to allow folds for splat constants.
1414 ConstantInt *CI = dyn_cast<ConstantInt>(Cmp.getOperand(1));
1415 if (!CI)
1416 return nullptr;
Sanjay Patel06b127a2016-09-15 14:37:50 +00001417
Sanjay Patel97459832016-09-15 15:11:12 +00001418 // Canonicalize icmp instructions based on dominating conditions.
1419 BasicBlock *Parent = Cmp.getParent();
1420 BasicBlock *Dom = Parent->getSinglePredecessor();
1421 auto *BI = Dom ? dyn_cast<BranchInst>(Dom->getTerminator()) : nullptr;
1422 ICmpInst::Predicate Pred2;
1423 BasicBlock *TrueBB, *FalseBB;
1424 ConstantInt *CI2;
1425 if (BI && match(BI, m_Br(m_ICmp(Pred2, m_Specific(X), m_ConstantInt(CI2)),
1426 TrueBB, FalseBB)) &&
1427 TrueBB != FalseBB) {
1428 ConstantRange CR =
1429 ConstantRange::makeAllowedICmpRegion(Pred, CI->getValue());
1430 ConstantRange DominatingCR =
1431 (Parent == TrueBB)
1432 ? ConstantRange::makeExactICmpRegion(Pred2, CI2->getValue())
1433 : ConstantRange::makeExactICmpRegion(
1434 CmpInst::getInversePredicate(Pred2), CI2->getValue());
1435 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1436 ConstantRange Difference = DominatingCR.difference(CR);
1437 if (Intersection.isEmptySet())
1438 return replaceInstUsesWith(Cmp, Builder->getFalse());
1439 if (Difference.isEmptySet())
1440 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel06b127a2016-09-15 14:37:50 +00001441
Sanjay Patel97459832016-09-15 15:11:12 +00001442 // If this is a normal comparison, it demands all bits. If it is a sign
1443 // bit comparison, it only demands the sign bit.
1444 bool UnusedBit;
1445 bool IsSignBit = isSignBitCheck(Pred, CI->getValue(), UnusedBit);
1446
1447 // Canonicalizing a sign bit comparison that gets used in a branch,
1448 // pessimizes codegen by generating branch on zero instruction instead
1449 // of a test and branch. So we avoid canonicalizing in such situations
1450 // because test and branch instruction has better branch displacement
1451 // than compare and branch instruction.
1452 if (!isBranchOnSignBitCheck(Cmp, IsSignBit) && !Cmp.isEquality()) {
1453 if (auto *AI = Intersection.getSingleElement())
1454 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder->getInt(*AI));
1455 if (auto *AD = Difference.getSingleElement())
1456 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder->getInt(*AD));
Sanjay Patel06b127a2016-09-15 14:37:50 +00001457 }
1458 }
1459
1460 return nullptr;
1461}
1462
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001463/// Fold icmp (trunc X, Y), C.
1464Instruction *InstCombiner::foldICmpTruncConstant(ICmpInst &Cmp,
1465 Instruction *Trunc,
1466 const APInt *C) {
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001467 ICmpInst::Predicate Pred = Cmp.getPredicate();
1468 Value *X = Trunc->getOperand(0);
Sanjay Patel40e8ca42016-08-18 20:28:54 +00001469 if (*C == 1 && C->getBitWidth() > 1) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001470 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1471 Value *V = nullptr;
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001472 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001473 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1474 ConstantInt::get(V->getType(), 1));
1475 }
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001476
1477 if (Cmp.isEquality() && Trunc->hasOneUse()) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001478 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1479 // of the high bits truncated out of x are known.
Sanjay Patel40e8ca42016-08-18 20:28:54 +00001480 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1481 SrcBits = X->getType()->getScalarSizeInBits();
Sanjay Patela3f4f082016-08-16 17:54:36 +00001482 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001483 computeKnownBits(X, KnownZero, KnownOne, 0, &Cmp);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001484
1485 // If all the high bits are known, we can do this xform.
1486 if ((KnownZero | KnownOne).countLeadingOnes() >= SrcBits - DstBits) {
1487 // Pull in the high bits from known-ones set.
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001488 APInt NewRHS = C->zext(SrcBits);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001489 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
Sanjay Patel40e8ca42016-08-18 20:28:54 +00001490 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), NewRHS));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001491 }
1492 }
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001493
Sanjay Patela3f4f082016-08-16 17:54:36 +00001494 return nullptr;
1495}
1496
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001497/// Fold icmp (xor X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001498Instruction *InstCombiner::foldICmpXorConstant(ICmpInst &Cmp,
1499 BinaryOperator *Xor,
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001500 const APInt *C) {
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001501 Value *X = Xor->getOperand(0);
1502 Value *Y = Xor->getOperand(1);
Sanjay Pateldaffec912016-08-17 19:45:18 +00001503 const APInt *XorC;
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001504 if (!match(Y, m_APInt(XorC)))
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001505 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001506
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001507 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1508 // fold the xor.
1509 ICmpInst::Predicate Pred = Cmp.getPredicate();
1510 if ((Pred == ICmpInst::ICMP_SLT && *C == 0) ||
1511 (Pred == ICmpInst::ICMP_SGT && C->isAllOnesValue())) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001512
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001513 // If the sign bit of the XorCst is not set, there is no change to
1514 // the operation, just stop using the Xor.
Sanjay Pateldaffec912016-08-17 19:45:18 +00001515 if (!XorC->isNegative()) {
1516 Cmp.setOperand(0, X);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001517 Worklist.Add(Xor);
1518 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001519 }
1520
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001521 // Was the old condition true if the operand is positive?
1522 bool isTrueIfPositive = Pred == ICmpInst::ICMP_SGT;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001523
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001524 // If so, the new one isn't.
1525 isTrueIfPositive ^= true;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001526
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001527 Constant *CmpConstant = cast<Constant>(Cmp.getOperand(1));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001528 if (isTrueIfPositive)
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001529 return new ICmpInst(ICmpInst::ICMP_SGT, X, SubOne(CmpConstant));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001530 else
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001531 return new ICmpInst(ICmpInst::ICMP_SLT, X, AddOne(CmpConstant));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001532 }
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001533
1534 if (Xor->hasOneUse()) {
Sanjay Pateldaffec912016-08-17 19:45:18 +00001535 // (icmp u/s (xor X SignBit), C) -> (icmp s/u X, (xor C SignBit))
1536 if (!Cmp.isEquality() && XorC->isSignBit()) {
1537 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1538 : Cmp.getSignedPredicate();
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001539 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001540 }
1541
Sanjay Pateldaffec912016-08-17 19:45:18 +00001542 // (icmp u/s (xor X ~SignBit), C) -> (icmp s/u X, (xor C ~SignBit))
1543 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1544 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1545 : Cmp.getSignedPredicate();
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001546 Pred = Cmp.getSwappedPredicate(Pred);
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001547 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001548 }
1549 }
1550
1551 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1552 // iff -C is a power of 2
Sanjay Pateldaffec912016-08-17 19:45:18 +00001553 if (Pred == ICmpInst::ICMP_UGT && *XorC == ~(*C) && (*C + 1).isPowerOf2())
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001554 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001555
1556 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1557 // iff -C is a power of 2
Sanjay Pateldaffec912016-08-17 19:45:18 +00001558 if (Pred == ICmpInst::ICMP_ULT && *XorC == -(*C) && C->isPowerOf2())
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001559 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001560
Sanjay Patela3f4f082016-08-16 17:54:36 +00001561 return nullptr;
1562}
1563
Sanjay Patel14e0e182016-08-26 18:28:46 +00001564/// Fold icmp (and (sh X, Y), C2), C1.
1565Instruction *InstCombiner::foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
Sanjay Patel9b40f982016-09-07 22:33:03 +00001566 const APInt *C1, const APInt *C2) {
1567 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1568 if (!Shift || !Shift->isShift())
Sanjay Patelda9c5622016-08-26 17:15:22 +00001569 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001570
Sanjay Patelda9c5622016-08-26 17:15:22 +00001571 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1572 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1573 // code produced by the clang front-end, for bitfield access.
Sanjay Patelda9c5622016-08-26 17:15:22 +00001574 // This seemingly simple opportunity to fold away a shift turns out to be
1575 // rather complicated. See PR17827 for details.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001576 unsigned ShiftOpcode = Shift->getOpcode();
1577 bool IsShl = ShiftOpcode == Instruction::Shl;
1578 const APInt *C3;
1579 if (match(Shift->getOperand(1), m_APInt(C3))) {
Sanjay Patelda9c5622016-08-26 17:15:22 +00001580 bool CanFold = false;
Sanjay Patelda9c5622016-08-26 17:15:22 +00001581 if (ShiftOpcode == Instruction::AShr) {
1582 // There may be some constraints that make this possible, but nothing
1583 // simple has been discovered yet.
1584 CanFold = false;
1585 } else if (ShiftOpcode == Instruction::Shl) {
1586 // For a left shift, we can fold if the comparison is not signed. We can
1587 // also fold a signed comparison if the mask value and comparison value
1588 // are not negative. These constraints may not be obvious, but we can
1589 // prove that they are correct using an SMT solver.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001590 if (!Cmp.isSigned() || (!C2->isNegative() && !C1->isNegative()))
Sanjay Patelda9c5622016-08-26 17:15:22 +00001591 CanFold = true;
1592 } else if (ShiftOpcode == Instruction::LShr) {
1593 // For a logical right shift, we can fold if the comparison is not signed.
1594 // We can also fold a signed comparison if the shifted mask value and the
1595 // shifted comparison value are not negative. These constraints may not be
1596 // obvious, but we can prove that they are correct using an SMT solver.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001597 if (!Cmp.isSigned() ||
1598 (!C2->shl(*C3).isNegative() && !C1->shl(*C3).isNegative()))
Sanjay Patelda9c5622016-08-26 17:15:22 +00001599 CanFold = true;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001600 }
1601
Sanjay Patelda9c5622016-08-26 17:15:22 +00001602 if (CanFold) {
Sanjay Patel9b40f982016-09-07 22:33:03 +00001603 APInt NewCst = IsShl ? C1->lshr(*C3) : C1->shl(*C3);
1604 APInt SameAsC1 = IsShl ? NewCst.shl(*C3) : NewCst.lshr(*C3);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001605 // Check to see if we are shifting out any of the bits being compared.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001606 if (SameAsC1 != *C1) {
Sanjay Patelda9c5622016-08-26 17:15:22 +00001607 // If we shifted bits out, the fold is not going to work out. As a
1608 // special case, check to see if this means that the result is always
1609 // true or false now.
1610 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
Sanjay Patel1c608f42016-09-08 16:54:02 +00001611 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
Sanjay Patelda9c5622016-08-26 17:15:22 +00001612 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
Sanjay Patel1c608f42016-09-08 16:54:02 +00001613 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001614 } else {
Sanjay Patel9b40f982016-09-07 22:33:03 +00001615 Cmp.setOperand(1, ConstantInt::get(And->getType(), NewCst));
1616 APInt NewAndCst = IsShl ? C2->lshr(*C3) : C2->shl(*C3);
1617 And->setOperand(1, ConstantInt::get(And->getType(), NewAndCst));
Sanjay Patelda9c5622016-08-26 17:15:22 +00001618 And->setOperand(0, Shift->getOperand(0));
1619 Worklist.Add(Shift); // Shift is dead.
1620 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001621 }
Sanjay Patelda9c5622016-08-26 17:15:22 +00001622 }
1623 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001624
Sanjay Patelda9c5622016-08-26 17:15:22 +00001625 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1626 // preferable because it allows the C2 << Y expression to be hoisted out of a
1627 // loop if Y is invariant and X is not.
Sanjay Patel14e0e182016-08-26 18:28:46 +00001628 if (Shift->hasOneUse() && *C1 == 0 && Cmp.isEquality() &&
Sanjay Patelda9c5622016-08-26 17:15:22 +00001629 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1630 // Compute C2 << Y.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001631 Value *NewShift =
1632 IsShl ? Builder->CreateLShr(And->getOperand(1), Shift->getOperand(1))
1633 : Builder->CreateShl(And->getOperand(1), Shift->getOperand(1));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001634
Sanjay Patelda9c5622016-08-26 17:15:22 +00001635 // Compute X & (C2 << Y).
Sanjay Patel9b40f982016-09-07 22:33:03 +00001636 Value *NewAnd = Builder->CreateAnd(Shift->getOperand(0), NewShift);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001637 Cmp.setOperand(0, NewAnd);
1638 return &Cmp;
1639 }
1640
Sanjay Patel14e0e182016-08-26 18:28:46 +00001641 return nullptr;
1642}
1643
1644/// Fold icmp (and X, C2), C1.
1645Instruction *InstCombiner::foldICmpAndConstConst(ICmpInst &Cmp,
1646 BinaryOperator *And,
1647 const APInt *C1) {
Sanjay Patel6b490972016-09-04 14:32:15 +00001648 const APInt *C2;
1649 if (!match(And->getOperand(1), m_APInt(C2)))
Sanjay Patel14e0e182016-08-26 18:28:46 +00001650 return nullptr;
1651
1652 if (!And->hasOneUse() || !And->getOperand(0)->hasOneUse())
1653 return nullptr;
1654
Sanjay Patel6b490972016-09-04 14:32:15 +00001655 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1656 // the input width without changing the value produced, eliminate the cast:
1657 //
1658 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1659 //
1660 // We can do this transformation if the constants do not have their sign bits
1661 // set or if it is an equality comparison. Extending a relational comparison
1662 // when we're checking the sign bit would not work.
1663 Value *W;
1664 if (match(And->getOperand(0), m_Trunc(m_Value(W))) &&
1665 (Cmp.isEquality() || (!C1->isNegative() && !C2->isNegative()))) {
1666 // TODO: Is this a good transform for vectors? Wider types may reduce
1667 // throughput. Should this transform be limited (even for scalars) by using
Sanjay Patel2217f752017-01-31 17:25:42 +00001668 // shouldChangeType()?
Sanjay Patel6b490972016-09-04 14:32:15 +00001669 if (!Cmp.getType()->isVectorTy()) {
1670 Type *WideType = W->getType();
1671 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1672 Constant *ZextC1 = ConstantInt::get(WideType, C1->zext(WideScalarBits));
1673 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1674 Value *NewAnd = Builder->CreateAnd(W, ZextC2, And->getName());
1675 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
Sanjay Patel14e0e182016-08-26 18:28:46 +00001676 }
1677 }
1678
Sanjay Patel9b40f982016-09-07 22:33:03 +00001679 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, C2))
Sanjay Patel14e0e182016-08-26 18:28:46 +00001680 return I;
1681
Sanjay Patelda9c5622016-08-26 17:15:22 +00001682 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
Sanjay Patel6b490972016-09-04 14:32:15 +00001683 // (icmp pred (and A, (or (shl 1, B), 1), 0))
Sanjay Patelda9c5622016-08-26 17:15:22 +00001684 //
1685 // iff pred isn't signed
Sanjay Pateldef931e2016-09-07 20:50:44 +00001686 if (!Cmp.isSigned() && *C1 == 0 && match(And->getOperand(1), m_One())) {
1687 Constant *One = cast<Constant>(And->getOperand(1));
1688 Value *Or = And->getOperand(0);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001689 Value *A, *B, *LShr;
Sanjay Pateldef931e2016-09-07 20:50:44 +00001690 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1691 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1692 unsigned UsesRemoved = 0;
1693 if (And->hasOneUse())
1694 ++UsesRemoved;
1695 if (Or->hasOneUse())
1696 ++UsesRemoved;
1697 if (LShr->hasOneUse())
1698 ++UsesRemoved;
1699
1700 // Compute A & ((1 << B) | 1)
1701 Value *NewOr = nullptr;
1702 if (auto *C = dyn_cast<Constant>(B)) {
1703 if (UsesRemoved >= 1)
1704 NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1705 } else {
1706 if (UsesRemoved >= 3)
1707 NewOr = Builder->CreateOr(Builder->CreateShl(One, B, LShr->getName(),
Sanjay Patelda9c5622016-08-26 17:15:22 +00001708 /*HasNUW=*/true),
1709 One, Or->getName());
Sanjay Pateldef931e2016-09-07 20:50:44 +00001710 }
1711 if (NewOr) {
1712 Value *NewAnd = Builder->CreateAnd(A, NewOr, And->getName());
1713 Cmp.setOperand(0, NewAnd);
1714 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001715 }
1716 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001717 }
Sanjay Patelda9c5622016-08-26 17:15:22 +00001718
Sanjay Pateldef931e2016-09-07 20:50:44 +00001719 // (X & C2) > C1 --> (X & C2) != 0, if any bit set in (X & C2) will produce a
1720 // result greater than C1.
1721 unsigned NumTZ = C2->countTrailingZeros();
1722 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && NumTZ < C2->getBitWidth() &&
1723 APInt::getOneBitSet(C2->getBitWidth(), NumTZ).ugt(*C1)) {
1724 Constant *Zero = Constant::getNullValue(And->getType());
1725 return new ICmpInst(ICmpInst::ICMP_NE, And, Zero);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001726 }
1727
Sanjay Pateld3c7bb282016-08-26 16:42:33 +00001728 return nullptr;
1729}
1730
1731/// Fold icmp (and X, Y), C.
1732Instruction *InstCombiner::foldICmpAndConstant(ICmpInst &Cmp,
1733 BinaryOperator *And,
1734 const APInt *C) {
1735 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1736 return I;
1737
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001738 // TODO: These all require that Y is constant too, so refactor with the above.
Sanjay Patela3f4f082016-08-16 17:54:36 +00001739
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001740 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1741 Value *X = And->getOperand(0);
1742 Value *Y = And->getOperand(1);
1743 if (auto *LI = dyn_cast<LoadInst>(X))
1744 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1745 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001746 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001747 !LI->isVolatile() && isa<ConstantInt>(Y)) {
1748 ConstantInt *C2 = cast<ConstantInt>(Y);
1749 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C2))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001750 return Res;
1751 }
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001752
1753 if (!Cmp.isEquality())
1754 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001755
1756 // X & -C == -C -> X > u ~C
1757 // X & -C != -C -> X <= u ~C
1758 // iff C is a power of 2
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001759 if (Cmp.getOperand(1) == Y && (-(*C)).isPowerOf2()) {
1760 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT
1761 : CmpInst::ICMP_ULE;
1762 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1763 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001764
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001765 // (X & C2) == 0 -> (trunc X) >= 0
1766 // (X & C2) != 0 -> (trunc X) < 0
1767 // iff C2 is a power of 2 and it masks the sign bit of a legal integer type.
1768 const APInt *C2;
1769 if (And->hasOneUse() && *C == 0 && match(Y, m_APInt(C2))) {
1770 int32_t ExactLogBase2 = C2->exactLogBase2();
1771 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1772 Type *NTy = IntegerType::get(Cmp.getContext(), ExactLogBase2 + 1);
1773 if (And->getType()->isVectorTy())
1774 NTy = VectorType::get(NTy, And->getType()->getVectorNumElements());
1775 Value *Trunc = Builder->CreateTrunc(X, NTy);
1776 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_SGE
1777 : CmpInst::ICMP_SLT;
1778 return new ICmpInst(NewPred, Trunc, Constant::getNullValue(NTy));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001779 }
1780 }
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001781
Sanjay Patela3f4f082016-08-16 17:54:36 +00001782 return nullptr;
1783}
1784
Sanjay Patel943e92e2016-08-17 16:30:43 +00001785/// Fold icmp (or X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001786Instruction *InstCombiner::foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
Sanjay Patel943e92e2016-08-17 16:30:43 +00001787 const APInt *C) {
Sanjay Patel943e92e2016-08-17 16:30:43 +00001788 ICmpInst::Predicate Pred = Cmp.getPredicate();
1789 if (*C == 1) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001790 // icmp slt signum(V) 1 --> icmp slt V, 1
1791 Value *V = nullptr;
Sanjay Patel943e92e2016-08-17 16:30:43 +00001792 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001793 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1794 ConstantInt::get(V->getType(), 1));
1795 }
1796
Sanjay Patel943e92e2016-08-17 16:30:43 +00001797 if (!Cmp.isEquality() || *C != 0 || !Or->hasOneUse())
Sanjay Patela3f4f082016-08-16 17:54:36 +00001798 return nullptr;
1799
1800 Value *P, *Q;
Sanjay Patel943e92e2016-08-17 16:30:43 +00001801 if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001802 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1803 // -> and (icmp eq P, null), (icmp eq Q, null).
Reid Klecknera871d382016-08-19 16:53:18 +00001804 Value *CmpP =
1805 Builder->CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
1806 Value *CmpQ =
1807 Builder->CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
Sanjay Patel943e92e2016-08-17 16:30:43 +00001808 auto LogicOpc = Pred == ICmpInst::Predicate::ICMP_EQ ? Instruction::And
1809 : Instruction::Or;
1810 return BinaryOperator::Create(LogicOpc, CmpP, CmpQ);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001811 }
Sanjay Patel943e92e2016-08-17 16:30:43 +00001812
Sanjay Patela3f4f082016-08-16 17:54:36 +00001813 return nullptr;
1814}
1815
Sanjay Patel63478072016-08-18 15:44:44 +00001816/// Fold icmp (mul X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001817Instruction *InstCombiner::foldICmpMulConstant(ICmpInst &Cmp,
1818 BinaryOperator *Mul,
Sanjay Patel63478072016-08-18 15:44:44 +00001819 const APInt *C) {
1820 const APInt *MulC;
1821 if (!match(Mul->getOperand(1), m_APInt(MulC)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001822 return nullptr;
1823
Sanjay Patel63478072016-08-18 15:44:44 +00001824 // If this is a test of the sign bit and the multiply is sign-preserving with
1825 // a constant operand, use the multiply LHS operand instead.
1826 ICmpInst::Predicate Pred = Cmp.getPredicate();
Sanjay Patelc9196c42016-08-22 21:24:29 +00001827 if (isSignTest(Pred, *C) && Mul->hasNoSignedWrap()) {
Sanjay Patel63478072016-08-18 15:44:44 +00001828 if (MulC->isNegative())
1829 Pred = ICmpInst::getSwappedPredicate(Pred);
1830 return new ICmpInst(Pred, Mul->getOperand(0),
1831 Constant::getNullValue(Mul->getType()));
1832 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001833
1834 return nullptr;
1835}
1836
Sanjay Patel98cd99d2016-08-18 21:28:30 +00001837/// Fold icmp (shl 1, Y), C.
1838static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl,
1839 const APInt *C) {
1840 Value *Y;
1841 if (!match(Shl, m_Shl(m_One(), m_Value(Y))))
1842 return nullptr;
1843
1844 Type *ShiftType = Shl->getType();
1845 uint32_t TypeBits = C->getBitWidth();
1846 bool CIsPowerOf2 = C->isPowerOf2();
1847 ICmpInst::Predicate Pred = Cmp.getPredicate();
1848 if (Cmp.isUnsigned()) {
1849 // (1 << Y) pred C -> Y pred Log2(C)
1850 if (!CIsPowerOf2) {
1851 // (1 << Y) < 30 -> Y <= 4
1852 // (1 << Y) <= 30 -> Y <= 4
1853 // (1 << Y) >= 30 -> Y > 4
1854 // (1 << Y) > 30 -> Y > 4
1855 if (Pred == ICmpInst::ICMP_ULT)
1856 Pred = ICmpInst::ICMP_ULE;
1857 else if (Pred == ICmpInst::ICMP_UGE)
1858 Pred = ICmpInst::ICMP_UGT;
1859 }
1860
1861 // (1 << Y) >= 2147483648 -> Y >= 31 -> Y == 31
1862 // (1 << Y) < 2147483648 -> Y < 31 -> Y != 31
1863 unsigned CLog2 = C->logBase2();
1864 if (CLog2 == TypeBits - 1) {
1865 if (Pred == ICmpInst::ICMP_UGE)
1866 Pred = ICmpInst::ICMP_EQ;
1867 else if (Pred == ICmpInst::ICMP_ULT)
1868 Pred = ICmpInst::ICMP_NE;
1869 }
1870 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
1871 } else if (Cmp.isSigned()) {
1872 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
1873 if (C->isAllOnesValue()) {
1874 // (1 << Y) <= -1 -> Y == 31
1875 if (Pred == ICmpInst::ICMP_SLE)
1876 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
1877
1878 // (1 << Y) > -1 -> Y != 31
1879 if (Pred == ICmpInst::ICMP_SGT)
1880 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
1881 } else if (!(*C)) {
1882 // (1 << Y) < 0 -> Y == 31
1883 // (1 << Y) <= 0 -> Y == 31
1884 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1885 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
1886
1887 // (1 << Y) >= 0 -> Y != 31
1888 // (1 << Y) > 0 -> Y != 31
1889 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1890 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
1891 }
1892 } else if (Cmp.isEquality() && CIsPowerOf2) {
1893 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, C->logBase2()));
1894 }
1895
1896 return nullptr;
1897}
1898
Sanjay Patel38b75062016-08-19 17:20:37 +00001899/// Fold icmp (shl X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001900Instruction *InstCombiner::foldICmpShlConstant(ICmpInst &Cmp,
1901 BinaryOperator *Shl,
Sanjay Patel38b75062016-08-19 17:20:37 +00001902 const APInt *C) {
Sanjay Patel8da42cc2016-09-15 22:26:31 +00001903 const APInt *ShiftVal;
1904 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
1905 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), *C, *ShiftVal);
1906
Sanjay Patelfa7de602016-08-19 22:33:26 +00001907 const APInt *ShiftAmt;
1908 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
Sanjay Patel38b75062016-08-19 17:20:37 +00001909 return foldICmpShlOne(Cmp, Shl, C);
Sanjay Patela867afe2016-08-19 16:12:16 +00001910
Sanjay Patel38b75062016-08-19 17:20:37 +00001911 // Check that the shift amount is in range. If not, don't perform undefined
Sanjay Patel940c0612017-01-09 16:27:56 +00001912 // shifts. When the shift is visited, it will be simplified.
Sanjay Patel38b75062016-08-19 17:20:37 +00001913 unsigned TypeBits = C->getBitWidth();
Sanjay Patelfa7de602016-08-19 22:33:26 +00001914 if (ShiftAmt->uge(TypeBits))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001915 return nullptr;
1916
Sanjay Patele38e79c2016-08-19 17:34:05 +00001917 ICmpInst::Predicate Pred = Cmp.getPredicate();
1918 Value *X = Shl->getOperand(0);
Sanjay Patel14715b32017-01-17 21:25:16 +00001919 Type *ShType = Shl->getType();
1920
Sanjay Patel291c3d82017-01-19 16:12:10 +00001921 // NSW guarantees that we are only shifting out sign bits from the high bits,
1922 // so we can ASHR the compare constant without needing a mask and eliminate
1923 // the shift.
1924 if (Shl->hasNoSignedWrap()) {
1925 if (Pred == ICmpInst::ICMP_SGT) {
1926 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
1927 APInt ShiftedC = C->ashr(*ShiftAmt);
1928 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
1929 }
1930 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) {
1931 // This is the same code as the SGT case, but assert the pre-condition
1932 // that is needed for this to work with equality predicates.
1933 assert(C->ashr(*ShiftAmt).shl(*ShiftAmt) == *C &&
1934 "Compare known true or false was not folded");
1935 APInt ShiftedC = C->ashr(*ShiftAmt);
1936 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
1937 }
1938 if (Pred == ICmpInst::ICMP_SLT) {
1939 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
1940 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
1941 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
1942 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
1943 assert(!C->isMinSignedValue() && "Unexpected icmp slt");
1944 APInt ShiftedC = (*C - 1).ashr(*ShiftAmt) + 1;
1945 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
1946 }
1947 // If this is a signed comparison to 0 and the shift is sign preserving,
1948 // use the shift LHS operand instead; isSignTest may change 'Pred', so only
1949 // do that if we're sure to not continue on in this function.
1950 if (isSignTest(Pred, *C))
1951 return new ICmpInst(Pred, X, Constant::getNullValue(ShType));
1952 }
Sanjay Patel14715b32017-01-17 21:25:16 +00001953
Sanjay Patel291c3d82017-01-19 16:12:10 +00001954 // NUW guarantees that we are only shifting out zero bits from the high bits,
1955 // so we can LSHR the compare constant without needing a mask and eliminate
1956 // the shift.
Sanjay Patel14715b32017-01-17 21:25:16 +00001957 if (Shl->hasNoUnsignedWrap()) {
Sanjay Patelae23d652017-01-18 21:16:12 +00001958 if (Pred == ICmpInst::ICMP_UGT) {
Sanjay Patel14715b32017-01-17 21:25:16 +00001959 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
1960 APInt ShiftedC = C->lshr(*ShiftAmt);
1961 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
1962 }
Sanjay Patelae23d652017-01-18 21:16:12 +00001963 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) {
1964 // This is the same code as the UGT case, but assert the pre-condition
1965 // that is needed for this to work with equality predicates.
1966 assert(C->lshr(*ShiftAmt).shl(*ShiftAmt) == *C &&
1967 "Compare known true or false was not folded");
1968 APInt ShiftedC = C->lshr(*ShiftAmt);
1969 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
1970 }
Sanjay Patel14715b32017-01-17 21:25:16 +00001971 if (Pred == ICmpInst::ICMP_ULT) {
1972 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
1973 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
1974 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
1975 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
1976 assert(C->ugt(0) && "ult 0 should have been eliminated");
1977 APInt ShiftedC = (*C - 1).lshr(*ShiftAmt) + 1;
1978 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
1979 }
1980 }
1981
Sanjay Patel291c3d82017-01-19 16:12:10 +00001982 if (Cmp.isEquality() && Shl->hasOneUse()) {
1983 // Strength-reduce the shift into an 'and'.
1984 Constant *Mask = ConstantInt::get(
1985 ShType,
1986 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
1987 Value *And = Builder->CreateAnd(X, Mask, Shl->getName() + ".mask");
Sanjay Patel14715b32017-01-17 21:25:16 +00001988 Constant *LShrC = ConstantInt::get(ShType, C->lshr(*ShiftAmt));
Sanjay Patel291c3d82017-01-19 16:12:10 +00001989 return new ICmpInst(Pred, And, LShrC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001990 }
1991
Sanjay Patela3f4f082016-08-16 17:54:36 +00001992 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1993 bool TrueIfSigned = false;
Sanjay Patel79263662016-08-21 15:07:45 +00001994 if (Shl->hasOneUse() && isSignBitCheck(Pred, *C, TrueIfSigned)) {
Sanjay Patel7ffcde72016-08-21 16:35:34 +00001995 // (X << 31) <s 0 --> (X & 1) != 0
Sanjay Patela3f4f082016-08-16 17:54:36 +00001996 Constant *Mask = ConstantInt::get(
Sanjay Patel14715b32017-01-17 21:25:16 +00001997 ShType,
Sanjay Patelfa7de602016-08-19 22:33:26 +00001998 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
Sanjay Patele38e79c2016-08-19 17:34:05 +00001999 Value *And = Builder->CreateAnd(X, Mask, Shl->getName() + ".mask");
Sanjay Patela3f4f082016-08-16 17:54:36 +00002000 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Sanjay Patel14715b32017-01-17 21:25:16 +00002001 And, Constant::getNullValue(ShType));
Sanjay Patelc0339c72016-11-01 19:19:29 +00002002 }
2003
Sanjay Patel643d21a2016-08-21 17:10:07 +00002004 // Transform (icmp pred iM (shl iM %v, N), C)
2005 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2006 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
Sanjay Patel940c0612017-01-09 16:27:56 +00002007 // This enables us to get rid of the shift in favor of a trunc that may be
Sanjay Patela3f4f082016-08-16 17:54:36 +00002008 // free on the target. It has the additional benefit of comparing to a
Sanjay Patel940c0612017-01-09 16:27:56 +00002009 // smaller constant that may be more target-friendly.
Sanjay Patelfa7de602016-08-19 22:33:26 +00002010 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
Sanjay Patelf3dda132016-10-25 20:11:47 +00002011 if (Shl->hasOneUse() && Amt != 0 && C->countTrailingZeros() >= Amt &&
2012 DL.isLegalInteger(TypeBits - Amt)) {
Sanjay Patel643d21a2016-08-21 17:10:07 +00002013 Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt);
Sanjay Patel14715b32017-01-17 21:25:16 +00002014 if (ShType->isVectorTy())
2015 TruncTy = VectorType::get(TruncTy, ShType->getVectorNumElements());
Sanjay Patel643d21a2016-08-21 17:10:07 +00002016 Constant *NewC =
2017 ConstantInt::get(TruncTy, C->ashr(*ShiftAmt).trunc(TypeBits - Amt));
2018 return new ICmpInst(Pred, Builder->CreateTrunc(X, TruncTy), NewC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00002019 }
2020
2021 return nullptr;
2022}
2023
Sanjay Patela3920492016-08-22 20:45:06 +00002024/// Fold icmp ({al}shr X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00002025Instruction *InstCombiner::foldICmpShrConstant(ICmpInst &Cmp,
2026 BinaryOperator *Shr,
2027 const APInt *C) {
Sanjay Patela3920492016-08-22 20:45:06 +00002028 // An exact shr only shifts out zero bits, so:
2029 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
Sanjay Pateld64e9882016-08-23 22:05:55 +00002030 Value *X = Shr->getOperand(0);
Sanjay Patelc9196c42016-08-22 21:24:29 +00002031 CmpInst::Predicate Pred = Cmp.getPredicate();
2032 if (Cmp.isEquality() && Shr->isExact() && Shr->hasOneUse() && *C == 0)
Sanjay Pateld64e9882016-08-23 22:05:55 +00002033 return new ICmpInst(Pred, X, Cmp.getOperand(1));
Sanjay Patela3920492016-08-22 20:45:06 +00002034
Sanjay Patel8da42cc2016-09-15 22:26:31 +00002035 const APInt *ShiftVal;
2036 if (Cmp.isEquality() && match(Shr->getOperand(0), m_APInt(ShiftVal)))
2037 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), *C, *ShiftVal);
2038
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002039 const APInt *ShiftAmt;
2040 if (!match(Shr->getOperand(1), m_APInt(ShiftAmt)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00002041 return nullptr;
2042
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002043 // Check that the shift amount is in range. If not, don't perform undefined
2044 // shifts. When the shift is visited it will be simplified.
2045 unsigned TypeBits = C->getBitWidth();
2046 unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002047 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2048 return nullptr;
2049
Sanjay Pateld64e9882016-08-23 22:05:55 +00002050 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002051 if (!Cmp.isEquality()) {
2052 // If we have an unsigned comparison and an ashr, we can't simplify this.
2053 // Similarly for signed comparisons with lshr.
Sanjay Pateld64e9882016-08-23 22:05:55 +00002054 if (Cmp.isSigned() != IsAShr)
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002055 return nullptr;
2056
2057 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
2058 // by a power of 2. Since we already have logic to simplify these,
2059 // transform to div and then simplify the resultant comparison.
Sanjay Pateld64e9882016-08-23 22:05:55 +00002060 if (IsAShr && (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002061 return nullptr;
2062
2063 // Revisit the shift (to delete it).
2064 Worklist.Add(Shr);
2065
2066 Constant *DivCst = ConstantInt::get(
2067 Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
2068
Sanjay Pateld64e9882016-08-23 22:05:55 +00002069 Value *Tmp = IsAShr ? Builder->CreateSDiv(X, DivCst, "", Shr->isExact())
2070 : Builder->CreateUDiv(X, DivCst, "", Shr->isExact());
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002071
2072 Cmp.setOperand(0, Tmp);
2073
2074 // If the builder folded the binop, just return it.
2075 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
2076 if (!TheDiv)
2077 return &Cmp;
2078
2079 // Otherwise, fold this div/compare.
2080 assert(TheDiv->getOpcode() == Instruction::SDiv ||
2081 TheDiv->getOpcode() == Instruction::UDiv);
2082
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002083 Instruction *Res = foldICmpDivConstant(Cmp, TheDiv, C);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002084 assert(Res && "This div/cst should have folded!");
Sanjay Patela3920492016-08-22 20:45:06 +00002085 return Res;
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002086 }
2087
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002088 // Handle equality comparisons of shift-by-constant.
2089
Sanjay Patel8e297742016-08-24 13:55:55 +00002090 // If the comparison constant changes with the shift, the comparison cannot
2091 // succeed (bits of the comparison constant cannot match the shifted value).
2092 // This should be known by InstSimplify and already be folded to true/false.
2093 assert(((IsAShr && C->shl(ShAmtVal).ashr(ShAmtVal) == *C) ||
2094 (!IsAShr && C->shl(ShAmtVal).lshr(ShAmtVal) == *C)) &&
2095 "Expected icmp+shr simplify did not occur.");
2096
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002097 // Check if the bits shifted out are known to be zero. If so, we can compare
2098 // against the unshifted value:
2099 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002100 Constant *ShiftedCmpRHS = ConstantInt::get(Shr->getType(), *C << ShAmtVal);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002101 if (Shr->hasOneUse()) {
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002102 if (Shr->isExact())
2103 return new ICmpInst(Pred, X, ShiftedCmpRHS);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002104
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002105 // Otherwise strength reduce the shift into an 'and'.
2106 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2107 Constant *Mask = ConstantInt::get(Shr->getType(), Val);
Sanjay Pateld64e9882016-08-23 22:05:55 +00002108 Value *And = Builder->CreateAnd(X, Mask, Shr->getName() + ".mask");
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002109 return new ICmpInst(Pred, And, ShiftedCmpRHS);
2110 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002111
2112 return nullptr;
2113}
2114
Sanjay Patel12a41052016-08-18 17:37:26 +00002115/// Fold icmp (udiv X, Y), C.
2116Instruction *InstCombiner::foldICmpUDivConstant(ICmpInst &Cmp,
Sanjay Patelc9196c42016-08-22 21:24:29 +00002117 BinaryOperator *UDiv,
Sanjay Patel12a41052016-08-18 17:37:26 +00002118 const APInt *C) {
Sanjay Patelfa5ca2b2016-08-18 17:55:59 +00002119 const APInt *C2;
2120 if (!match(UDiv->getOperand(0), m_APInt(C2)))
2121 return nullptr;
2122
2123 assert(C2 != 0 && "udiv 0, X should have been simplified already.");
2124
2125 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2126 Value *Y = UDiv->getOperand(1);
2127 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT) {
2128 assert(!C->isMaxValue() &&
2129 "icmp ugt X, UINT_MAX should have been simplified already.");
2130 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2131 ConstantInt::get(Y->getType(), C2->udiv(*C + 1)));
2132 }
2133
2134 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2135 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT) {
2136 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2137 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2138 ConstantInt::get(Y->getType(), C2->udiv(*C)));
Sanjay Patela3f4f082016-08-16 17:54:36 +00002139 }
2140
2141 return nullptr;
2142}
2143
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002144/// Fold icmp ({su}div X, Y), C.
2145Instruction *InstCombiner::foldICmpDivConstant(ICmpInst &Cmp,
2146 BinaryOperator *Div,
2147 const APInt *C) {
Sanjay Patela7cb4772016-08-30 17:10:49 +00002148 // Fold: icmp pred ([us]div X, C2), C -> range test
Sanjay Patela3f4f082016-08-16 17:54:36 +00002149 // Fold this div into the comparison, producing a range check.
2150 // Determine, based on the divide type, what the range is being
2151 // checked. If there is an overflow on the low or high side, remember
2152 // it, otherwise compute the range [low, hi) bounding the new value.
2153 // See: InsertRangeTest above for the kinds of replacements possible.
Sanjay Patela7cb4772016-08-30 17:10:49 +00002154 const APInt *C2;
2155 if (!match(Div->getOperand(1), m_APInt(C2)))
Sanjay Patel16554142016-08-24 23:03:36 +00002156 return nullptr;
2157
Sanjay Patel16554142016-08-24 23:03:36 +00002158 // FIXME: If the operand types don't match the type of the divide
2159 // then don't attempt this transform. The code below doesn't have the
2160 // logic to deal with a signed divide and an unsigned compare (and
Sanjay Patela7cb4772016-08-30 17:10:49 +00002161 // vice versa). This is because (x /s C2) <s C produces different
2162 // results than (x /s C2) <u C or (x /u C2) <s C or even
2163 // (x /u C2) <u C. Simply casting the operands and result won't
Sanjay Patel16554142016-08-24 23:03:36 +00002164 // work. :( The if statement below tests that condition and bails
2165 // if it finds it.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002166 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2167 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
Sanjay Patel16554142016-08-24 23:03:36 +00002168 return nullptr;
Sanjay Patela7cb4772016-08-30 17:10:49 +00002169
Sanjay Pateleea2ef72016-09-05 23:38:22 +00002170 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2171 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2172 // division-by-constant cases should be present, we can not assert that they
2173 // have happened before we reach this icmp instruction.
2174 if (*C2 == 0 || *C2 == 1 || (DivIsSigned && C2->isAllOnesValue()))
2175 return nullptr;
Sanjay Patelb3714572016-08-30 17:31:34 +00002176
Sanjay Patel541aef42016-08-31 21:57:21 +00002177 // TODO: We could do all of the computations below using APInt.
2178 Constant *CmpRHS = cast<Constant>(Cmp.getOperand(1));
2179 Constant *DivRHS = cast<Constant>(Div->getOperand(1));
Sanjay Patelb3714572016-08-30 17:31:34 +00002180
Sanjay Patel541aef42016-08-31 21:57:21 +00002181 // Compute Prod = CmpRHS * DivRHS. We are essentially solving an equation of
2182 // form X / C2 = C. We solve for X by multiplying C2 (DivRHS) and C (CmpRHS).
2183 // By solving for X, we can turn this into a range check instead of computing
2184 // a divide.
2185 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Sanjay Patel16554142016-08-24 23:03:36 +00002186
Sanjay Patel541aef42016-08-31 21:57:21 +00002187 // Determine if the product overflows by seeing if the product is not equal to
2188 // the divide. Make sure we do the same kind of divide as in the LHS
2189 // instruction that we're folding.
2190 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS)
2191 : ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Sanjay Patel16554142016-08-24 23:03:36 +00002192
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002193 ICmpInst::Predicate Pred = Cmp.getPredicate();
Sanjay Patel16554142016-08-24 23:03:36 +00002194
2195 // If the division is known to be exact, then there is no remainder from the
2196 // divide, so the covered range size is unit, otherwise it is the divisor.
Sanjay Patel541aef42016-08-31 21:57:21 +00002197 Constant *RangeSize =
2198 Div->isExact() ? ConstantInt::get(Div->getType(), 1) : DivRHS;
Sanjay Patel16554142016-08-24 23:03:36 +00002199
2200 // Figure out the interval that is being checked. For example, a comparison
2201 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2202 // Compute this interval based on the constants involved and the signedness of
2203 // the compare/divide. This computes a half-open interval, keeping track of
2204 // whether either value in the interval overflows. After analysis each
2205 // overflow variable is set to 0 if it's corresponding bound variable is valid
2206 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2207 int LoOverflow = 0, HiOverflow = 0;
2208 Constant *LoBound = nullptr, *HiBound = nullptr;
2209
2210 if (!DivIsSigned) { // udiv
2211 // e.g. X/5 op 3 --> [15, 20)
2212 LoBound = Prod;
2213 HiOverflow = LoOverflow = ProdOV;
2214 if (!HiOverflow) {
2215 // If this is not an exact divide, then many values in the range collapse
2216 // to the same result value.
Sanjay Pateld93c4c02016-09-15 18:22:25 +00002217 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
Sanjay Patel16554142016-08-24 23:03:36 +00002218 }
Sanjay Patel541aef42016-08-31 21:57:21 +00002219 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002220 if (*C == 0) { // (X / pos) op 0
Sanjay Patel16554142016-08-24 23:03:36 +00002221 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2222 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
2223 HiBound = RangeSize;
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002224 } else if (C->isStrictlyPositive()) { // (X / pos) op pos
Sanjay Patel16554142016-08-24 23:03:36 +00002225 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2226 HiOverflow = LoOverflow = ProdOV;
2227 if (!HiOverflow)
Sanjay Pateld93c4c02016-09-15 18:22:25 +00002228 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
Sanjay Patel16554142016-08-24 23:03:36 +00002229 } else { // (X / pos) op neg
2230 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2231 HiBound = AddOne(Prod);
2232 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2233 if (!LoOverflow) {
Sanjay Patel541aef42016-08-31 21:57:21 +00002234 Constant *DivNeg = ConstantExpr::getNeg(RangeSize);
Sanjay Pateld93c4c02016-09-15 18:22:25 +00002235 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Sanjay Patel16554142016-08-24 23:03:36 +00002236 }
2237 }
Sanjay Patel541aef42016-08-31 21:57:21 +00002238 } else if (C2->isNegative()) { // Divisor is < 0.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002239 if (Div->isExact())
Sanjay Patel541aef42016-08-31 21:57:21 +00002240 RangeSize = ConstantExpr::getNeg(RangeSize);
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002241 if (*C == 0) { // (X / neg) op 0
Sanjay Patel16554142016-08-24 23:03:36 +00002242 // e.g. X/-5 op 0 --> [-4, 5)
2243 LoBound = AddOne(RangeSize);
Sanjay Patel541aef42016-08-31 21:57:21 +00002244 HiBound = ConstantExpr::getNeg(RangeSize);
Sanjay Patel16554142016-08-24 23:03:36 +00002245 if (HiBound == DivRHS) { // -INTMIN = INTMIN
2246 HiOverflow = 1; // [INTMIN+1, overflow)
2247 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
2248 }
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002249 } else if (C->isStrictlyPositive()) { // (X / neg) op pos
Sanjay Patel16554142016-08-24 23:03:36 +00002250 // e.g. X/-5 op 3 --> [-19, -14)
2251 HiBound = AddOne(Prod);
2252 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2253 if (!LoOverflow)
Sanjay Pateld93c4c02016-09-15 18:22:25 +00002254 LoOverflow = addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Sanjay Patel16554142016-08-24 23:03:36 +00002255 } else { // (X / neg) op neg
2256 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2257 LoOverflow = HiOverflow = ProdOV;
2258 if (!HiOverflow)
Sanjay Pateld93c4c02016-09-15 18:22:25 +00002259 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
Sanjay Patel16554142016-08-24 23:03:36 +00002260 }
2261
2262 // Dividing by a negative swaps the condition. LT <-> GT
2263 Pred = ICmpInst::getSwappedPredicate(Pred);
2264 }
2265
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002266 Value *X = Div->getOperand(0);
Sanjay Patel16554142016-08-24 23:03:36 +00002267 switch (Pred) {
2268 default: llvm_unreachable("Unhandled icmp opcode!");
2269 case ICmpInst::ICMP_EQ:
2270 if (LoOverflow && HiOverflow)
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002271 return replaceInstUsesWith(Cmp, Builder->getFalse());
Sanjay Patel16554142016-08-24 23:03:36 +00002272 if (HiOverflow)
2273 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2274 ICmpInst::ICMP_UGE, X, LoBound);
2275 if (LoOverflow)
2276 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2277 ICmpInst::ICMP_ULT, X, HiBound);
Sanjay Patel85d79742016-08-31 19:49:56 +00002278 return replaceInstUsesWith(
Sanjay Patel541aef42016-08-31 21:57:21 +00002279 Cmp, insertRangeTest(X, LoBound->getUniqueInteger(),
2280 HiBound->getUniqueInteger(), DivIsSigned, true));
Sanjay Patel16554142016-08-24 23:03:36 +00002281 case ICmpInst::ICMP_NE:
2282 if (LoOverflow && HiOverflow)
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002283 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel16554142016-08-24 23:03:36 +00002284 if (HiOverflow)
2285 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2286 ICmpInst::ICMP_ULT, X, LoBound);
2287 if (LoOverflow)
2288 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2289 ICmpInst::ICMP_UGE, X, HiBound);
Sanjay Patel541aef42016-08-31 21:57:21 +00002290 return replaceInstUsesWith(Cmp,
2291 insertRangeTest(X, LoBound->getUniqueInteger(),
2292 HiBound->getUniqueInteger(),
2293 DivIsSigned, false));
Sanjay Patel16554142016-08-24 23:03:36 +00002294 case ICmpInst::ICMP_ULT:
2295 case ICmpInst::ICMP_SLT:
2296 if (LoOverflow == +1) // Low bound is greater than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002297 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel16554142016-08-24 23:03:36 +00002298 if (LoOverflow == -1) // Low bound is less than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002299 return replaceInstUsesWith(Cmp, Builder->getFalse());
Sanjay Patel16554142016-08-24 23:03:36 +00002300 return new ICmpInst(Pred, X, LoBound);
2301 case ICmpInst::ICMP_UGT:
2302 case ICmpInst::ICMP_SGT:
2303 if (HiOverflow == +1) // High bound greater than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002304 return replaceInstUsesWith(Cmp, Builder->getFalse());
Sanjay Patel16554142016-08-24 23:03:36 +00002305 if (HiOverflow == -1) // High bound less than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002306 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel16554142016-08-24 23:03:36 +00002307 if (Pred == ICmpInst::ICMP_UGT)
2308 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
2309 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
2310 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002311
2312 return nullptr;
2313}
2314
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002315/// Fold icmp (sub X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00002316Instruction *InstCombiner::foldICmpSubConstant(ICmpInst &Cmp,
2317 BinaryOperator *Sub,
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002318 const APInt *C) {
Sanjay Patel886a5422016-09-15 18:05:17 +00002319 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
2320 ICmpInst::Predicate Pred = Cmp.getPredicate();
2321
2322 // The following transforms are only worth it if the only user of the subtract
2323 // is the icmp.
2324 if (!Sub->hasOneUse())
Sanjay Patela3f4f082016-08-16 17:54:36 +00002325 return nullptr;
2326
Sanjay Patel886a5422016-09-15 18:05:17 +00002327 if (Sub->hasNoSignedWrap()) {
2328 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
2329 if (Pred == ICmpInst::ICMP_SGT && C->isAllOnesValue())
2330 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
Sanjay Patela3f4f082016-08-16 17:54:36 +00002331
Sanjay Patel886a5422016-09-15 18:05:17 +00002332 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
2333 if (Pred == ICmpInst::ICMP_SGT && *C == 0)
2334 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
2335
2336 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
2337 if (Pred == ICmpInst::ICMP_SLT && *C == 0)
2338 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
2339
2340 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
2341 if (Pred == ICmpInst::ICMP_SLT && *C == 1)
2342 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
2343 }
2344
2345 const APInt *C2;
2346 if (!match(X, m_APInt(C2)))
2347 return nullptr;
2348
2349 // C2 - Y <u C -> (Y | (C - 1)) == C2
2350 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
2351 if (Pred == ICmpInst::ICMP_ULT && C->isPowerOf2() &&
2352 (*C2 & (*C - 1)) == (*C - 1))
2353 return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateOr(Y, *C - 1), X);
2354
2355 // C2 - Y >u C -> (Y | C) != C2
2356 // iff C2 & C == C and C + 1 is a power of 2
2357 if (Pred == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() && (*C2 & *C) == *C)
2358 return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateOr(Y, *C), X);
Sanjay Patela3f4f082016-08-16 17:54:36 +00002359
2360 return nullptr;
2361}
2362
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002363/// Fold icmp (add X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00002364Instruction *InstCombiner::foldICmpAddConstant(ICmpInst &Cmp,
2365 BinaryOperator *Add,
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002366 const APInt *C) {
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002367 Value *Y = Add->getOperand(1);
2368 const APInt *C2;
2369 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00002370 return nullptr;
2371
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002372 // Fold icmp pred (add X, C2), C.
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002373 Value *X = Add->getOperand(0);
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002374 Type *Ty = Add->getType();
Sanjay Patel6dd2eae2017-02-08 16:19:36 +00002375 CmpInst::Predicate Pred = Cmp.getPredicate();
Sanjay Patel45b7e692017-02-12 16:40:30 +00002376
2377 // If the add does not wrap, we can always adjust the compare by subtracting
2378 // the constants. Equality comparisons are handled elsewhere. SGE/SLE are
2379 // canonicalized to SGT/SLT.
2380 if (Add->hasNoSignedWrap() &&
2381 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) {
2382 bool Overflow;
2383 APInt NewC = C->ssub_ov(*C2, Overflow);
2384 // If there is overflow, the result must be true or false.
2385 // TODO: Can we assert there is no overflow because InstSimplify always
2386 // handles those cases?
2387 if (!Overflow)
2388 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
2389 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
2390 }
2391
Sanjay Patel6dd2eae2017-02-08 16:19:36 +00002392 auto CR = ConstantRange::makeExactICmpRegion(Pred, *C).subtract(*C2);
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002393 const APInt &Upper = CR.getUpper();
2394 const APInt &Lower = CR.getLower();
2395 if (Cmp.isSigned()) {
2396 if (Lower.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002397 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002398 if (Upper.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002399 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002400 } else {
2401 if (Lower.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002402 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002403 if (Upper.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002404 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002405 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002406
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002407 if (!Add->hasOneUse())
2408 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002409
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002410 // X+C <u C2 -> (X & -C2) == C
2411 // iff C & (C2-1) == 0
2412 // C2 is a power of 2
Sanjay Patel6dd2eae2017-02-08 16:19:36 +00002413 if (Pred == ICmpInst::ICMP_ULT && C->isPowerOf2() && (*C2 & (*C - 1)) == 0)
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002414 return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateAnd(X, -(*C)),
2415 ConstantExpr::getNeg(cast<Constant>(Y)));
2416
2417 // X+C >u C2 -> (X & ~C2) != C
2418 // iff C & C2 == 0
2419 // C2+1 is a power of 2
Sanjay Patel6dd2eae2017-02-08 16:19:36 +00002420 if (Pred == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() && (*C2 & *C) == 0)
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002421 return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateAnd(X, ~(*C)),
2422 ConstantExpr::getNeg(cast<Constant>(Y)));
2423
Sanjay Patela3f4f082016-08-16 17:54:36 +00002424 return nullptr;
2425}
2426
Sanjay Patelf58f68c2016-09-10 15:03:44 +00002427/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
2428/// where X is some kind of instruction.
2429Instruction *InstCombiner::foldICmpInstWithConstant(ICmpInst &Cmp) {
Sanjay Patelc9196c42016-08-22 21:24:29 +00002430 const APInt *C;
2431 if (!match(Cmp.getOperand(1), m_APInt(C)))
Sanjay Patel1e5b2d12016-08-16 16:08:11 +00002432 return nullptr;
2433
Sanjay Patelc9196c42016-08-22 21:24:29 +00002434 BinaryOperator *BO;
2435 if (match(Cmp.getOperand(0), m_BinOp(BO))) {
2436 switch (BO->getOpcode()) {
2437 case Instruction::Xor:
2438 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
2439 return I;
2440 break;
2441 case Instruction::And:
2442 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
2443 return I;
2444 break;
2445 case Instruction::Or:
2446 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
2447 return I;
2448 break;
2449 case Instruction::Mul:
2450 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
2451 return I;
2452 break;
2453 case Instruction::Shl:
2454 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
2455 return I;
2456 break;
2457 case Instruction::LShr:
2458 case Instruction::AShr:
2459 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
2460 return I;
2461 break;
2462 case Instruction::UDiv:
2463 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
2464 return I;
2465 LLVM_FALLTHROUGH;
2466 case Instruction::SDiv:
2467 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
2468 return I;
2469 break;
2470 case Instruction::Sub:
2471 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
2472 return I;
2473 break;
2474 case Instruction::Add:
2475 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
2476 return I;
2477 break;
2478 default:
2479 break;
2480 }
Sanjay Patelf58f68c2016-09-10 15:03:44 +00002481 // TODO: These folds could be refactored to be part of the above calls.
2482 if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, C))
2483 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002484 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002485
Sanjay Patelc9196c42016-08-22 21:24:29 +00002486 Instruction *LHSI;
2487 if (match(Cmp.getOperand(0), m_Instruction(LHSI)) &&
2488 LHSI->getOpcode() == Instruction::Trunc)
2489 if (Instruction *I = foldICmpTruncConstant(Cmp, LHSI, C))
2490 return I;
2491
Sanjay Patelf58f68c2016-09-10 15:03:44 +00002492 if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, C))
2493 return I;
2494
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002495 return nullptr;
2496}
Jim Grosbach129c52a2011-09-30 18:09:53 +00002497
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002498/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
2499/// icmp eq/ne BO, C.
2500Instruction *InstCombiner::foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
2501 BinaryOperator *BO,
2502 const APInt *C) {
2503 // TODO: Some of these folds could work with arbitrary constants, but this
2504 // function is limited to scalar and vector splat constants.
2505 if (!Cmp.isEquality())
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002506 return nullptr;
2507
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002508 ICmpInst::Predicate Pred = Cmp.getPredicate();
2509 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
2510 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
Sanjay Patel51a767c2016-08-03 17:23:08 +00002511 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002512
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002513 switch (BO->getOpcode()) {
2514 case Instruction::SRem:
2515 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002516 if (*C == 0 && BO->hasOneUse()) {
Sanjay Patel2e9675f2016-08-03 19:48:40 +00002517 const APInt *BOC;
2518 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002519 Value *NewRem = Builder->CreateURem(BOp0, BOp1, BO->getName());
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002520 return new ICmpInst(Pred, NewRem,
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002521 Constant::getNullValue(BO->getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002522 }
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002523 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002524 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002525 case Instruction::Add: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002526 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
Sanjay Patel00a324e2016-08-03 22:08:44 +00002527 const APInt *BOC;
2528 if (match(BOp1, m_APInt(BOC))) {
2529 if (BO->hasOneUse()) {
2530 Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1));
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002531 return new ICmpInst(Pred, BOp0, SubC);
Sanjay Patel00a324e2016-08-03 22:08:44 +00002532 }
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002533 } else if (*C == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002534 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2535 // efficiently invertible, or if the add has just this one use.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002536 if (Value *NegVal = dyn_castNegVal(BOp1))
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002537 return new ICmpInst(Pred, BOp0, NegVal);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002538 if (Value *NegVal = dyn_castNegVal(BOp0))
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002539 return new ICmpInst(Pred, NegVal, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002540 if (BO->hasOneUse()) {
2541 Value *Neg = Builder->CreateNeg(BOp1);
2542 Neg->takeName(BO);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002543 return new ICmpInst(Pred, BOp0, Neg);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002544 }
2545 }
2546 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002547 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002548 case Instruction::Xor:
2549 if (BO->hasOneUse()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002550 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002551 // For the xor case, we can xor two constants together, eliminating
2552 // the explicit xor.
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002553 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
2554 } else if (*C == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002555 // Replace ((xor A, B) != 0) with (A != B)
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002556 return new ICmpInst(Pred, BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002557 }
2558 }
2559 break;
2560 case Instruction::Sub:
2561 if (BO->hasOneUse()) {
Sanjay Patel9d591d12016-08-04 15:19:25 +00002562 const APInt *BOC;
2563 if (match(BOp0, m_APInt(BOC))) {
Sanjay Patel362ff5c2016-09-15 17:01:17 +00002564 // Replace ((sub BOC, B) != C) with (B != BOC-C).
Sanjay Patel9d591d12016-08-04 15:19:25 +00002565 Constant *SubC = ConstantExpr::getSub(cast<Constant>(BOp0), RHS);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002566 return new ICmpInst(Pred, BOp1, SubC);
2567 } else if (*C == 0) {
Sanjay Patel362ff5c2016-09-15 17:01:17 +00002568 // Replace ((sub A, B) != 0) with (A != B).
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002569 return new ICmpInst(Pred, BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002570 }
2571 }
2572 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002573 case Instruction::Or: {
2574 const APInt *BOC;
2575 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002576 // Comparing if all bits outside of a constant mask are set?
2577 // Replace (X | C) == -1 with (X & ~C) == ~C.
2578 // This removes the -1 constant.
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002579 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
2580 Value *And = Builder->CreateAnd(BOp0, NotBOC);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002581 return new ICmpInst(Pred, And, NotBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002582 }
2583 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002584 }
Sanjay Pateld938e882016-08-04 20:05:02 +00002585 case Instruction::And: {
2586 const APInt *BOC;
2587 if (match(BOp1, m_APInt(BOC))) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002588 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002589 if (C == BOC && C->isPowerOf2())
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002590 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
Sanjay Patelab50a932016-08-02 22:38:33 +00002591 BO, Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002592
2593 // Don't perform the following transforms if the AND has multiple uses
2594 if (!BO->hasOneUse())
2595 break;
2596
2597 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Sanjay Pateld938e882016-08-04 20:05:02 +00002598 if (BOC->isSignBit()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002599 Constant *Zero = Constant::getNullValue(BOp0->getType());
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002600 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
2601 return new ICmpInst(NewPred, BOp0, Zero);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002602 }
2603
2604 // ((X & ~7) == 0) --> X < 8
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002605 if (*C == 0 && (~(*BOC) + 1).isPowerOf2()) {
Sanjay Pateld938e882016-08-04 20:05:02 +00002606 Constant *NegBOC = ConstantExpr::getNeg(cast<Constant>(BOp1));
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002607 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
2608 return new ICmpInst(NewPred, BOp0, NegBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002609 }
2610 }
2611 break;
Sanjay Pateld938e882016-08-04 20:05:02 +00002612 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002613 case Instruction::Mul:
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002614 if (*C == 0 && BO->hasNoSignedWrap()) {
Sanjay Patel3bade132016-08-04 22:19:27 +00002615 const APInt *BOC;
2616 if (match(BOp1, m_APInt(BOC)) && *BOC != 0) {
2617 // The trivial case (mul X, 0) is handled by InstSimplify.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002618 // General case : (mul X, C) != 0 iff X != 0
2619 // (mul X, C) == 0 iff X == 0
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002620 return new ICmpInst(Pred, BOp0, Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002621 }
2622 }
2623 break;
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002624 case Instruction::UDiv:
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002625 if (*C == 0) {
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002626 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002627 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
2628 return new ICmpInst(NewPred, BOp1, BOp0);
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002629 }
2630 break;
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002631 default:
2632 break;
2633 }
2634 return nullptr;
2635}
2636
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002637/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
2638Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
2639 const APInt *C) {
2640 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0));
2641 if (!II || !Cmp.isEquality())
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002642 return nullptr;
2643
2644 // Handle icmp {eq|ne} <intrinsic>, intcst.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002645 switch (II->getIntrinsicID()) {
2646 case Intrinsic::bswap:
2647 Worklist.Add(II);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002648 Cmp.setOperand(0, II->getArgOperand(0));
2649 Cmp.setOperand(1, Builder->getInt(C->byteSwap()));
2650 return &Cmp;
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002651 case Intrinsic::ctlz:
2652 case Intrinsic::cttz:
Amaury Sechet6bea6742016-08-04 05:27:20 +00002653 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002654 if (*C == C->getBitWidth()) {
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002655 Worklist.Add(II);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002656 Cmp.setOperand(0, II->getArgOperand(0));
2657 Cmp.setOperand(1, ConstantInt::getNullValue(II->getType()));
2658 return &Cmp;
Chris Lattner2188e402010-01-04 07:37:31 +00002659 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002660 break;
Amaury Sechet6bea6742016-08-04 05:27:20 +00002661 case Intrinsic::ctpop: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002662 // popcount(A) == 0 -> A == 0 and likewise for !=
Amaury Sechet6bea6742016-08-04 05:27:20 +00002663 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002664 bool IsZero = *C == 0;
2665 if (IsZero || *C == C->getBitWidth()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002666 Worklist.Add(II);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002667 Cmp.setOperand(0, II->getArgOperand(0));
2668 auto *NewOp = IsZero ? Constant::getNullValue(II->getType())
2669 : Constant::getAllOnesValue(II->getType());
2670 Cmp.setOperand(1, NewOp);
2671 return &Cmp;
Amaury Sechet6bea6742016-08-04 05:27:20 +00002672 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002673 break;
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002674 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002675 default:
2676 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002677 }
Craig Topperf40110f2014-04-25 05:29:35 +00002678 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002679}
2680
Sanjay Patel10494b22016-09-16 16:10:22 +00002681/// Handle icmp with constant (but not simple integer constant) RHS.
2682Instruction *InstCombiner::foldICmpInstWithConstantNotInt(ICmpInst &I) {
2683 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2684 Constant *RHSC = dyn_cast<Constant>(Op1);
2685 Instruction *LHSI = dyn_cast<Instruction>(Op0);
2686 if (!RHSC || !LHSI)
2687 return nullptr;
2688
2689 switch (LHSI->getOpcode()) {
2690 case Instruction::GetElementPtr:
2691 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2692 if (RHSC->isNullValue() &&
2693 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2694 return new ICmpInst(
2695 I.getPredicate(), LHSI->getOperand(0),
2696 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2697 break;
2698 case Instruction::PHI:
2699 // Only fold icmp into the PHI if the phi and icmp are in the same
2700 // block. If in the same block, we're encouraging jump threading. If
2701 // not, we are just pessimizing the code by making an i1 phi.
2702 if (LHSI->getParent() == I.getParent())
2703 if (Instruction *NV = FoldOpIntoPhi(I))
2704 return NV;
2705 break;
2706 case Instruction::Select: {
2707 // If either operand of the select is a constant, we can fold the
2708 // comparison into the select arms, which will cause one to be
2709 // constant folded and the select turned into a bitwise or.
2710 Value *Op1 = nullptr, *Op2 = nullptr;
2711 ConstantInt *CI = nullptr;
2712 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2713 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2714 CI = dyn_cast<ConstantInt>(Op1);
2715 }
2716 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2717 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2718 CI = dyn_cast<ConstantInt>(Op2);
2719 }
2720
2721 // We only want to perform this transformation if it will not lead to
2722 // additional code. This is true if either both sides of the select
2723 // fold to a constant (in which case the icmp is replaced with a select
2724 // which will usually simplify) or this is the only user of the
2725 // select (in which case we are trading a select+icmp for a simpler
2726 // select+icmp) or all uses of the select can be replaced based on
2727 // dominance information ("Global cases").
2728 bool Transform = false;
2729 if (Op1 && Op2)
2730 Transform = true;
2731 else if (Op1 || Op2) {
2732 // Local case
2733 if (LHSI->hasOneUse())
2734 Transform = true;
2735 // Global cases
2736 else if (CI && !CI->isZero())
2737 // When Op1 is constant try replacing select with second operand.
2738 // Otherwise Op2 is constant and try replacing select with first
2739 // operand.
2740 Transform =
2741 replacedSelectWithOperand(cast<SelectInst>(LHSI), &I, Op1 ? 2 : 1);
2742 }
2743 if (Transform) {
2744 if (!Op1)
2745 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1), RHSC,
2746 I.getName());
2747 if (!Op2)
2748 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2), RHSC,
2749 I.getName());
2750 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2751 }
2752 break;
2753 }
2754 case Instruction::IntToPtr:
2755 // icmp pred inttoptr(X), null -> icmp pred X, 0
2756 if (RHSC->isNullValue() &&
2757 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
2758 return new ICmpInst(
2759 I.getPredicate(), LHSI->getOperand(0),
2760 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2761 break;
2762
2763 case Instruction::Load:
2764 // Try to optimize things like "A[i] > 4" to index computations.
2765 if (GetElementPtrInst *GEP =
2766 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2767 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2768 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2769 !cast<LoadInst>(LHSI)->isVolatile())
2770 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
2771 return Res;
2772 }
2773 break;
2774 }
2775
2776 return nullptr;
2777}
2778
2779/// Try to fold icmp (binop), X or icmp X, (binop).
2780Instruction *InstCombiner::foldICmpBinOp(ICmpInst &I) {
2781 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2782
2783 // Special logic for binary operators.
2784 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2785 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2786 if (!BO0 && !BO1)
2787 return nullptr;
2788
2789 CmpInst::Predicate Pred = I.getPredicate();
2790 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2791 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2792 NoOp0WrapProblem =
2793 ICmpInst::isEquality(Pred) ||
2794 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2795 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2796 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2797 NoOp1WrapProblem =
2798 ICmpInst::isEquality(Pred) ||
2799 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2800 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2801
2802 // Analyze the case when either Op0 or Op1 is an add instruction.
2803 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2804 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2805 if (BO0 && BO0->getOpcode() == Instruction::Add) {
2806 A = BO0->getOperand(0);
2807 B = BO0->getOperand(1);
2808 }
2809 if (BO1 && BO1->getOpcode() == Instruction::Add) {
2810 C = BO1->getOperand(0);
2811 D = BO1->getOperand(1);
2812 }
2813
Sanjay Patel10494b22016-09-16 16:10:22 +00002814 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2815 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2816 return new ICmpInst(Pred, A == Op1 ? B : A,
2817 Constant::getNullValue(Op1->getType()));
2818
2819 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2820 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2821 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2822 C == Op0 ? D : C);
2823
2824 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
2825 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
2826 NoOp1WrapProblem &&
2827 // Try not to increase register pressure.
2828 BO0->hasOneUse() && BO1->hasOneUse()) {
2829 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2830 Value *Y, *Z;
2831 if (A == C) {
2832 // C + B == C + D -> B == D
2833 Y = B;
2834 Z = D;
2835 } else if (A == D) {
2836 // D + B == C + D -> B == C
2837 Y = B;
2838 Z = C;
2839 } else if (B == C) {
2840 // A + C == C + D -> A == D
2841 Y = A;
2842 Z = D;
2843 } else {
2844 assert(B == D);
2845 // A + D == C + D -> A == C
2846 Y = A;
2847 Z = C;
2848 }
2849 return new ICmpInst(Pred, Y, Z);
2850 }
2851
2852 // icmp slt (X + -1), Y -> icmp sle X, Y
2853 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
2854 match(B, m_AllOnes()))
2855 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
2856
2857 // icmp sge (X + -1), Y -> icmp sgt X, Y
2858 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
2859 match(B, m_AllOnes()))
2860 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
2861
2862 // icmp sle (X + 1), Y -> icmp slt X, Y
2863 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One()))
2864 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
2865
2866 // icmp sgt (X + 1), Y -> icmp sge X, Y
2867 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One()))
2868 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
2869
2870 // icmp sgt X, (Y + -1) -> icmp sge X, Y
2871 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
2872 match(D, m_AllOnes()))
2873 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
2874
2875 // icmp sle X, (Y + -1) -> icmp slt X, Y
2876 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
2877 match(D, m_AllOnes()))
2878 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
2879
2880 // icmp sge X, (Y + 1) -> icmp sgt X, Y
2881 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One()))
2882 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
2883
2884 // icmp slt X, (Y + 1) -> icmp sle X, Y
2885 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One()))
2886 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
2887
Sanjay Patel40f40172017-01-13 23:25:46 +00002888 // TODO: The subtraction-related identities shown below also hold, but
2889 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
2890 // wouldn't happen even if they were implemented.
2891 //
2892 // icmp ult (X - 1), Y -> icmp ule X, Y
2893 // icmp uge (X - 1), Y -> icmp ugt X, Y
2894 // icmp ugt X, (Y - 1) -> icmp uge X, Y
2895 // icmp ule X, (Y - 1) -> icmp ult X, Y
2896
2897 // icmp ule (X + 1), Y -> icmp ult X, Y
2898 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One()))
2899 return new ICmpInst(CmpInst::ICMP_ULT, A, Op1);
2900
2901 // icmp ugt (X + 1), Y -> icmp uge X, Y
2902 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One()))
2903 return new ICmpInst(CmpInst::ICMP_UGE, A, Op1);
2904
2905 // icmp uge X, (Y + 1) -> icmp ugt X, Y
2906 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One()))
2907 return new ICmpInst(CmpInst::ICMP_UGT, Op0, C);
2908
2909 // icmp ult X, (Y + 1) -> icmp ule X, Y
2910 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One()))
2911 return new ICmpInst(CmpInst::ICMP_ULE, Op0, C);
2912
Sanjay Patel10494b22016-09-16 16:10:22 +00002913 // if C1 has greater magnitude than C2:
2914 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
2915 // s.t. C3 = C1 - C2
2916 //
2917 // if C2 has greater magnitude than C1:
2918 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
2919 // s.t. C3 = C2 - C1
2920 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
2921 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
2922 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
2923 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
2924 const APInt &AP1 = C1->getValue();
2925 const APInt &AP2 = C2->getValue();
2926 if (AP1.isNegative() == AP2.isNegative()) {
2927 APInt AP1Abs = C1->getValue().abs();
2928 APInt AP2Abs = C2->getValue().abs();
2929 if (AP1Abs.uge(AP2Abs)) {
2930 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
2931 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
2932 return new ICmpInst(Pred, NewAdd, C);
2933 } else {
2934 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
2935 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
2936 return new ICmpInst(Pred, A, NewAdd);
2937 }
2938 }
2939 }
2940
2941 // Analyze the case when either Op0 or Op1 is a sub instruction.
2942 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2943 A = nullptr;
2944 B = nullptr;
2945 C = nullptr;
2946 D = nullptr;
2947 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
2948 A = BO0->getOperand(0);
2949 B = BO0->getOperand(1);
2950 }
2951 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
2952 C = BO1->getOperand(0);
2953 D = BO1->getOperand(1);
2954 }
2955
2956 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2957 if (A == Op1 && NoOp0WrapProblem)
2958 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2959
2960 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2961 if (C == Op0 && NoOp1WrapProblem)
2962 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2963
2964 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
2965 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2966 // Try not to increase register pressure.
2967 BO0->hasOneUse() && BO1->hasOneUse())
2968 return new ICmpInst(Pred, A, C);
2969
2970 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2971 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2972 // Try not to increase register pressure.
2973 BO0->hasOneUse() && BO1->hasOneUse())
2974 return new ICmpInst(Pred, D, B);
2975
2976 // icmp (0-X) < cst --> x > -cst
2977 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
2978 Value *X;
2979 if (match(BO0, m_Neg(m_Value(X))))
2980 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
2981 if (!RHSC->isMinValue(/*isSigned=*/true))
2982 return new ICmpInst(I.getSwappedPredicate(), X,
2983 ConstantExpr::getNeg(RHSC));
2984 }
2985
2986 BinaryOperator *SRem = nullptr;
2987 // icmp (srem X, Y), Y
2988 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
2989 SRem = BO0;
2990 // icmp Y, (srem X, Y)
2991 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2992 Op0 == BO1->getOperand(1))
2993 SRem = BO1;
2994 if (SRem) {
2995 // We don't check hasOneUse to avoid increasing register pressure because
2996 // the value we use is the same value this instruction was already using.
2997 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2998 default:
2999 break;
3000 case ICmpInst::ICMP_EQ:
3001 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3002 case ICmpInst::ICMP_NE:
3003 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3004 case ICmpInst::ICMP_SGT:
3005 case ICmpInst::ICMP_SGE:
3006 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
3007 Constant::getAllOnesValue(SRem->getType()));
3008 case ICmpInst::ICMP_SLT:
3009 case ICmpInst::ICMP_SLE:
3010 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
3011 Constant::getNullValue(SRem->getType()));
3012 }
3013 }
3014
3015 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() &&
3016 BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) {
3017 switch (BO0->getOpcode()) {
3018 default:
3019 break;
3020 case Instruction::Add:
3021 case Instruction::Sub:
3022 case Instruction::Xor:
3023 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
3024 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3025 BO1->getOperand(0));
3026 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
3027 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3028 if (CI->getValue().isSignBit()) {
3029 ICmpInst::Predicate Pred =
3030 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate();
3031 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3032 }
3033
3034 if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) {
3035 ICmpInst::Predicate Pred =
3036 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate();
3037 Pred = I.getSwappedPredicate(Pred);
3038 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3039 }
3040 }
3041 break;
3042 case Instruction::Mul:
3043 if (!I.isEquality())
3044 break;
3045
3046 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3047 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
3048 // Mask = -1 >> count-trailing-zeros(Cst).
3049 if (!CI->isZero() && !CI->isOne()) {
3050 const APInt &AP = CI->getValue();
3051 ConstantInt *Mask = ConstantInt::get(
3052 I.getContext(),
3053 APInt::getLowBitsSet(AP.getBitWidth(),
3054 AP.getBitWidth() - AP.countTrailingZeros()));
3055 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
3056 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
3057 return new ICmpInst(I.getPredicate(), And1, And2);
3058 }
3059 }
3060 break;
3061 case Instruction::UDiv:
3062 case Instruction::LShr:
3063 if (I.isSigned())
3064 break;
3065 LLVM_FALLTHROUGH;
3066 case Instruction::SDiv:
3067 case Instruction::AShr:
3068 if (!BO0->isExact() || !BO1->isExact())
3069 break;
3070 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3071 BO1->getOperand(0));
3072 case Instruction::Shl: {
3073 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
3074 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
3075 if (!NUW && !NSW)
3076 break;
3077 if (!NSW && I.isSigned())
3078 break;
3079 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3080 BO1->getOperand(0));
3081 }
3082 }
3083 }
3084
3085 if (BO0) {
3086 // Transform A & (L - 1) `ult` L --> L != 0
3087 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
3088 auto BitwiseAnd =
3089 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
3090
3091 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
3092 auto *Zero = Constant::getNullValue(BO0->getType());
3093 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
3094 }
3095 }
3096
3097 return nullptr;
3098}
3099
Sanjay Pateldd46b522016-12-19 17:32:37 +00003100/// Fold icmp Pred min|max(X, Y), X.
3101static Instruction *foldICmpWithMinMax(ICmpInst &Cmp) {
Sanjay Pateld6406412016-12-15 19:13:37 +00003102 ICmpInst::Predicate Pred = Cmp.getPredicate();
3103 Value *Op0 = Cmp.getOperand(0);
3104 Value *X = Cmp.getOperand(1);
3105
Sanjay Pateldd46b522016-12-19 17:32:37 +00003106 // Canonicalize minimum or maximum operand to LHS of the icmp.
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003107 if (match(X, m_c_SMin(m_Specific(Op0), m_Value())) ||
Sanjay Pateldd46b522016-12-19 17:32:37 +00003108 match(X, m_c_SMax(m_Specific(Op0), m_Value())) ||
3109 match(X, m_c_UMin(m_Specific(Op0), m_Value())) ||
3110 match(X, m_c_UMax(m_Specific(Op0), m_Value()))) {
Sanjay Pateld6406412016-12-15 19:13:37 +00003111 std::swap(Op0, X);
3112 Pred = Cmp.getSwappedPredicate();
3113 }
3114
3115 Value *Y;
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003116 if (match(Op0, m_c_SMin(m_Specific(X), m_Value(Y)))) {
Sanjay Pateldd46b522016-12-19 17:32:37 +00003117 // smin(X, Y) == X --> X s<= Y
3118 // smin(X, Y) s>= X --> X s<= Y
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003119 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SGE)
3120 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3121
Sanjay Pateldd46b522016-12-19 17:32:37 +00003122 // smin(X, Y) != X --> X s> Y
3123 // smin(X, Y) s< X --> X s> Y
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003124 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SLT)
3125 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3126
3127 // These cases should be handled in InstSimplify:
Sanjay Pateldd46b522016-12-19 17:32:37 +00003128 // smin(X, Y) s<= X --> true
3129 // smin(X, Y) s> X --> false
Sanjay Pateld6406412016-12-15 19:13:37 +00003130 return nullptr;
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003131 }
Sanjay Pateldd46b522016-12-19 17:32:37 +00003132
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003133 if (match(Op0, m_c_SMax(m_Specific(X), m_Value(Y)))) {
Sanjay Pateldd46b522016-12-19 17:32:37 +00003134 // smax(X, Y) == X --> X s>= Y
3135 // smax(X, Y) s<= X --> X s>= Y
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003136 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SLE)
3137 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
Sanjay Pateld6406412016-12-15 19:13:37 +00003138
Sanjay Pateldd46b522016-12-19 17:32:37 +00003139 // smax(X, Y) != X --> X s< Y
3140 // smax(X, Y) s> X --> X s< Y
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003141 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SGT)
3142 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
Sanjay Pateld6406412016-12-15 19:13:37 +00003143
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003144 // These cases should be handled in InstSimplify:
Sanjay Pateldd46b522016-12-19 17:32:37 +00003145 // smax(X, Y) s>= X --> true
3146 // smax(X, Y) s< X --> false
3147 return nullptr;
3148 }
3149
3150 if (match(Op0, m_c_UMin(m_Specific(X), m_Value(Y)))) {
3151 // umin(X, Y) == X --> X u<= Y
3152 // umin(X, Y) u>= X --> X u<= Y
3153 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_UGE)
3154 return new ICmpInst(ICmpInst::ICMP_ULE, X, Y);
3155
3156 // umin(X, Y) != X --> X u> Y
3157 // umin(X, Y) u< X --> X u> Y
3158 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT)
3159 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
3160
3161 // These cases should be handled in InstSimplify:
3162 // umin(X, Y) u<= X --> true
3163 // umin(X, Y) u> X --> false
3164 return nullptr;
3165 }
3166
3167 if (match(Op0, m_c_UMax(m_Specific(X), m_Value(Y)))) {
3168 // umax(X, Y) == X --> X u>= Y
3169 // umax(X, Y) u<= X --> X u>= Y
3170 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_ULE)
3171 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y);
3172
3173 // umax(X, Y) != X --> X u< Y
3174 // umax(X, Y) u> X --> X u< Y
3175 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_UGT)
3176 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
3177
3178 // These cases should be handled in InstSimplify:
3179 // umax(X, Y) u>= X --> true
3180 // umax(X, Y) u< X --> false
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003181 return nullptr;
3182 }
Sanjay Pateld6406412016-12-15 19:13:37 +00003183
Sanjay Pateld6406412016-12-15 19:13:37 +00003184 return nullptr;
3185}
3186
Sanjay Patel10494b22016-09-16 16:10:22 +00003187Instruction *InstCombiner::foldICmpEquality(ICmpInst &I) {
3188 if (!I.isEquality())
3189 return nullptr;
3190
3191 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3192 Value *A, *B, *C, *D;
3193 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3194 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
3195 Value *OtherVal = A == Op1 ? B : A;
3196 return new ICmpInst(I.getPredicate(), OtherVal,
3197 Constant::getNullValue(A->getType()));
3198 }
3199
3200 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
3201 // A^c1 == C^c2 --> A == C^(c1^c2)
3202 ConstantInt *C1, *C2;
3203 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
3204 Op1->hasOneUse()) {
3205 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
3206 Value *Xor = Builder->CreateXor(C, NC);
3207 return new ICmpInst(I.getPredicate(), A, Xor);
3208 }
3209
3210 // A^B == A^D -> B == D
3211 if (A == C)
3212 return new ICmpInst(I.getPredicate(), B, D);
3213 if (A == D)
3214 return new ICmpInst(I.getPredicate(), B, C);
3215 if (B == C)
3216 return new ICmpInst(I.getPredicate(), A, D);
3217 if (B == D)
3218 return new ICmpInst(I.getPredicate(), A, C);
3219 }
3220 }
3221
3222 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
3223 // A == (A^B) -> B == 0
3224 Value *OtherVal = A == Op0 ? B : A;
3225 return new ICmpInst(I.getPredicate(), OtherVal,
3226 Constant::getNullValue(A->getType()));
3227 }
3228
3229 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
3230 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
3231 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
3232 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
3233
3234 if (A == C) {
3235 X = B;
3236 Y = D;
3237 Z = A;
3238 } else if (A == D) {
3239 X = B;
3240 Y = C;
3241 Z = A;
3242 } else if (B == C) {
3243 X = A;
3244 Y = D;
3245 Z = B;
3246 } else if (B == D) {
3247 X = A;
3248 Y = C;
3249 Z = B;
3250 }
3251
3252 if (X) { // Build (X^Y) & Z
3253 Op1 = Builder->CreateXor(X, Y);
3254 Op1 = Builder->CreateAnd(Op1, Z);
3255 I.setOperand(0, Op1);
3256 I.setOperand(1, Constant::getNullValue(Op1->getType()));
3257 return &I;
3258 }
3259 }
3260
3261 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
3262 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
3263 ConstantInt *Cst1;
3264 if ((Op0->hasOneUse() && match(Op0, m_ZExt(m_Value(A))) &&
3265 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
3266 (Op1->hasOneUse() && match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
3267 match(Op1, m_ZExt(m_Value(A))))) {
3268 APInt Pow2 = Cst1->getValue() + 1;
3269 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
3270 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
3271 return new ICmpInst(I.getPredicate(), A,
3272 Builder->CreateTrunc(B, A->getType()));
3273 }
3274
3275 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
3276 // For lshr and ashr pairs.
3277 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3278 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
3279 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3280 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
3281 unsigned TypeBits = Cst1->getBitWidth();
3282 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3283 if (ShAmt < TypeBits && ShAmt != 0) {
3284 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
3285 ? ICmpInst::ICMP_UGE
3286 : ICmpInst::ICMP_ULT;
3287 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
3288 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
3289 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
3290 }
3291 }
3292
3293 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
3294 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
3295 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
3296 unsigned TypeBits = Cst1->getBitWidth();
3297 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3298 if (ShAmt < TypeBits && ShAmt != 0) {
3299 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
3300 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
3301 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
3302 I.getName() + ".mask");
3303 return new ICmpInst(I.getPredicate(), And,
3304 Constant::getNullValue(Cst1->getType()));
3305 }
3306 }
3307
3308 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
3309 // "icmp (and X, mask), cst"
3310 uint64_t ShAmt = 0;
3311 if (Op0->hasOneUse() &&
3312 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
3313 match(Op1, m_ConstantInt(Cst1)) &&
3314 // Only do this when A has multiple uses. This is most important to do
3315 // when it exposes other optimizations.
3316 !A->hasOneUse()) {
3317 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
3318
3319 if (ShAmt < ASize) {
3320 APInt MaskV =
3321 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
3322 MaskV <<= ShAmt;
3323
3324 APInt CmpV = Cst1->getValue().zext(ASize);
3325 CmpV <<= ShAmt;
3326
3327 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
3328 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
3329 }
3330 }
3331
3332 return nullptr;
3333}
3334
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003335/// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so
3336/// far.
Sanjay Patel43395062016-07-21 18:07:40 +00003337Instruction *InstCombiner::foldICmpWithCastAndCast(ICmpInst &ICmp) {
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003338 const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00003339 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003340 Type *SrcTy = LHSCIOp->getType();
3341 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00003342 Value *RHSCIOp;
3343
Jim Grosbach129c52a2011-09-30 18:09:53 +00003344 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00003345 // integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003346 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
3347 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00003348 Value *RHSOp = nullptr;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003349 if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
Michael Liaod266b922015-02-13 04:51:26 +00003350 Value *RHSCIOp = RHSC->getOperand(0);
3351 if (RHSCIOp->getType()->getPointerAddressSpace() ==
3352 LHSCIOp->getType()->getPointerAddressSpace()) {
3353 RHSOp = RHSC->getOperand(0);
3354 // If the pointer types don't match, insert a bitcast.
3355 if (LHSCIOp->getType() != RHSOp->getType())
3356 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
3357 }
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003358 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003359 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003360 }
Chris Lattner2188e402010-01-04 07:37:31 +00003361
3362 if (RHSOp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003363 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner2188e402010-01-04 07:37:31 +00003364 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003365
Chris Lattner2188e402010-01-04 07:37:31 +00003366 // The code below only handles extension cast instructions, so far.
3367 // Enforce this.
3368 if (LHSCI->getOpcode() != Instruction::ZExt &&
3369 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00003370 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003371
3372 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003373 bool isSignedCmp = ICmp.isSigned();
Chris Lattner2188e402010-01-04 07:37:31 +00003374
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003375 if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003376 // Not an extension from the same type?
3377 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003378 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00003379 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003380
Chris Lattner2188e402010-01-04 07:37:31 +00003381 // If the signedness of the two casts doesn't agree (i.e. one is a sext
3382 // and the other is a zext), then we can't handle this.
3383 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00003384 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003385
3386 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003387 if (ICmp.isEquality())
3388 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00003389
3390 // A signed comparison of sign extended values simplifies into a
3391 // signed comparison.
3392 if (isSignedCmp && isSignedExt)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003393 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00003394
3395 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003396 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00003397 }
3398
Sanjay Patel4c204232016-06-04 20:39:22 +00003399 // If we aren't dealing with a constant on the RHS, exit early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003400 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
3401 if (!C)
Craig Topperf40110f2014-04-25 05:29:35 +00003402 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003403
3404 // Compute the constant that would happen if we truncated to SrcTy then
Sanjay Patelc774f8c2016-06-04 21:20:44 +00003405 // re-extended to DestTy.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003406 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
Sanjay Patelc774f8c2016-06-04 21:20:44 +00003407 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattner2188e402010-01-04 07:37:31 +00003408
3409 // If the re-extended constant didn't change...
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003410 if (Res2 == C) {
Chris Lattner2188e402010-01-04 07:37:31 +00003411 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003412 if (ICmp.isEquality())
3413 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00003414
3415 // A signed comparison of sign extended values simplifies into a
3416 // signed comparison.
3417 if (isSignedExt && isSignedCmp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003418 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00003419
3420 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003421 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00003422 }
3423
Sanjay Patel6a333c32016-06-06 16:56:57 +00003424 // The re-extended constant changed, partly changed (in the case of a vector),
3425 // or could not be determined to be equal (in the case of a constant
3426 // expression), so the constant cannot be represented in the shorter type.
3427 // Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003428 // All the cases that fold to true or false will have already been handled
3429 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00003430
Sanjay Patel6a333c32016-06-06 16:56:57 +00003431 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
Craig Topperf40110f2014-04-25 05:29:35 +00003432 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003433
3434 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
3435 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003436
3437 // We're performing an unsigned comp with a sign extended value.
3438 // This is true if the input is >= 0. [aka >s -1]
3439 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003440 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00003441
3442 // Finally, return the value computed.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003443 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
3444 return replaceInstUsesWith(ICmp, Result);
Chris Lattner2188e402010-01-04 07:37:31 +00003445
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003446 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00003447 return BinaryOperator::CreateNot(Result);
3448}
3449
Sanjoy Dasb0984472015-04-08 04:27:22 +00003450bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
3451 Value *RHS, Instruction &OrigI,
3452 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00003453 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
3454 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003455
3456 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
3457 Result = OpResult;
3458 Overflow = OverflowVal;
3459 if (ReuseName)
3460 Result->takeName(&OrigI);
3461 return true;
3462 };
3463
Sanjoy Das6f5dca72015-08-28 19:09:31 +00003464 // If the overflow check was an add followed by a compare, the insertion point
3465 // may be pointing to the compare. We want to insert the new instructions
3466 // before the add in case there are uses of the add between the add and the
3467 // compare.
3468 Builder->SetInsertPoint(&OrigI);
3469
Sanjoy Dasb0984472015-04-08 04:27:22 +00003470 switch (OCF) {
3471 case OCF_INVALID:
3472 llvm_unreachable("bad overflow check kind!");
3473
3474 case OCF_UNSIGNED_ADD: {
3475 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
3476 if (OR == OverflowResult::NeverOverflows)
3477 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
3478 true);
3479
3480 if (OR == OverflowResult::AlwaysOverflows)
3481 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003482
3483 // Fall through uadd into sadd
3484 LLVM_FALLTHROUGH;
Sanjoy Dasb0984472015-04-08 04:27:22 +00003485 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00003486 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00003487 // X + 0 -> {X, false}
3488 if (match(RHS, m_Zero()))
3489 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003490
3491 // We can strength reduce this signed add into a regular add if we can prove
3492 // that it will never overflow.
3493 if (OCF == OCF_SIGNED_ADD)
3494 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
3495 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
3496 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00003497 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00003498 }
3499
3500 case OCF_UNSIGNED_SUB:
3501 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00003502 // X - 0 -> {X, false}
3503 if (match(RHS, m_Zero()))
3504 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003505
3506 if (OCF == OCF_SIGNED_SUB) {
3507 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
3508 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
3509 true);
3510 } else {
3511 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
3512 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
3513 true);
3514 }
3515 break;
3516 }
3517
3518 case OCF_UNSIGNED_MUL: {
3519 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
3520 if (OR == OverflowResult::NeverOverflows)
3521 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
3522 true);
3523 if (OR == OverflowResult::AlwaysOverflows)
3524 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003525 LLVM_FALLTHROUGH;
3526 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00003527 case OCF_SIGNED_MUL:
3528 // X * undef -> undef
3529 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00003530 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003531
David Majnemer27e89ba2015-05-21 23:04:21 +00003532 // X * 0 -> {0, false}
3533 if (match(RHS, m_Zero()))
3534 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003535
David Majnemer27e89ba2015-05-21 23:04:21 +00003536 // X * 1 -> {X, false}
3537 if (match(RHS, m_One()))
3538 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003539
3540 if (OCF == OCF_SIGNED_MUL)
3541 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
3542 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
3543 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00003544 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00003545 }
3546
3547 return false;
3548}
3549
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003550/// \brief Recognize and process idiom involving test for multiplication
3551/// overflow.
3552///
3553/// The caller has matched a pattern of the form:
3554/// I = cmp u (mul(zext A, zext B), V
3555/// The function checks if this is a test for overflow and if so replaces
3556/// multiplication with call to 'mul.with.overflow' intrinsic.
3557///
3558/// \param I Compare instruction.
3559/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
3560/// the compare instruction. Must be of integer type.
3561/// \param OtherVal The other argument of compare instruction.
3562/// \returns Instruction which must replace the compare instruction, NULL if no
3563/// replacement required.
Sanjay Pateld93c4c02016-09-15 18:22:25 +00003564static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003565 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00003566 // Don't bother doing this transformation for pointers, don't do it for
3567 // vectors.
3568 if (!isa<IntegerType>(MulVal->getType()))
3569 return nullptr;
3570
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003571 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
3572 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00003573 auto *MulInstr = dyn_cast<Instruction>(MulVal);
3574 if (!MulInstr)
3575 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003576 assert(MulInstr->getOpcode() == Instruction::Mul);
3577
David Majnemer634ca232014-11-01 23:46:05 +00003578 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
3579 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003580 assert(LHS->getOpcode() == Instruction::ZExt);
3581 assert(RHS->getOpcode() == Instruction::ZExt);
3582 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
3583
3584 // Calculate type and width of the result produced by mul.with.overflow.
3585 Type *TyA = A->getType(), *TyB = B->getType();
3586 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
3587 WidthB = TyB->getPrimitiveSizeInBits();
3588 unsigned MulWidth;
3589 Type *MulType;
3590 if (WidthB > WidthA) {
3591 MulWidth = WidthB;
3592 MulType = TyB;
3593 } else {
3594 MulWidth = WidthA;
3595 MulType = TyA;
3596 }
3597
3598 // In order to replace the original mul with a narrower mul.with.overflow,
3599 // all uses must ignore upper bits of the product. The number of used low
3600 // bits must be not greater than the width of mul.with.overflow.
3601 if (MulVal->hasNUsesOrMore(2))
3602 for (User *U : MulVal->users()) {
3603 if (U == &I)
3604 continue;
3605 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
3606 // Check if truncation ignores bits above MulWidth.
3607 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
3608 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00003609 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003610 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
3611 // Check if AND ignores bits above MulWidth.
3612 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00003613 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003614 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3615 const APInt &CVal = CI->getValue();
3616 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00003617 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003618 }
3619 } else {
3620 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00003621 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003622 }
3623 }
3624
3625 // Recognize patterns
3626 switch (I.getPredicate()) {
3627 case ICmpInst::ICMP_EQ:
3628 case ICmpInst::ICMP_NE:
3629 // Recognize pattern:
3630 // mulval = mul(zext A, zext B)
3631 // cmp eq/neq mulval, zext trunc mulval
3632 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
3633 if (Zext->hasOneUse()) {
3634 Value *ZextArg = Zext->getOperand(0);
3635 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
3636 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
3637 break; //Recognized
3638 }
3639
3640 // Recognize pattern:
3641 // mulval = mul(zext A, zext B)
3642 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
3643 ConstantInt *CI;
3644 Value *ValToMask;
3645 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
3646 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00003647 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003648 const APInt &CVal = CI->getValue() + 1;
3649 if (CVal.isPowerOf2()) {
3650 unsigned MaskWidth = CVal.logBase2();
3651 if (MaskWidth == MulWidth)
3652 break; // Recognized
3653 }
3654 }
Craig Topperf40110f2014-04-25 05:29:35 +00003655 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003656
3657 case ICmpInst::ICMP_UGT:
3658 // Recognize pattern:
3659 // mulval = mul(zext A, zext B)
3660 // cmp ugt mulval, max
3661 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3662 APInt MaxVal = APInt::getMaxValue(MulWidth);
3663 MaxVal = MaxVal.zext(CI->getBitWidth());
3664 if (MaxVal.eq(CI->getValue()))
3665 break; // Recognized
3666 }
Craig Topperf40110f2014-04-25 05:29:35 +00003667 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003668
3669 case ICmpInst::ICMP_UGE:
3670 // Recognize pattern:
3671 // mulval = mul(zext A, zext B)
3672 // cmp uge mulval, max+1
3673 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3674 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
3675 if (MaxVal.eq(CI->getValue()))
3676 break; // Recognized
3677 }
Craig Topperf40110f2014-04-25 05:29:35 +00003678 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003679
3680 case ICmpInst::ICMP_ULE:
3681 // Recognize pattern:
3682 // mulval = mul(zext A, zext B)
3683 // cmp ule mulval, max
3684 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3685 APInt MaxVal = APInt::getMaxValue(MulWidth);
3686 MaxVal = MaxVal.zext(CI->getBitWidth());
3687 if (MaxVal.eq(CI->getValue()))
3688 break; // Recognized
3689 }
Craig Topperf40110f2014-04-25 05:29:35 +00003690 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003691
3692 case ICmpInst::ICMP_ULT:
3693 // Recognize pattern:
3694 // mulval = mul(zext A, zext B)
3695 // cmp ule mulval, max + 1
3696 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00003697 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003698 if (MaxVal.eq(CI->getValue()))
3699 break; // Recognized
3700 }
Craig Topperf40110f2014-04-25 05:29:35 +00003701 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003702
3703 default:
Craig Topperf40110f2014-04-25 05:29:35 +00003704 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003705 }
3706
3707 InstCombiner::BuilderTy *Builder = IC.Builder;
3708 Builder->SetInsertPoint(MulInstr);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003709
3710 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
3711 Value *MulA = A, *MulB = B;
3712 if (WidthA < MulWidth)
3713 MulA = Builder->CreateZExt(A, MulType);
3714 if (WidthB < MulWidth)
3715 MulB = Builder->CreateZExt(B, MulType);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00003716 Value *F = Intrinsic::getDeclaration(I.getModule(),
3717 Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00003718 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003719 IC.Worklist.Add(MulInstr);
3720
3721 // If there are uses of mul result other than the comparison, we know that
3722 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00003723 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003724 if (MulVal->hasNUsesOrMore(2)) {
3725 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
3726 for (User *U : MulVal->users()) {
3727 if (U == &I || U == OtherVal)
3728 continue;
3729 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
3730 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
Sanjay Patel4b198802016-02-01 22:23:39 +00003731 IC.replaceInstUsesWith(*TI, Mul);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003732 else
3733 TI->setOperand(0, Mul);
3734 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
3735 assert(BO->getOpcode() == Instruction::And);
3736 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
3737 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
3738 APInt ShortMask = CI->getValue().trunc(MulWidth);
3739 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
3740 Instruction *Zext =
3741 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
3742 IC.Worklist.Add(Zext);
Sanjay Patel4b198802016-02-01 22:23:39 +00003743 IC.replaceInstUsesWith(*BO, Zext);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003744 } else {
3745 llvm_unreachable("Unexpected Binary operation");
3746 }
3747 IC.Worklist.Add(cast<Instruction>(U));
3748 }
3749 }
3750 if (isa<Instruction>(OtherVal))
3751 IC.Worklist.Add(cast<Instruction>(OtherVal));
3752
3753 // The original icmp gets replaced with the overflow value, maybe inverted
3754 // depending on predicate.
3755 bool Inverse = false;
3756 switch (I.getPredicate()) {
3757 case ICmpInst::ICMP_NE:
3758 break;
3759 case ICmpInst::ICMP_EQ:
3760 Inverse = true;
3761 break;
3762 case ICmpInst::ICMP_UGT:
3763 case ICmpInst::ICMP_UGE:
3764 if (I.getOperand(0) == MulVal)
3765 break;
3766 Inverse = true;
3767 break;
3768 case ICmpInst::ICMP_ULT:
3769 case ICmpInst::ICMP_ULE:
3770 if (I.getOperand(1) == MulVal)
3771 break;
3772 Inverse = true;
3773 break;
3774 default:
3775 llvm_unreachable("Unexpected predicate");
3776 }
3777 if (Inverse) {
3778 Value *Res = Builder->CreateExtractValue(Call, 1);
3779 return BinaryOperator::CreateNot(Res);
3780 }
3781
3782 return ExtractValueInst::Create(Call, 1);
3783}
3784
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003785/// When performing a comparison against a constant, it is possible that not all
3786/// the bits in the LHS are demanded. This helper method computes the mask that
3787/// IS demanded.
Sanjay Pateld93c4c02016-09-15 18:22:25 +00003788static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth,
3789 bool isSignCheck) {
Owen Andersond490c2d2011-01-11 00:36:45 +00003790 if (isSignCheck)
3791 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003792
Owen Andersond490c2d2011-01-11 00:36:45 +00003793 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3794 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00003795 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003796
Owen Andersond490c2d2011-01-11 00:36:45 +00003797 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003798 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00003799 // correspond to the trailing ones of the comparand. The value of these
3800 // bits doesn't impact the outcome of the comparison, because any value
3801 // greater than the RHS must differ in a bit higher than these due to carry.
3802 case ICmpInst::ICMP_UGT: {
3803 unsigned trailingOnes = RHS.countTrailingOnes();
3804 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
3805 return ~lowBitsSet;
3806 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003807
Owen Andersond490c2d2011-01-11 00:36:45 +00003808 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
3809 // Any value less than the RHS must differ in a higher bit because of carries.
3810 case ICmpInst::ICMP_ULT: {
3811 unsigned trailingZeros = RHS.countTrailingZeros();
3812 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
3813 return ~lowBitsSet;
3814 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003815
Owen Andersond490c2d2011-01-11 00:36:45 +00003816 default:
3817 return APInt::getAllOnesValue(BitWidth);
3818 }
Owen Andersond490c2d2011-01-11 00:36:45 +00003819}
Chris Lattner2188e402010-01-04 07:37:31 +00003820
Quentin Colombet5ab55552013-09-09 20:56:48 +00003821/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
3822/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00003823/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00003824/// as subtract operands and their positions in those instructions.
3825/// The rational is that several architectures use the same instruction for
3826/// both subtract and cmp, thus it is better if the order of those operands
3827/// match.
3828/// \return true if Op0 and Op1 should be swapped.
3829static bool swapMayExposeCSEOpportunities(const Value * Op0,
3830 const Value * Op1) {
3831 // Filter out pointer value as those cannot appears directly in subtract.
3832 // FIXME: we may want to go through inttoptrs or bitcasts.
3833 if (Op0->getType()->isPointerTy())
3834 return false;
3835 // Count every uses of both Op0 and Op1 in a subtract.
3836 // Each time Op0 is the first operand, count -1: swapping is bad, the
3837 // subtract has already the same layout as the compare.
3838 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00003839 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003840 // At the end, if the benefit is greater than 0, Op0 should come second to
3841 // expose more CSE opportunities.
3842 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003843 for (const User *U : Op0->users()) {
3844 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003845 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
3846 continue;
3847 // If Op0 is the first argument, this is not beneficial to swap the
3848 // arguments.
3849 int LocalSwapBenefits = -1;
3850 unsigned Op1Idx = 1;
3851 if (BinOp->getOperand(Op1Idx) == Op0) {
3852 Op1Idx = 0;
3853 LocalSwapBenefits = 1;
3854 }
3855 if (BinOp->getOperand(Op1Idx) != Op1)
3856 continue;
3857 GlobalSwapBenefits += LocalSwapBenefits;
3858 }
3859 return GlobalSwapBenefits > 0;
3860}
3861
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003862/// \brief Check that one use is in the same block as the definition and all
Sanjay Patel53523312016-09-12 14:25:46 +00003863/// other uses are in blocks dominated by a given block.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003864///
3865/// \param DI Definition
3866/// \param UI Use
3867/// \param DB Block that must dominate all uses of \p DI outside
3868/// the parent block
3869/// \return true when \p UI is the only use of \p DI in the parent block
3870/// and all other uses of \p DI are in blocks dominated by \p DB.
3871///
3872bool InstCombiner::dominatesAllUses(const Instruction *DI,
3873 const Instruction *UI,
3874 const BasicBlock *DB) const {
3875 assert(DI && UI && "Instruction not defined\n");
Sanjay Patel53523312016-09-12 14:25:46 +00003876 // Ignore incomplete definitions.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003877 if (!DI->getParent())
3878 return false;
Sanjay Patel53523312016-09-12 14:25:46 +00003879 // DI and UI must be in the same block.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003880 if (DI->getParent() != UI->getParent())
3881 return false;
Sanjay Patel53523312016-09-12 14:25:46 +00003882 // Protect from self-referencing blocks.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003883 if (DI->getParent() == DB)
3884 return false;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003885 for (const User *U : DI->users()) {
3886 auto *Usr = cast<Instruction>(U);
Justin Bogner99798402016-08-05 01:06:44 +00003887 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003888 return false;
3889 }
3890 return true;
3891}
3892
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003893/// Return true when the instruction sequence within a block is select-cmp-br.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003894static bool isChainSelectCmpBranch(const SelectInst *SI) {
3895 const BasicBlock *BB = SI->getParent();
3896 if (!BB)
3897 return false;
3898 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
3899 if (!BI || BI->getNumSuccessors() != 2)
3900 return false;
3901 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
3902 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
3903 return false;
3904 return true;
3905}
3906
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003907/// \brief True when a select result is replaced by one of its operands
3908/// in select-icmp sequence. This will eventually result in the elimination
3909/// of the select.
3910///
3911/// \param SI Select instruction
3912/// \param Icmp Compare instruction
3913/// \param SIOpd Operand that replaces the select
3914///
3915/// Notes:
3916/// - The replacement is global and requires dominator information
3917/// - The caller is responsible for the actual replacement
3918///
3919/// Example:
3920///
3921/// entry:
3922/// %4 = select i1 %3, %C* %0, %C* null
3923/// %5 = icmp eq %C* %4, null
3924/// br i1 %5, label %9, label %7
3925/// ...
3926/// ; <label>:7 ; preds = %entry
3927/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
3928/// ...
3929///
3930/// can be transformed to
3931///
3932/// %5 = icmp eq %C* %0, null
3933/// %6 = select i1 %3, i1 %5, i1 true
3934/// br i1 %6, label %9, label %7
3935/// ...
3936/// ; <label>:7 ; preds = %entry
3937/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
3938///
3939/// Similar when the first operand of the select is a constant or/and
3940/// the compare is for not equal rather than equal.
3941///
3942/// NOTE: The function is only called when the select and compare constants
3943/// are equal, the optimization can work only for EQ predicates. This is not a
3944/// major restriction since a NE compare should be 'normalized' to an equal
3945/// compare, which usually happens in the combiner and test case
Sanjay Patel53523312016-09-12 14:25:46 +00003946/// select-cmp-br.ll checks for it.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003947bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
3948 const ICmpInst *Icmp,
3949 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00003950 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003951 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
3952 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
3953 // The check for the unique predecessor is not the best that can be
Sanjay Patel53523312016-09-12 14:25:46 +00003954 // done. But it protects efficiently against cases like when SI's
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003955 // home block has two successors, Succ and Succ1, and Succ1 predecessor
3956 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
3957 // replaced can be reached on either path. So the uniqueness check
3958 // guarantees that the path all uses of SI (outside SI's parent) are on
3959 // is disjoint from all other paths out of SI. But that information
3960 // is more expensive to compute, and the trade-off here is in favor
3961 // of compile-time.
3962 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
3963 NumSel++;
3964 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
3965 return true;
3966 }
3967 }
3968 return false;
3969}
3970
Sanjay Patel3151dec2016-09-12 15:24:31 +00003971/// Try to fold the comparison based on range information we can get by checking
3972/// whether bits are known to be zero or one in the inputs.
3973Instruction *InstCombiner::foldICmpUsingKnownBits(ICmpInst &I) {
3974 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3975 Type *Ty = Op0->getType();
Sanjay Patel0531f0a2016-09-12 15:52:28 +00003976 ICmpInst::Predicate Pred = I.getPredicate();
Sanjay Patel3151dec2016-09-12 15:24:31 +00003977
3978 // Get scalar or pointer size.
3979 unsigned BitWidth = Ty->isIntOrIntVectorTy()
3980 ? Ty->getScalarSizeInBits()
3981 : DL.getTypeSizeInBits(Ty->getScalarType());
3982
3983 if (!BitWidth)
3984 return nullptr;
3985
3986 // If this is a normal comparison, it demands all bits. If it is a sign bit
3987 // comparison, it only demands the sign bit.
3988 bool IsSignBit = false;
Sanjay Patelf5887f12016-09-12 16:25:41 +00003989 const APInt *CmpC;
3990 if (match(Op1, m_APInt(CmpC))) {
Sanjay Patel3151dec2016-09-12 15:24:31 +00003991 bool UnusedBit;
Sanjay Patelf5887f12016-09-12 16:25:41 +00003992 IsSignBit = isSignBitCheck(Pred, *CmpC, UnusedBit);
Sanjay Patel3151dec2016-09-12 15:24:31 +00003993 }
3994
3995 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
3996 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
3997
3998 if (SimplifyDemandedBits(I.getOperandUse(0),
Sanjay Pateld93c4c02016-09-15 18:22:25 +00003999 getDemandedBitsLHSMask(I, BitWidth, IsSignBit),
Sanjay Patel3151dec2016-09-12 15:24:31 +00004000 Op0KnownZero, Op0KnownOne, 0))
4001 return &I;
4002
4003 if (SimplifyDemandedBits(I.getOperandUse(1), APInt::getAllOnesValue(BitWidth),
4004 Op1KnownZero, Op1KnownOne, 0))
4005 return &I;
4006
4007 // Given the known and unknown bits, compute a range that the LHS could be
4008 // in. Compute the Min, Max and RHS values based on the known bits. For the
4009 // EQ and NE we use unsigned values.
4010 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
4011 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
4012 if (I.isSigned()) {
Sanjay Pateld93c4c02016-09-15 18:22:25 +00004013 computeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, Op0Min,
Sanjay Patel3151dec2016-09-12 15:24:31 +00004014 Op0Max);
Sanjay Pateld93c4c02016-09-15 18:22:25 +00004015 computeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, Op1Min,
Sanjay Patel3151dec2016-09-12 15:24:31 +00004016 Op1Max);
4017 } else {
Sanjay Pateld93c4c02016-09-15 18:22:25 +00004018 computeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, Op0Min,
Sanjay Patel3151dec2016-09-12 15:24:31 +00004019 Op0Max);
Sanjay Pateld93c4c02016-09-15 18:22:25 +00004020 computeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, Op1Min,
Sanjay Patel3151dec2016-09-12 15:24:31 +00004021 Op1Max);
4022 }
4023
4024 // If Min and Max are known to be the same, then SimplifyDemandedBits
Sanjay Patel0531f0a2016-09-12 15:52:28 +00004025 // figured out that the LHS is a constant. Constant fold this now, so that
4026 // code below can assume that Min != Max.
Sanjay Patel3151dec2016-09-12 15:24:31 +00004027 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Sanjay Patel0531f0a2016-09-12 15:52:28 +00004028 return new ICmpInst(Pred, ConstantInt::get(Op0->getType(), Op0Min), Op1);
Sanjay Patel3151dec2016-09-12 15:24:31 +00004029 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Sanjay Patel0531f0a2016-09-12 15:52:28 +00004030 return new ICmpInst(Pred, Op0, ConstantInt::get(Op1->getType(), Op1Min));
Sanjay Patel3151dec2016-09-12 15:24:31 +00004031
4032 // Based on the range information we know about the LHS, see if we can
4033 // simplify this comparison. For example, (x&4) < 8 is always true.
Sanjay Patel0531f0a2016-09-12 15:52:28 +00004034 switch (Pred) {
Sanjay Patel3151dec2016-09-12 15:24:31 +00004035 default:
4036 llvm_unreachable("Unknown icmp opcode!");
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004037 case ICmpInst::ICMP_EQ:
Sanjay Patel3151dec2016-09-12 15:24:31 +00004038 case ICmpInst::ICMP_NE: {
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004039 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) {
4040 return Pred == CmpInst::ICMP_EQ
4041 ? replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()))
4042 : replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4043 }
Sanjay Patel3151dec2016-09-12 15:24:31 +00004044
Sanjay Patel0531f0a2016-09-12 15:52:28 +00004045 // If all bits are known zero except for one, then we know at most one bit
4046 // is set. If the comparison is against zero, then this is a check to see if
4047 // *that* bit is set.
Sanjay Patel3151dec2016-09-12 15:24:31 +00004048 APInt Op0KnownZeroInverted = ~Op0KnownZero;
4049 if (~Op1KnownZero == 0) {
4050 // If the LHS is an AND with the same constant, look through it.
4051 Value *LHS = nullptr;
Sanjay Patel7577a3d2016-09-15 14:15:47 +00004052 const APInt *LHSC;
4053 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
4054 *LHSC != Op0KnownZeroInverted)
Sanjay Patel3151dec2016-09-12 15:24:31 +00004055 LHS = Op0;
4056
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004057 Value *X;
Sanjay Patel3151dec2016-09-12 15:24:31 +00004058 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
4059 APInt ValToCheck = Op0KnownZeroInverted;
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004060 Type *XTy = X->getType();
Sanjay Patel3151dec2016-09-12 15:24:31 +00004061 if (ValToCheck.isPowerOf2()) {
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004062 // ((1 << X) & 8) == 0 -> X != 3
4063 // ((1 << X) & 8) != 0 -> X == 3
4064 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros());
4065 auto NewPred = ICmpInst::getInversePredicate(Pred);
4066 return new ICmpInst(NewPred, X, CmpC);
Sanjay Patel3151dec2016-09-12 15:24:31 +00004067 } else if ((++ValToCheck).isPowerOf2()) {
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004068 // ((1 << X) & 7) == 0 -> X >= 3
4069 // ((1 << X) & 7) != 0 -> X < 3
4070 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros());
4071 auto NewPred =
4072 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
4073 return new ICmpInst(NewPred, X, CmpC);
Sanjay Patel3151dec2016-09-12 15:24:31 +00004074 }
4075 }
4076
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004077 // 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 +00004078 const APInt *CI;
4079 if (Op0KnownZeroInverted == 1 &&
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004080 match(LHS, m_LShr(m_Power2(CI), m_Value(X)))) {
4081 // ((8 >>u X) & 1) == 0 -> X != 3
4082 // ((8 >>u X) & 1) != 0 -> X == 3
4083 unsigned CmpVal = CI->countTrailingZeros();
4084 auto NewPred = ICmpInst::getInversePredicate(Pred);
4085 return new ICmpInst(NewPred, X, ConstantInt::get(X->getType(), CmpVal));
4086 }
Sanjay Patel3151dec2016-09-12 15:24:31 +00004087 }
4088 break;
4089 }
4090 case ICmpInst::ICMP_ULT: {
4091 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
4092 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4093 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
4094 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4095 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
4096 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4097
4098 const APInt *CmpC;
4099 if (match(Op1, m_APInt(CmpC))) {
4100 // A <u C -> A == C-1 if min(A)+1 == C
4101 if (Op1Max == Op0Min + 1) {
4102 Constant *CMinus1 = ConstantInt::get(Op0->getType(), *CmpC - 1);
4103 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, CMinus1);
4104 }
Sanjay Patel3151dec2016-09-12 15:24:31 +00004105 }
4106 break;
4107 }
4108 case ICmpInst::ICMP_UGT: {
4109 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
4110 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4111
4112 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
4113 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4114
4115 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
4116 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4117
4118 const APInt *CmpC;
4119 if (match(Op1, m_APInt(CmpC))) {
4120 // A >u C -> A == C+1 if max(a)-1 == C
4121 if (*CmpC == Op0Max - 1)
4122 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4123 ConstantInt::get(Op1->getType(), *CmpC + 1));
Sanjay Patel3151dec2016-09-12 15:24:31 +00004124 }
4125 break;
4126 }
4127 case ICmpInst::ICMP_SLT:
4128 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
4129 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4130 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
4131 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4132 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
4133 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4134 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4135 if (Op1Max == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
4136 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4137 Builder->getInt(CI->getValue() - 1));
4138 }
4139 break;
4140 case ICmpInst::ICMP_SGT:
4141 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
4142 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4143 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
4144 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4145
4146 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
4147 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4148 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4149 if (Op1Min == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
4150 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4151 Builder->getInt(CI->getValue() + 1));
4152 }
4153 break;
4154 case ICmpInst::ICMP_SGE:
4155 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
4156 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
4157 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4158 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
4159 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4160 break;
4161 case ICmpInst::ICMP_SLE:
4162 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
4163 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
4164 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4165 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
4166 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4167 break;
4168 case ICmpInst::ICMP_UGE:
4169 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
4170 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
4171 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4172 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
4173 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4174 break;
4175 case ICmpInst::ICMP_ULE:
4176 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
4177 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
4178 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4179 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
4180 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4181 break;
4182 }
4183
4184 // Turn a signed comparison into an unsigned one if both operands are known to
4185 // have the same sign.
4186 if (I.isSigned() &&
4187 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
4188 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
4189 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
4190
4191 return nullptr;
4192}
4193
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004194/// If we have an icmp le or icmp ge instruction with a constant operand, turn
4195/// it into the appropriate icmp lt or icmp gt instruction. This transform
4196/// allows them to be folded in visitICmpInst.
Sanjay Patele9b2c322016-05-17 00:57:57 +00004197static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
4198 ICmpInst::Predicate Pred = I.getPredicate();
4199 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE &&
4200 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE)
4201 return nullptr;
4202
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004203 Value *Op0 = I.getOperand(0);
4204 Value *Op1 = I.getOperand(1);
Sanjay Patele9b2c322016-05-17 00:57:57 +00004205 auto *Op1C = dyn_cast<Constant>(Op1);
4206 if (!Op1C)
4207 return nullptr;
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004208
Sanjay Patele9b2c322016-05-17 00:57:57 +00004209 // Check if the constant operand can be safely incremented/decremented without
4210 // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled
4211 // the edge cases for us, so we just assert on them. For vectors, we must
4212 // handle the edge cases.
4213 Type *Op1Type = Op1->getType();
4214 bool IsSigned = I.isSigned();
4215 bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE);
Sanjay Patel18254932016-05-17 01:12:31 +00004216 auto *CI = dyn_cast<ConstantInt>(Op1C);
4217 if (CI) {
Sanjay Patele9b2c322016-05-17 00:57:57 +00004218 // A <= MAX -> TRUE ; A >= MIN -> TRUE
4219 assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned));
4220 } else if (Op1Type->isVectorTy()) {
Sanjay Patelb79ab272016-05-13 15:10:46 +00004221 // TODO? If the edge cases for vectors were guaranteed to be handled as they
Sanjay Patele9b2c322016-05-17 00:57:57 +00004222 // are for scalar, we could remove the min/max checks. However, to do that,
4223 // we would have to use insertelement/shufflevector to replace edge values.
4224 unsigned NumElts = Op1Type->getVectorNumElements();
4225 for (unsigned i = 0; i != NumElts; ++i) {
4226 Constant *Elt = Op1C->getAggregateElement(i);
Benjamin Kramerca9a0fe2016-05-17 12:08:55 +00004227 if (!Elt)
4228 return nullptr;
4229
Sanjay Patele9b2c322016-05-17 00:57:57 +00004230 if (isa<UndefValue>(Elt))
4231 continue;
Sanjay Patel06b127a2016-09-15 14:37:50 +00004232
Sanjay Patele9b2c322016-05-17 00:57:57 +00004233 // Bail out if we can't determine if this constant is min/max or if we
4234 // know that this constant is min/max.
4235 auto *CI = dyn_cast<ConstantInt>(Elt);
4236 if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned)))
4237 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00004238 }
Sanjay Patele9b2c322016-05-17 00:57:57 +00004239 } else {
4240 // ConstantExpr?
4241 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00004242 }
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004243
Sanjay Patele9b2c322016-05-17 00:57:57 +00004244 // Increment or decrement the constant and set the new comparison predicate:
4245 // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT
Sanjay Patel22b01fe2016-05-17 20:20:40 +00004246 Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true);
Sanjay Patele9b2c322016-05-17 00:57:57 +00004247 CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT;
4248 NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred;
4249 return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne));
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004250}
4251
Chris Lattner2188e402010-01-04 07:37:31 +00004252Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4253 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00004254 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00004255 unsigned Op0Cplxity = getComplexity(Op0);
4256 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004257
Chris Lattner2188e402010-01-04 07:37:31 +00004258 /// Orders the operands of the compare so that they are listed from most
4259 /// complex to least complex. This puts constants before unary operators,
4260 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00004261 if (Op0Cplxity < Op1Cplxity ||
Sanjay Patel4c204232016-06-04 20:39:22 +00004262 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00004263 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00004264 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00004265 Changed = true;
4266 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004267
Jingyue Wu5e34ce32015-06-25 20:14:47 +00004268 if (Value *V =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004269 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004270 return replaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004271
Pete Cooperbc5c5242011-12-01 03:58:40 +00004272 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00004273 // ie, abs(val) != 0 -> val != 0
Sanjay Patel4c204232016-06-04 20:39:22 +00004274 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
Pete Cooperfdddc272011-12-01 19:13:26 +00004275 Value *Cond, *SelectTrue, *SelectFalse;
4276 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00004277 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00004278 if (Value *V = dyn_castNegVal(SelectTrue)) {
4279 if (V == SelectFalse)
4280 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
4281 }
4282 else if (Value *V = dyn_castNegVal(SelectFalse)) {
4283 if (V == SelectTrue)
4284 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00004285 }
4286 }
4287 }
4288
Chris Lattner229907c2011-07-18 04:54:35 +00004289 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00004290
4291 // icmp's with boolean values can always be turned into bitwise operations
Sanjay Patela6fbc822016-06-05 17:49:45 +00004292 if (Ty->getScalarType()->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00004293 switch (I.getPredicate()) {
4294 default: llvm_unreachable("Invalid icmp instruction!");
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004295 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
4296 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00004297 return BinaryOperator::CreateNot(Xor);
4298 }
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004299 case ICmpInst::ICMP_NE: // icmp ne i1 A, B -> A^B
Chris Lattner2188e402010-01-04 07:37:31 +00004300 return BinaryOperator::CreateXor(Op0, Op1);
4301
4302 case ICmpInst::ICMP_UGT:
4303 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004304 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004305 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
4306 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00004307 return BinaryOperator::CreateAnd(Not, Op1);
4308 }
4309 case ICmpInst::ICMP_SGT:
4310 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004311 LLVM_FALLTHROUGH;
Chris Lattner2188e402010-01-04 07:37:31 +00004312 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004313 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00004314 return BinaryOperator::CreateAnd(Not, Op0);
4315 }
4316 case ICmpInst::ICMP_UGE:
4317 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004318 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004319 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
4320 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00004321 return BinaryOperator::CreateOr(Not, Op1);
4322 }
4323 case ICmpInst::ICMP_SGE:
4324 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004325 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004326 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
4327 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00004328 return BinaryOperator::CreateOr(Not, Op0);
4329 }
4330 }
4331 }
4332
Sanjay Patele9b2c322016-05-17 00:57:57 +00004333 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004334 return NewICmp;
4335
Sanjay Patel06b127a2016-09-15 14:37:50 +00004336 if (Instruction *Res = foldICmpWithConstant(I))
4337 return Res;
Chris Lattner2188e402010-01-04 07:37:31 +00004338
Sanjay Patel3151dec2016-09-12 15:24:31 +00004339 if (Instruction *Res = foldICmpUsingKnownBits(I))
4340 return Res;
Chris Lattner2188e402010-01-04 07:37:31 +00004341
4342 // Test if the ICmpInst instruction is used exclusively by a select as
4343 // part of a minimum or maximum operation. If so, refrain from doing
4344 // any other folding. This helps out other analyses which understand
4345 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4346 // and CodeGen. And in this case, at least one of the comparison
4347 // operands has at least one user besides the compare (the select),
4348 // which would often largely negate the benefit of folding anyway.
4349 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00004350 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00004351 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4352 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00004353 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004354
Sanjay Patelfebcb9c2017-01-27 23:26:27 +00004355 // FIXME: We only do this after checking for min/max to prevent infinite
4356 // looping caused by a reverse canonicalization of these patterns for min/max.
4357 // FIXME: The organization of folds is a mess. These would naturally go into
4358 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
4359 // down here after the min/max restriction.
4360 ICmpInst::Predicate Pred = I.getPredicate();
4361 const APInt *C;
4362 if (match(Op1, m_APInt(C))) {
4363 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
4364 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
4365 Constant *Zero = Constant::getNullValue(Op0->getType());
4366 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
4367 }
4368
4369 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
4370 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
4371 Constant *AllOnes = Constant::getAllOnesValue(Op0->getType());
4372 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
4373 }
4374 }
4375
Sanjay Patelf58f68c2016-09-10 15:03:44 +00004376 if (Instruction *Res = foldICmpInstWithConstant(I))
Sanjay Patel1271bf92016-07-23 13:06:49 +00004377 return Res;
4378
Sanjay Patel10494b22016-09-16 16:10:22 +00004379 if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
4380 return Res;
Chris Lattner2188e402010-01-04 07:37:31 +00004381
4382 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
4383 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Sanjay Patel43395062016-07-21 18:07:40 +00004384 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner2188e402010-01-04 07:37:31 +00004385 return NI;
4386 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00004387 if (Instruction *NI = foldGEPICmp(GEP, Op0,
Chris Lattner2188e402010-01-04 07:37:31 +00004388 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
4389 return NI;
4390
Hans Wennborgf1f36512015-10-07 00:20:07 +00004391 // Try to optimize equality comparisons against alloca-based pointers.
4392 if (Op0->getType()->isPointerTy() && I.isEquality()) {
4393 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
4394 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00004395 if (Instruction *New = foldAllocaCmp(I, Alloca, Op1))
Hans Wennborgf1f36512015-10-07 00:20:07 +00004396 return New;
4397 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00004398 if (Instruction *New = foldAllocaCmp(I, Alloca, Op0))
Hans Wennborgf1f36512015-10-07 00:20:07 +00004399 return New;
4400 }
4401
Chris Lattner2188e402010-01-04 07:37:31 +00004402 // Test to see if the operands of the icmp are casted versions of other
4403 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
4404 // now.
4405 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00004406 if (Op0->getType()->isPointerTy() &&
4407 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00004408 // We keep moving the cast from the left operand over to the right
4409 // operand, where it can often be eliminated completely.
4410 Op0 = CI->getOperand(0);
4411
4412 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
4413 // so eliminate it as well.
4414 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
4415 Op1 = CI2->getOperand(0);
4416
4417 // If Op1 is a constant, we can fold the cast into the constant.
4418 if (Op0->getType() != Op1->getType()) {
4419 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4420 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
4421 } else {
4422 // Otherwise, cast the RHS right before the icmp
4423 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
4424 }
4425 }
4426 return new ICmpInst(I.getPredicate(), Op0, Op1);
4427 }
4428 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004429
Chris Lattner2188e402010-01-04 07:37:31 +00004430 if (isa<CastInst>(Op0)) {
4431 // Handle the special case of: icmp (cast bool to X), <cst>
4432 // This comes up when you have code like
4433 // int X = A < B;
4434 // if (X) ...
4435 // For generality, we handle any zero-extension of any operand comparison
4436 // with a constant or another cast from the same type.
4437 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00004438 if (Instruction *R = foldICmpWithCastAndCast(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004439 return R;
4440 }
Chris Lattner2188e402010-01-04 07:37:31 +00004441
Sanjay Patel10494b22016-09-16 16:10:22 +00004442 if (Instruction *Res = foldICmpBinOp(I))
4443 return Res;
Duncan Sandse5220012011-02-17 07:46:37 +00004444
Sanjay Pateldd46b522016-12-19 17:32:37 +00004445 if (Instruction *Res = foldICmpWithMinMax(I))
Sanjay Pateld6406412016-12-15 19:13:37 +00004446 return Res;
4447
Sanjay Patel10494b22016-09-16 16:10:22 +00004448 {
4449 Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00004450 // Transform (A & ~B) == 0 --> (A & B) != 0
4451 // and (A & ~B) != 0 --> (A & B) == 0
4452 // if A is a power of 2.
4453 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00004454 match(Op1, m_Zero()) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004455 isKnownToBeAPowerOfTwo(A, DL, false, 0, &AC, &I, &DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00004456 return new ICmpInst(I.getInversePredicate(),
4457 Builder->CreateAnd(A, B),
4458 Op1);
4459
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004460 // ~x < ~y --> y < x
4461 // ~x < cst --> ~cst < x
4462 if (match(Op0, m_Not(m_Value(A)))) {
4463 if (match(Op1, m_Not(m_Value(B))))
4464 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00004465 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004466 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
4467 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00004468
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004469 Instruction *AddI = nullptr;
4470 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
4471 m_Instruction(AddI))) &&
4472 isa<IntegerType>(A->getType())) {
4473 Value *Result;
4474 Constant *Overflow;
4475 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
4476 Overflow)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004477 replaceInstUsesWith(*AddI, Result);
4478 return replaceInstUsesWith(I, Overflow);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004479 }
4480 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004481
4482 // (zext a) * (zext b) --> llvm.umul.with.overflow.
4483 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
Sanjay Pateld93c4c02016-09-15 18:22:25 +00004484 if (Instruction *R = processUMulZExtIdiom(I, Op0, Op1, *this))
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004485 return R;
4486 }
4487 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
Sanjay Pateld93c4c02016-09-15 18:22:25 +00004488 if (Instruction *R = processUMulZExtIdiom(I, Op1, Op0, *this))
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004489 return R;
4490 }
Chris Lattner2188e402010-01-04 07:37:31 +00004491 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004492
Sanjay Patel10494b22016-09-16 16:10:22 +00004493 if (Instruction *Res = foldICmpEquality(I))
4494 return Res;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004495
David Majnemerc1eca5a2014-11-06 23:23:30 +00004496 // The 'cmpxchg' instruction returns an aggregate containing the old value and
4497 // an i1 which indicates whether or not we successfully did the swap.
4498 //
4499 // Replace comparisons between the old value and the expected value with the
4500 // indicator that 'cmpxchg' returns.
4501 //
4502 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
4503 // spuriously fail. In those cases, the old value may equal the expected
4504 // value but it is possible for the swap to not occur.
4505 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4506 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4507 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4508 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4509 !ACXI->isWeak())
4510 return ExtractValueInst::Create(ACXI, 1);
4511
Chris Lattner2188e402010-01-04 07:37:31 +00004512 {
4513 Value *X; ConstantInt *Cst;
4514 // icmp X+Cst, X
4515 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004516 return foldICmpAddOpConst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004517
4518 // icmp X, X+Cst
4519 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004520 return foldICmpAddOpConst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004521 }
Craig Topperf40110f2014-04-25 05:29:35 +00004522 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004523}
4524
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004525/// Fold fcmp ([us]itofp x, cst) if possible.
Sanjay Patel43395062016-07-21 18:07:40 +00004526Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
Chris Lattner2188e402010-01-04 07:37:31 +00004527 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00004528 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004529 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004530
Chris Lattner2188e402010-01-04 07:37:31 +00004531 // Get the width of the mantissa. We don't want to hack on conversions that
4532 // might lose information from the integer, e.g. "i64 -> float"
4533 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00004534 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004535
Matt Arsenault55e73122015-01-06 15:50:59 +00004536 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4537
Chris Lattner2188e402010-01-04 07:37:31 +00004538 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004539
Matt Arsenault55e73122015-01-06 15:50:59 +00004540 if (I.isEquality()) {
4541 FCmpInst::Predicate P = I.getPredicate();
4542 bool IsExact = false;
4543 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
4544 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
4545
4546 // If the floating point constant isn't an integer value, we know if we will
4547 // ever compare equal / not equal to it.
4548 if (!IsExact) {
4549 // TODO: Can never be -0.0 and other non-representable values
4550 APFloat RHSRoundInt(RHS);
4551 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
4552 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
4553 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00004554 return replaceInstUsesWith(I, Builder->getFalse());
Matt Arsenault55e73122015-01-06 15:50:59 +00004555
4556 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
Sanjay Patel4b198802016-02-01 22:23:39 +00004557 return replaceInstUsesWith(I, Builder->getTrue());
Matt Arsenault55e73122015-01-06 15:50:59 +00004558 }
4559 }
4560
4561 // TODO: If the constant is exactly representable, is it always OK to do
4562 // equality compares as integer?
4563 }
4564
Arch D. Robison8ed08542015-09-15 17:51:59 +00004565 // Check to see that the input is converted from an integer type that is small
4566 // enough that preserves all bits. TODO: check here for "known" sign bits.
4567 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4568 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00004569
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004570 // Following test does NOT adjust InputSize downwards for signed inputs,
4571 // because the most negative value still requires all the mantissa bits
Arch D. Robison8ed08542015-09-15 17:51:59 +00004572 // to distinguish it from one less than that value.
4573 if ((int)InputSize > MantissaWidth) {
4574 // Conversion would lose accuracy. Check if loss can impact comparison.
4575 int Exp = ilogb(RHS);
4576 if (Exp == APFloat::IEK_Inf) {
4577 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004578 if (MaxExponent < (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004579 // Conversion could create infinity.
4580 return nullptr;
4581 } else {
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004582 // Note that if RHS is zero or NaN, then Exp is negative
Arch D. Robison8ed08542015-09-15 17:51:59 +00004583 // and first condition is trivially false.
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004584 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004585 // Conversion could affect comparison.
4586 return nullptr;
4587 }
4588 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004589
Chris Lattner2188e402010-01-04 07:37:31 +00004590 // Otherwise, we can potentially simplify the comparison. We know that it
4591 // will always come through as an integer value and we know the constant is
4592 // not a NAN (it would have been previously simplified).
4593 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00004594
Chris Lattner2188e402010-01-04 07:37:31 +00004595 ICmpInst::Predicate Pred;
4596 switch (I.getPredicate()) {
4597 default: llvm_unreachable("Unexpected predicate!");
4598 case FCmpInst::FCMP_UEQ:
4599 case FCmpInst::FCMP_OEQ:
4600 Pred = ICmpInst::ICMP_EQ;
4601 break;
4602 case FCmpInst::FCMP_UGT:
4603 case FCmpInst::FCMP_OGT:
4604 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4605 break;
4606 case FCmpInst::FCMP_UGE:
4607 case FCmpInst::FCMP_OGE:
4608 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4609 break;
4610 case FCmpInst::FCMP_ULT:
4611 case FCmpInst::FCMP_OLT:
4612 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4613 break;
4614 case FCmpInst::FCMP_ULE:
4615 case FCmpInst::FCMP_OLE:
4616 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4617 break;
4618 case FCmpInst::FCMP_UNE:
4619 case FCmpInst::FCMP_ONE:
4620 Pred = ICmpInst::ICMP_NE;
4621 break;
4622 case FCmpInst::FCMP_ORD:
Sanjay Patel4b198802016-02-01 22:23:39 +00004623 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004624 case FCmpInst::FCMP_UNO:
Sanjay Patel4b198802016-02-01 22:23:39 +00004625 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004626 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004627
Chris Lattner2188e402010-01-04 07:37:31 +00004628 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004629
Chris Lattner2188e402010-01-04 07:37:31 +00004630 // See if the FP constant is too large for the integer. For example,
4631 // comparing an i8 to 300.0.
4632 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004633
Chris Lattner2188e402010-01-04 07:37:31 +00004634 if (!LHSUnsigned) {
4635 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4636 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004637 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004638 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4639 APFloat::rmNearestTiesToEven);
4640 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4641 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4642 Pred == ICmpInst::ICMP_SLE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004643 return replaceInstUsesWith(I, Builder->getTrue());
4644 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004645 }
4646 } else {
4647 // If the RHS value is > UnsignedMax, fold the comparison. This handles
4648 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004649 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004650 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4651 APFloat::rmNearestTiesToEven);
4652 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
4653 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
4654 Pred == ICmpInst::ICMP_ULE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004655 return replaceInstUsesWith(I, Builder->getTrue());
4656 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004657 }
4658 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004659
Chris Lattner2188e402010-01-04 07:37:31 +00004660 if (!LHSUnsigned) {
4661 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004662 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004663 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4664 APFloat::rmNearestTiesToEven);
4665 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4666 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4667 Pred == ICmpInst::ICMP_SGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004668 return replaceInstUsesWith(I, Builder->getTrue());
4669 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004670 }
Devang Patel698452b2012-02-13 23:05:18 +00004671 } else {
4672 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004673 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00004674 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
4675 APFloat::rmNearestTiesToEven);
4676 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
4677 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
4678 Pred == ICmpInst::ICMP_UGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004679 return replaceInstUsesWith(I, Builder->getTrue());
4680 return replaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00004681 }
Chris Lattner2188e402010-01-04 07:37:31 +00004682 }
4683
4684 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4685 // [0, UMAX], but it may still be fractional. See if it is fractional by
4686 // casting the FP value to the integer value and back, checking for equality.
4687 // Don't do this for zero, because -0.0 is not fractional.
4688 Constant *RHSInt = LHSUnsigned
4689 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4690 : ConstantExpr::getFPToSI(RHSC, IntTy);
4691 if (!RHS.isZero()) {
4692 bool Equal = LHSUnsigned
4693 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4694 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4695 if (!Equal) {
4696 // If we had a comparison against a fractional value, we have to adjust
4697 // the compare predicate and sometimes the value. RHSC is rounded towards
4698 // zero at this point.
4699 switch (Pred) {
4700 default: llvm_unreachable("Unexpected integer comparison!");
4701 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Sanjay Patel4b198802016-02-01 22:23:39 +00004702 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004703 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Sanjay Patel4b198802016-02-01 22:23:39 +00004704 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004705 case ICmpInst::ICMP_ULE:
4706 // (float)int <= 4.4 --> int <= 4
4707 // (float)int <= -4.4 --> false
4708 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004709 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004710 break;
4711 case ICmpInst::ICMP_SLE:
4712 // (float)int <= 4.4 --> int <= 4
4713 // (float)int <= -4.4 --> int < -4
4714 if (RHS.isNegative())
4715 Pred = ICmpInst::ICMP_SLT;
4716 break;
4717 case ICmpInst::ICMP_ULT:
4718 // (float)int < -4.4 --> false
4719 // (float)int < 4.4 --> int <= 4
4720 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004721 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004722 Pred = ICmpInst::ICMP_ULE;
4723 break;
4724 case ICmpInst::ICMP_SLT:
4725 // (float)int < -4.4 --> int < -4
4726 // (float)int < 4.4 --> int <= 4
4727 if (!RHS.isNegative())
4728 Pred = ICmpInst::ICMP_SLE;
4729 break;
4730 case ICmpInst::ICMP_UGT:
4731 // (float)int > 4.4 --> int > 4
4732 // (float)int > -4.4 --> true
4733 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004734 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004735 break;
4736 case ICmpInst::ICMP_SGT:
4737 // (float)int > 4.4 --> int > 4
4738 // (float)int > -4.4 --> int >= -4
4739 if (RHS.isNegative())
4740 Pred = ICmpInst::ICMP_SGE;
4741 break;
4742 case ICmpInst::ICMP_UGE:
4743 // (float)int >= -4.4 --> true
4744 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00004745 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004746 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004747 Pred = ICmpInst::ICMP_UGT;
4748 break;
4749 case ICmpInst::ICMP_SGE:
4750 // (float)int >= -4.4 --> int >= -4
4751 // (float)int >= 4.4 --> int > 4
4752 if (!RHS.isNegative())
4753 Pred = ICmpInst::ICMP_SGT;
4754 break;
4755 }
4756 }
4757 }
4758
4759 // Lower this FP comparison into an appropriate integer version of the
4760 // comparison.
4761 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4762}
4763
4764Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4765 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004766
Chris Lattner2188e402010-01-04 07:37:31 +00004767 /// Orders the operands of the compare so that they are listed from most
4768 /// complex to least complex. This puts constants before unary operators,
4769 /// before binary operators.
4770 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4771 I.swapOperands();
4772 Changed = true;
4773 }
4774
4775 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004776
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004777 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004778 I.getFastMathFlags(), DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004779 return replaceInstUsesWith(I, V);
Chris Lattner2188e402010-01-04 07:37:31 +00004780
4781 // Simplify 'fcmp pred X, X'
4782 if (Op0 == Op1) {
4783 switch (I.getPredicate()) {
4784 default: llvm_unreachable("Unknown predicate!");
4785 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4786 case FCmpInst::FCMP_ULT: // True if unordered or less than
4787 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4788 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4789 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4790 I.setPredicate(FCmpInst::FCMP_UNO);
4791 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4792 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004793
Chris Lattner2188e402010-01-04 07:37:31 +00004794 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4795 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4796 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4797 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4798 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4799 I.setPredicate(FCmpInst::FCMP_ORD);
4800 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4801 return &I;
4802 }
4803 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004804
James Molloy2b21a7c2015-05-20 18:41:25 +00004805 // Test if the FCmpInst instruction is used exclusively by a select as
4806 // part of a minimum or maximum operation. If so, refrain from doing
4807 // any other folding. This helps out other analyses which understand
4808 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4809 // and CodeGen. And in this case, at least one of the comparison
4810 // operands has at least one user besides the compare (the select),
4811 // which would often largely negate the benefit of folding anyway.
4812 if (I.hasOneUse())
4813 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4814 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4815 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4816 return nullptr;
4817
Chris Lattner2188e402010-01-04 07:37:31 +00004818 // Handle fcmp with constant RHS
4819 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4820 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4821 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004822 case Instruction::FPExt: {
4823 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4824 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4825 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4826 if (!RHSF)
4827 break;
4828
4829 const fltSemantics *Sem;
4830 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004831 if (LHSExt->getSrcTy()->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004832 Sem = &APFloat::IEEEhalf();
Dan Gohman518cda42011-12-17 00:04:22 +00004833 else if (LHSExt->getSrcTy()->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004834 Sem = &APFloat::IEEEsingle();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004835 else if (LHSExt->getSrcTy()->isDoubleTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004836 Sem = &APFloat::IEEEdouble();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004837 else if (LHSExt->getSrcTy()->isFP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004838 Sem = &APFloat::IEEEquad();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004839 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004840 Sem = &APFloat::x87DoubleExtended();
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004841 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004842 Sem = &APFloat::PPCDoubleDouble();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004843 else
4844 break;
4845
4846 bool Lossy;
4847 APFloat F = RHSF->getValueAPF();
4848 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4849
Jim Grosbach24ff8342011-09-30 18:45:50 +00004850 // Avoid lossy conversions and denormals. Zero is a special case
4851 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004852 APFloat Fabs = F;
4853 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004854 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004855 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4856 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004857
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004858 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4859 ConstantFP::get(RHSC->getContext(), F));
4860 break;
4861 }
Chris Lattner2188e402010-01-04 07:37:31 +00004862 case Instruction::PHI:
4863 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4864 // block. If in the same block, we're encouraging jump threading. If
4865 // not, we are just pessimizing the code by making an i1 phi.
4866 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004867 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004868 return NV;
4869 break;
4870 case Instruction::SIToFP:
4871 case Instruction::UIToFP:
Sanjay Patel43395062016-07-21 18:07:40 +00004872 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
Chris Lattner2188e402010-01-04 07:37:31 +00004873 return NV;
4874 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004875 case Instruction::FSub: {
4876 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4877 Value *Op;
4878 if (match(LHSI, m_FNeg(m_Value(Op))))
4879 return new FCmpInst(I.getSwappedPredicate(), Op,
4880 ConstantExpr::getFNeg(RHSC));
4881 break;
4882 }
Dan Gohman94732022010-02-24 06:46:09 +00004883 case Instruction::Load:
4884 if (GetElementPtrInst *GEP =
4885 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4886 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4887 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4888 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00004889 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Dan Gohman94732022010-02-24 06:46:09 +00004890 return Res;
4891 }
4892 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004893 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004894 if (!RHSC->isNullValue())
4895 break;
4896
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004897 CallInst *CI = cast<CallInst>(LHSI);
Justin Bogner99798402016-08-05 01:06:44 +00004898 Intrinsic::ID IID = getIntrinsicForCallSite(CI, &TLI);
David Majnemer2e02ba72016-04-15 17:21:03 +00004899 if (IID != Intrinsic::fabs)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004900 break;
4901
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004902 // Various optimization for fabs compared with zero.
David Majnemer2e02ba72016-04-15 17:21:03 +00004903 switch (I.getPredicate()) {
4904 default:
4905 break;
4906 // fabs(x) < 0 --> false
4907 case FCmpInst::FCMP_OLT:
4908 llvm_unreachable("handled by SimplifyFCmpInst");
4909 // fabs(x) > 0 --> x != 0
4910 case FCmpInst::FCMP_OGT:
4911 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
4912 // fabs(x) <= 0 --> x == 0
4913 case FCmpInst::FCMP_OLE:
4914 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
4915 // fabs(x) >= 0 --> !isnan(x)
4916 case FCmpInst::FCMP_OGE:
4917 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
4918 // fabs(x) == 0 --> x == 0
4919 // fabs(x) != 0 --> x != 0
4920 case FCmpInst::FCMP_OEQ:
4921 case FCmpInst::FCMP_UEQ:
4922 case FCmpInst::FCMP_ONE:
4923 case FCmpInst::FCMP_UNE:
4924 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004925 }
4926 }
Chris Lattner2188e402010-01-04 07:37:31 +00004927 }
Chris Lattner2188e402010-01-04 07:37:31 +00004928 }
4929
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004930 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004931 Value *X, *Y;
4932 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004933 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004934
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004935 // fcmp (fpext x), (fpext y) -> fcmp x, y
4936 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4937 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4938 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4939 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4940 RHSExt->getOperand(0));
4941
Craig Topperf40110f2014-04-25 05:29:35 +00004942 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004943}