blob: 2daaa2da4ae4c479dfc358b56af3ddb38405bcb5 [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();
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002375 auto CR =
2376 ConstantRange::makeExactICmpRegion(Cmp.getPredicate(), *C).subtract(*C2);
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002377 const APInt &Upper = CR.getUpper();
2378 const APInt &Lower = CR.getLower();
2379 if (Cmp.isSigned()) {
2380 if (Lower.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002381 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002382 if (Upper.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002383 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002384 } else {
2385 if (Lower.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002386 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002387 if (Upper.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002388 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002389 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002390
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002391 if (!Add->hasOneUse())
2392 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002393
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002394 // X+C <u C2 -> (X & -C2) == C
2395 // iff C & (C2-1) == 0
2396 // C2 is a power of 2
2397 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && C->isPowerOf2() &&
2398 (*C2 & (*C - 1)) == 0)
2399 return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateAnd(X, -(*C)),
2400 ConstantExpr::getNeg(cast<Constant>(Y)));
2401
2402 // X+C >u C2 -> (X & ~C2) != C
2403 // iff C & C2 == 0
2404 // C2+1 is a power of 2
2405 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() &&
2406 (*C2 & *C) == 0)
2407 return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateAnd(X, ~(*C)),
2408 ConstantExpr::getNeg(cast<Constant>(Y)));
2409
Sanjay Patela3f4f082016-08-16 17:54:36 +00002410 return nullptr;
2411}
2412
Sanjay Patelf58f68c2016-09-10 15:03:44 +00002413/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
2414/// where X is some kind of instruction.
2415Instruction *InstCombiner::foldICmpInstWithConstant(ICmpInst &Cmp) {
Sanjay Patelc9196c42016-08-22 21:24:29 +00002416 const APInt *C;
2417 if (!match(Cmp.getOperand(1), m_APInt(C)))
Sanjay Patel1e5b2d12016-08-16 16:08:11 +00002418 return nullptr;
2419
Sanjay Patelc9196c42016-08-22 21:24:29 +00002420 BinaryOperator *BO;
2421 if (match(Cmp.getOperand(0), m_BinOp(BO))) {
2422 switch (BO->getOpcode()) {
2423 case Instruction::Xor:
2424 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
2425 return I;
2426 break;
2427 case Instruction::And:
2428 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
2429 return I;
2430 break;
2431 case Instruction::Or:
2432 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
2433 return I;
2434 break;
2435 case Instruction::Mul:
2436 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
2437 return I;
2438 break;
2439 case Instruction::Shl:
2440 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
2441 return I;
2442 break;
2443 case Instruction::LShr:
2444 case Instruction::AShr:
2445 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
2446 return I;
2447 break;
2448 case Instruction::UDiv:
2449 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
2450 return I;
2451 LLVM_FALLTHROUGH;
2452 case Instruction::SDiv:
2453 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
2454 return I;
2455 break;
2456 case Instruction::Sub:
2457 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
2458 return I;
2459 break;
2460 case Instruction::Add:
2461 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
2462 return I;
2463 break;
2464 default:
2465 break;
2466 }
Sanjay Patelf58f68c2016-09-10 15:03:44 +00002467 // TODO: These folds could be refactored to be part of the above calls.
2468 if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, C))
2469 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002470 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002471
Sanjay Patelc9196c42016-08-22 21:24:29 +00002472 Instruction *LHSI;
2473 if (match(Cmp.getOperand(0), m_Instruction(LHSI)) &&
2474 LHSI->getOpcode() == Instruction::Trunc)
2475 if (Instruction *I = foldICmpTruncConstant(Cmp, LHSI, C))
2476 return I;
2477
Sanjay Patelf58f68c2016-09-10 15:03:44 +00002478 if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, C))
2479 return I;
2480
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002481 return nullptr;
2482}
Jim Grosbach129c52a2011-09-30 18:09:53 +00002483
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002484/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
2485/// icmp eq/ne BO, C.
2486Instruction *InstCombiner::foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
2487 BinaryOperator *BO,
2488 const APInt *C) {
2489 // TODO: Some of these folds could work with arbitrary constants, but this
2490 // function is limited to scalar and vector splat constants.
2491 if (!Cmp.isEquality())
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002492 return nullptr;
2493
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002494 ICmpInst::Predicate Pred = Cmp.getPredicate();
2495 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
2496 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
Sanjay Patel51a767c2016-08-03 17:23:08 +00002497 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002498
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002499 switch (BO->getOpcode()) {
2500 case Instruction::SRem:
2501 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002502 if (*C == 0 && BO->hasOneUse()) {
Sanjay Patel2e9675f2016-08-03 19:48:40 +00002503 const APInt *BOC;
2504 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002505 Value *NewRem = Builder->CreateURem(BOp0, BOp1, BO->getName());
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002506 return new ICmpInst(Pred, NewRem,
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002507 Constant::getNullValue(BO->getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002508 }
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002509 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002510 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002511 case Instruction::Add: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002512 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
Sanjay Patel00a324e2016-08-03 22:08:44 +00002513 const APInt *BOC;
2514 if (match(BOp1, m_APInt(BOC))) {
2515 if (BO->hasOneUse()) {
2516 Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1));
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002517 return new ICmpInst(Pred, BOp0, SubC);
Sanjay Patel00a324e2016-08-03 22:08:44 +00002518 }
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002519 } else if (*C == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002520 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2521 // efficiently invertible, or if the add has just this one use.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002522 if (Value *NegVal = dyn_castNegVal(BOp1))
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002523 return new ICmpInst(Pred, BOp0, NegVal);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002524 if (Value *NegVal = dyn_castNegVal(BOp0))
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002525 return new ICmpInst(Pred, NegVal, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002526 if (BO->hasOneUse()) {
2527 Value *Neg = Builder->CreateNeg(BOp1);
2528 Neg->takeName(BO);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002529 return new ICmpInst(Pred, BOp0, Neg);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002530 }
2531 }
2532 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002533 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002534 case Instruction::Xor:
2535 if (BO->hasOneUse()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002536 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002537 // For the xor case, we can xor two constants together, eliminating
2538 // the explicit xor.
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002539 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
2540 } else if (*C == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002541 // Replace ((xor A, B) != 0) with (A != B)
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002542 return new ICmpInst(Pred, BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002543 }
2544 }
2545 break;
2546 case Instruction::Sub:
2547 if (BO->hasOneUse()) {
Sanjay Patel9d591d12016-08-04 15:19:25 +00002548 const APInt *BOC;
2549 if (match(BOp0, m_APInt(BOC))) {
Sanjay Patel362ff5c2016-09-15 17:01:17 +00002550 // Replace ((sub BOC, B) != C) with (B != BOC-C).
Sanjay Patel9d591d12016-08-04 15:19:25 +00002551 Constant *SubC = ConstantExpr::getSub(cast<Constant>(BOp0), RHS);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002552 return new ICmpInst(Pred, BOp1, SubC);
2553 } else if (*C == 0) {
Sanjay Patel362ff5c2016-09-15 17:01:17 +00002554 // Replace ((sub A, B) != 0) with (A != B).
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002555 return new ICmpInst(Pred, BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002556 }
2557 }
2558 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002559 case Instruction::Or: {
2560 const APInt *BOC;
2561 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002562 // Comparing if all bits outside of a constant mask are set?
2563 // Replace (X | C) == -1 with (X & ~C) == ~C.
2564 // This removes the -1 constant.
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002565 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
2566 Value *And = Builder->CreateAnd(BOp0, NotBOC);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002567 return new ICmpInst(Pred, And, NotBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002568 }
2569 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002570 }
Sanjay Pateld938e882016-08-04 20:05:02 +00002571 case Instruction::And: {
2572 const APInt *BOC;
2573 if (match(BOp1, m_APInt(BOC))) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002574 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002575 if (C == BOC && C->isPowerOf2())
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002576 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
Sanjay Patelab50a932016-08-02 22:38:33 +00002577 BO, Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002578
2579 // Don't perform the following transforms if the AND has multiple uses
2580 if (!BO->hasOneUse())
2581 break;
2582
2583 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Sanjay Pateld938e882016-08-04 20:05:02 +00002584 if (BOC->isSignBit()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002585 Constant *Zero = Constant::getNullValue(BOp0->getType());
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002586 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
2587 return new ICmpInst(NewPred, BOp0, Zero);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002588 }
2589
2590 // ((X & ~7) == 0) --> X < 8
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002591 if (*C == 0 && (~(*BOC) + 1).isPowerOf2()) {
Sanjay Pateld938e882016-08-04 20:05:02 +00002592 Constant *NegBOC = ConstantExpr::getNeg(cast<Constant>(BOp1));
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002593 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
2594 return new ICmpInst(NewPred, BOp0, NegBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002595 }
2596 }
2597 break;
Sanjay Pateld938e882016-08-04 20:05:02 +00002598 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002599 case Instruction::Mul:
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002600 if (*C == 0 && BO->hasNoSignedWrap()) {
Sanjay Patel3bade132016-08-04 22:19:27 +00002601 const APInt *BOC;
2602 if (match(BOp1, m_APInt(BOC)) && *BOC != 0) {
2603 // The trivial case (mul X, 0) is handled by InstSimplify.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002604 // General case : (mul X, C) != 0 iff X != 0
2605 // (mul X, C) == 0 iff X == 0
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002606 return new ICmpInst(Pred, BOp0, Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002607 }
2608 }
2609 break;
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002610 case Instruction::UDiv:
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002611 if (*C == 0) {
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002612 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002613 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
2614 return new ICmpInst(NewPred, BOp1, BOp0);
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002615 }
2616 break;
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002617 default:
2618 break;
2619 }
2620 return nullptr;
2621}
2622
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002623/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
2624Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
2625 const APInt *C) {
2626 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0));
2627 if (!II || !Cmp.isEquality())
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002628 return nullptr;
2629
2630 // Handle icmp {eq|ne} <intrinsic>, intcst.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002631 switch (II->getIntrinsicID()) {
2632 case Intrinsic::bswap:
2633 Worklist.Add(II);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002634 Cmp.setOperand(0, II->getArgOperand(0));
2635 Cmp.setOperand(1, Builder->getInt(C->byteSwap()));
2636 return &Cmp;
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002637 case Intrinsic::ctlz:
2638 case Intrinsic::cttz:
Amaury Sechet6bea6742016-08-04 05:27:20 +00002639 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002640 if (*C == C->getBitWidth()) {
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002641 Worklist.Add(II);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002642 Cmp.setOperand(0, II->getArgOperand(0));
2643 Cmp.setOperand(1, ConstantInt::getNullValue(II->getType()));
2644 return &Cmp;
Chris Lattner2188e402010-01-04 07:37:31 +00002645 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002646 break;
Amaury Sechet6bea6742016-08-04 05:27:20 +00002647 case Intrinsic::ctpop: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002648 // popcount(A) == 0 -> A == 0 and likewise for !=
Amaury Sechet6bea6742016-08-04 05:27:20 +00002649 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002650 bool IsZero = *C == 0;
2651 if (IsZero || *C == C->getBitWidth()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002652 Worklist.Add(II);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002653 Cmp.setOperand(0, II->getArgOperand(0));
2654 auto *NewOp = IsZero ? Constant::getNullValue(II->getType())
2655 : Constant::getAllOnesValue(II->getType());
2656 Cmp.setOperand(1, NewOp);
2657 return &Cmp;
Amaury Sechet6bea6742016-08-04 05:27:20 +00002658 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002659 break;
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002660 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002661 default:
2662 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002663 }
Craig Topperf40110f2014-04-25 05:29:35 +00002664 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002665}
2666
Sanjay Patel10494b22016-09-16 16:10:22 +00002667/// Handle icmp with constant (but not simple integer constant) RHS.
2668Instruction *InstCombiner::foldICmpInstWithConstantNotInt(ICmpInst &I) {
2669 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2670 Constant *RHSC = dyn_cast<Constant>(Op1);
2671 Instruction *LHSI = dyn_cast<Instruction>(Op0);
2672 if (!RHSC || !LHSI)
2673 return nullptr;
2674
2675 switch (LHSI->getOpcode()) {
2676 case Instruction::GetElementPtr:
2677 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2678 if (RHSC->isNullValue() &&
2679 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2680 return new ICmpInst(
2681 I.getPredicate(), LHSI->getOperand(0),
2682 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2683 break;
2684 case Instruction::PHI:
2685 // Only fold icmp into the PHI if the phi and icmp are in the same
2686 // block. If in the same block, we're encouraging jump threading. If
2687 // not, we are just pessimizing the code by making an i1 phi.
2688 if (LHSI->getParent() == I.getParent())
2689 if (Instruction *NV = FoldOpIntoPhi(I))
2690 return NV;
2691 break;
2692 case Instruction::Select: {
2693 // If either operand of the select is a constant, we can fold the
2694 // comparison into the select arms, which will cause one to be
2695 // constant folded and the select turned into a bitwise or.
2696 Value *Op1 = nullptr, *Op2 = nullptr;
2697 ConstantInt *CI = nullptr;
2698 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2699 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2700 CI = dyn_cast<ConstantInt>(Op1);
2701 }
2702 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2703 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2704 CI = dyn_cast<ConstantInt>(Op2);
2705 }
2706
2707 // We only want to perform this transformation if it will not lead to
2708 // additional code. This is true if either both sides of the select
2709 // fold to a constant (in which case the icmp is replaced with a select
2710 // which will usually simplify) or this is the only user of the
2711 // select (in which case we are trading a select+icmp for a simpler
2712 // select+icmp) or all uses of the select can be replaced based on
2713 // dominance information ("Global cases").
2714 bool Transform = false;
2715 if (Op1 && Op2)
2716 Transform = true;
2717 else if (Op1 || Op2) {
2718 // Local case
2719 if (LHSI->hasOneUse())
2720 Transform = true;
2721 // Global cases
2722 else if (CI && !CI->isZero())
2723 // When Op1 is constant try replacing select with second operand.
2724 // Otherwise Op2 is constant and try replacing select with first
2725 // operand.
2726 Transform =
2727 replacedSelectWithOperand(cast<SelectInst>(LHSI), &I, Op1 ? 2 : 1);
2728 }
2729 if (Transform) {
2730 if (!Op1)
2731 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1), RHSC,
2732 I.getName());
2733 if (!Op2)
2734 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2), RHSC,
2735 I.getName());
2736 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2737 }
2738 break;
2739 }
2740 case Instruction::IntToPtr:
2741 // icmp pred inttoptr(X), null -> icmp pred X, 0
2742 if (RHSC->isNullValue() &&
2743 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
2744 return new ICmpInst(
2745 I.getPredicate(), LHSI->getOperand(0),
2746 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2747 break;
2748
2749 case Instruction::Load:
2750 // Try to optimize things like "A[i] > 4" to index computations.
2751 if (GetElementPtrInst *GEP =
2752 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2753 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2754 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2755 !cast<LoadInst>(LHSI)->isVolatile())
2756 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
2757 return Res;
2758 }
2759 break;
2760 }
2761
2762 return nullptr;
2763}
2764
2765/// Try to fold icmp (binop), X or icmp X, (binop).
2766Instruction *InstCombiner::foldICmpBinOp(ICmpInst &I) {
2767 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2768
2769 // Special logic for binary operators.
2770 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2771 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2772 if (!BO0 && !BO1)
2773 return nullptr;
2774
2775 CmpInst::Predicate Pred = I.getPredicate();
2776 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2777 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2778 NoOp0WrapProblem =
2779 ICmpInst::isEquality(Pred) ||
2780 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2781 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2782 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2783 NoOp1WrapProblem =
2784 ICmpInst::isEquality(Pred) ||
2785 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2786 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2787
2788 // Analyze the case when either Op0 or Op1 is an add instruction.
2789 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2790 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2791 if (BO0 && BO0->getOpcode() == Instruction::Add) {
2792 A = BO0->getOperand(0);
2793 B = BO0->getOperand(1);
2794 }
2795 if (BO1 && BO1->getOpcode() == Instruction::Add) {
2796 C = BO1->getOperand(0);
2797 D = BO1->getOperand(1);
2798 }
2799
2800 // icmp (X+cst) < 0 --> X < -cst
2801 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
2802 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
2803 if (!RHSC->isMinValue(/*isSigned=*/true))
2804 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
2805
2806 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2807 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2808 return new ICmpInst(Pred, A == Op1 ? B : A,
2809 Constant::getNullValue(Op1->getType()));
2810
2811 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2812 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2813 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2814 C == Op0 ? D : C);
2815
2816 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
2817 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
2818 NoOp1WrapProblem &&
2819 // Try not to increase register pressure.
2820 BO0->hasOneUse() && BO1->hasOneUse()) {
2821 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2822 Value *Y, *Z;
2823 if (A == C) {
2824 // C + B == C + D -> B == D
2825 Y = B;
2826 Z = D;
2827 } else if (A == D) {
2828 // D + B == C + D -> B == C
2829 Y = B;
2830 Z = C;
2831 } else if (B == C) {
2832 // A + C == C + D -> A == D
2833 Y = A;
2834 Z = D;
2835 } else {
2836 assert(B == D);
2837 // A + D == C + D -> A == C
2838 Y = A;
2839 Z = C;
2840 }
2841 return new ICmpInst(Pred, Y, Z);
2842 }
2843
2844 // icmp slt (X + -1), Y -> icmp sle X, Y
2845 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
2846 match(B, m_AllOnes()))
2847 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
2848
2849 // icmp sge (X + -1), Y -> icmp sgt X, Y
2850 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
2851 match(B, m_AllOnes()))
2852 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
2853
2854 // icmp sle (X + 1), Y -> icmp slt X, Y
2855 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One()))
2856 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
2857
2858 // icmp sgt (X + 1), Y -> icmp sge X, Y
2859 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One()))
2860 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
2861
2862 // icmp sgt X, (Y + -1) -> icmp sge X, Y
2863 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
2864 match(D, m_AllOnes()))
2865 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
2866
2867 // icmp sle X, (Y + -1) -> icmp slt X, Y
2868 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
2869 match(D, m_AllOnes()))
2870 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
2871
2872 // icmp sge X, (Y + 1) -> icmp sgt X, Y
2873 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One()))
2874 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
2875
2876 // icmp slt X, (Y + 1) -> icmp sle X, Y
2877 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One()))
2878 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
2879
Sanjay Patel40f40172017-01-13 23:25:46 +00002880 // TODO: The subtraction-related identities shown below also hold, but
2881 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
2882 // wouldn't happen even if they were implemented.
2883 //
2884 // icmp ult (X - 1), Y -> icmp ule X, Y
2885 // icmp uge (X - 1), Y -> icmp ugt X, Y
2886 // icmp ugt X, (Y - 1) -> icmp uge X, Y
2887 // icmp ule X, (Y - 1) -> icmp ult X, Y
2888
2889 // icmp ule (X + 1), Y -> icmp ult X, Y
2890 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One()))
2891 return new ICmpInst(CmpInst::ICMP_ULT, A, Op1);
2892
2893 // icmp ugt (X + 1), Y -> icmp uge X, Y
2894 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One()))
2895 return new ICmpInst(CmpInst::ICMP_UGE, A, Op1);
2896
2897 // icmp uge X, (Y + 1) -> icmp ugt X, Y
2898 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One()))
2899 return new ICmpInst(CmpInst::ICMP_UGT, Op0, C);
2900
2901 // icmp ult X, (Y + 1) -> icmp ule X, Y
2902 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One()))
2903 return new ICmpInst(CmpInst::ICMP_ULE, Op0, C);
2904
Sanjay Patel10494b22016-09-16 16:10:22 +00002905 // if C1 has greater magnitude than C2:
2906 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
2907 // s.t. C3 = C1 - C2
2908 //
2909 // if C2 has greater magnitude than C1:
2910 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
2911 // s.t. C3 = C2 - C1
2912 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
2913 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
2914 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
2915 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
2916 const APInt &AP1 = C1->getValue();
2917 const APInt &AP2 = C2->getValue();
2918 if (AP1.isNegative() == AP2.isNegative()) {
2919 APInt AP1Abs = C1->getValue().abs();
2920 APInt AP2Abs = C2->getValue().abs();
2921 if (AP1Abs.uge(AP2Abs)) {
2922 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
2923 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
2924 return new ICmpInst(Pred, NewAdd, C);
2925 } else {
2926 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
2927 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
2928 return new ICmpInst(Pred, A, NewAdd);
2929 }
2930 }
2931 }
2932
2933 // Analyze the case when either Op0 or Op1 is a sub instruction.
2934 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2935 A = nullptr;
2936 B = nullptr;
2937 C = nullptr;
2938 D = nullptr;
2939 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
2940 A = BO0->getOperand(0);
2941 B = BO0->getOperand(1);
2942 }
2943 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
2944 C = BO1->getOperand(0);
2945 D = BO1->getOperand(1);
2946 }
2947
2948 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2949 if (A == Op1 && NoOp0WrapProblem)
2950 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2951
2952 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2953 if (C == Op0 && NoOp1WrapProblem)
2954 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2955
2956 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
2957 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2958 // Try not to increase register pressure.
2959 BO0->hasOneUse() && BO1->hasOneUse())
2960 return new ICmpInst(Pred, A, C);
2961
2962 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2963 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2964 // Try not to increase register pressure.
2965 BO0->hasOneUse() && BO1->hasOneUse())
2966 return new ICmpInst(Pred, D, B);
2967
2968 // icmp (0-X) < cst --> x > -cst
2969 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
2970 Value *X;
2971 if (match(BO0, m_Neg(m_Value(X))))
2972 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
2973 if (!RHSC->isMinValue(/*isSigned=*/true))
2974 return new ICmpInst(I.getSwappedPredicate(), X,
2975 ConstantExpr::getNeg(RHSC));
2976 }
2977
2978 BinaryOperator *SRem = nullptr;
2979 // icmp (srem X, Y), Y
2980 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
2981 SRem = BO0;
2982 // icmp Y, (srem X, Y)
2983 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2984 Op0 == BO1->getOperand(1))
2985 SRem = BO1;
2986 if (SRem) {
2987 // We don't check hasOneUse to avoid increasing register pressure because
2988 // the value we use is the same value this instruction was already using.
2989 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2990 default:
2991 break;
2992 case ICmpInst::ICMP_EQ:
2993 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2994 case ICmpInst::ICMP_NE:
2995 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2996 case ICmpInst::ICMP_SGT:
2997 case ICmpInst::ICMP_SGE:
2998 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2999 Constant::getAllOnesValue(SRem->getType()));
3000 case ICmpInst::ICMP_SLT:
3001 case ICmpInst::ICMP_SLE:
3002 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
3003 Constant::getNullValue(SRem->getType()));
3004 }
3005 }
3006
3007 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() &&
3008 BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) {
3009 switch (BO0->getOpcode()) {
3010 default:
3011 break;
3012 case Instruction::Add:
3013 case Instruction::Sub:
3014 case Instruction::Xor:
3015 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
3016 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3017 BO1->getOperand(0));
3018 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
3019 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3020 if (CI->getValue().isSignBit()) {
3021 ICmpInst::Predicate Pred =
3022 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate();
3023 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3024 }
3025
3026 if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) {
3027 ICmpInst::Predicate Pred =
3028 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate();
3029 Pred = I.getSwappedPredicate(Pred);
3030 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3031 }
3032 }
3033 break;
3034 case Instruction::Mul:
3035 if (!I.isEquality())
3036 break;
3037
3038 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3039 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
3040 // Mask = -1 >> count-trailing-zeros(Cst).
3041 if (!CI->isZero() && !CI->isOne()) {
3042 const APInt &AP = CI->getValue();
3043 ConstantInt *Mask = ConstantInt::get(
3044 I.getContext(),
3045 APInt::getLowBitsSet(AP.getBitWidth(),
3046 AP.getBitWidth() - AP.countTrailingZeros()));
3047 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
3048 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
3049 return new ICmpInst(I.getPredicate(), And1, And2);
3050 }
3051 }
3052 break;
3053 case Instruction::UDiv:
3054 case Instruction::LShr:
3055 if (I.isSigned())
3056 break;
3057 LLVM_FALLTHROUGH;
3058 case Instruction::SDiv:
3059 case Instruction::AShr:
3060 if (!BO0->isExact() || !BO1->isExact())
3061 break;
3062 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3063 BO1->getOperand(0));
3064 case Instruction::Shl: {
3065 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
3066 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
3067 if (!NUW && !NSW)
3068 break;
3069 if (!NSW && I.isSigned())
3070 break;
3071 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3072 BO1->getOperand(0));
3073 }
3074 }
3075 }
3076
3077 if (BO0) {
3078 // Transform A & (L - 1) `ult` L --> L != 0
3079 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
3080 auto BitwiseAnd =
3081 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
3082
3083 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
3084 auto *Zero = Constant::getNullValue(BO0->getType());
3085 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
3086 }
3087 }
3088
3089 return nullptr;
3090}
3091
Sanjay Pateldd46b522016-12-19 17:32:37 +00003092/// Fold icmp Pred min|max(X, Y), X.
3093static Instruction *foldICmpWithMinMax(ICmpInst &Cmp) {
Sanjay Pateld6406412016-12-15 19:13:37 +00003094 ICmpInst::Predicate Pred = Cmp.getPredicate();
3095 Value *Op0 = Cmp.getOperand(0);
3096 Value *X = Cmp.getOperand(1);
3097
Sanjay Pateldd46b522016-12-19 17:32:37 +00003098 // Canonicalize minimum or maximum operand to LHS of the icmp.
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003099 if (match(X, m_c_SMin(m_Specific(Op0), m_Value())) ||
Sanjay Pateldd46b522016-12-19 17:32:37 +00003100 match(X, m_c_SMax(m_Specific(Op0), m_Value())) ||
3101 match(X, m_c_UMin(m_Specific(Op0), m_Value())) ||
3102 match(X, m_c_UMax(m_Specific(Op0), m_Value()))) {
Sanjay Pateld6406412016-12-15 19:13:37 +00003103 std::swap(Op0, X);
3104 Pred = Cmp.getSwappedPredicate();
3105 }
3106
3107 Value *Y;
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003108 if (match(Op0, m_c_SMin(m_Specific(X), m_Value(Y)))) {
Sanjay Pateldd46b522016-12-19 17:32:37 +00003109 // smin(X, Y) == X --> X s<= Y
3110 // smin(X, Y) s>= X --> X s<= Y
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003111 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SGE)
3112 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3113
Sanjay Pateldd46b522016-12-19 17:32:37 +00003114 // smin(X, Y) != X --> X s> Y
3115 // smin(X, Y) s< X --> X s> Y
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003116 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SLT)
3117 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3118
3119 // These cases should be handled in InstSimplify:
Sanjay Pateldd46b522016-12-19 17:32:37 +00003120 // smin(X, Y) s<= X --> true
3121 // smin(X, Y) s> X --> false
Sanjay Pateld6406412016-12-15 19:13:37 +00003122 return nullptr;
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003123 }
Sanjay Pateldd46b522016-12-19 17:32:37 +00003124
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003125 if (match(Op0, m_c_SMax(m_Specific(X), m_Value(Y)))) {
Sanjay Pateldd46b522016-12-19 17:32:37 +00003126 // smax(X, Y) == X --> X s>= Y
3127 // smax(X, Y) s<= X --> X s>= Y
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003128 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SLE)
3129 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
Sanjay Pateld6406412016-12-15 19:13:37 +00003130
Sanjay Pateldd46b522016-12-19 17:32:37 +00003131 // smax(X, Y) != X --> X s< Y
3132 // smax(X, Y) s> X --> X s< Y
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003133 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SGT)
3134 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
Sanjay Pateld6406412016-12-15 19:13:37 +00003135
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003136 // These cases should be handled in InstSimplify:
Sanjay Pateldd46b522016-12-19 17:32:37 +00003137 // smax(X, Y) s>= X --> true
3138 // smax(X, Y) s< X --> false
3139 return nullptr;
3140 }
3141
3142 if (match(Op0, m_c_UMin(m_Specific(X), m_Value(Y)))) {
3143 // umin(X, Y) == X --> X u<= Y
3144 // umin(X, Y) u>= X --> X u<= Y
3145 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_UGE)
3146 return new ICmpInst(ICmpInst::ICMP_ULE, X, Y);
3147
3148 // umin(X, Y) != X --> X u> Y
3149 // umin(X, Y) u< X --> X u> Y
3150 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT)
3151 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
3152
3153 // These cases should be handled in InstSimplify:
3154 // umin(X, Y) u<= X --> true
3155 // umin(X, Y) u> X --> false
3156 return nullptr;
3157 }
3158
3159 if (match(Op0, m_c_UMax(m_Specific(X), m_Value(Y)))) {
3160 // umax(X, Y) == X --> X u>= Y
3161 // umax(X, Y) u<= X --> X u>= Y
3162 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_ULE)
3163 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y);
3164
3165 // umax(X, Y) != X --> X u< Y
3166 // umax(X, Y) u> X --> X u< Y
3167 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_UGT)
3168 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
3169
3170 // These cases should be handled in InstSimplify:
3171 // umax(X, Y) u>= X --> true
3172 // umax(X, Y) u< X --> false
Sanjay Patel8296c6c2016-12-19 16:28:53 +00003173 return nullptr;
3174 }
Sanjay Pateld6406412016-12-15 19:13:37 +00003175
Sanjay Pateld6406412016-12-15 19:13:37 +00003176 return nullptr;
3177}
3178
Sanjay Patel10494b22016-09-16 16:10:22 +00003179Instruction *InstCombiner::foldICmpEquality(ICmpInst &I) {
3180 if (!I.isEquality())
3181 return nullptr;
3182
3183 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3184 Value *A, *B, *C, *D;
3185 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3186 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
3187 Value *OtherVal = A == Op1 ? B : A;
3188 return new ICmpInst(I.getPredicate(), OtherVal,
3189 Constant::getNullValue(A->getType()));
3190 }
3191
3192 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
3193 // A^c1 == C^c2 --> A == C^(c1^c2)
3194 ConstantInt *C1, *C2;
3195 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
3196 Op1->hasOneUse()) {
3197 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
3198 Value *Xor = Builder->CreateXor(C, NC);
3199 return new ICmpInst(I.getPredicate(), A, Xor);
3200 }
3201
3202 // A^B == A^D -> B == D
3203 if (A == C)
3204 return new ICmpInst(I.getPredicate(), B, D);
3205 if (A == D)
3206 return new ICmpInst(I.getPredicate(), B, C);
3207 if (B == C)
3208 return new ICmpInst(I.getPredicate(), A, D);
3209 if (B == D)
3210 return new ICmpInst(I.getPredicate(), A, C);
3211 }
3212 }
3213
3214 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
3215 // A == (A^B) -> B == 0
3216 Value *OtherVal = A == Op0 ? B : A;
3217 return new ICmpInst(I.getPredicate(), OtherVal,
3218 Constant::getNullValue(A->getType()));
3219 }
3220
3221 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
3222 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
3223 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
3224 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
3225
3226 if (A == C) {
3227 X = B;
3228 Y = D;
3229 Z = A;
3230 } else if (A == D) {
3231 X = B;
3232 Y = C;
3233 Z = A;
3234 } else if (B == C) {
3235 X = A;
3236 Y = D;
3237 Z = B;
3238 } else if (B == D) {
3239 X = A;
3240 Y = C;
3241 Z = B;
3242 }
3243
3244 if (X) { // Build (X^Y) & Z
3245 Op1 = Builder->CreateXor(X, Y);
3246 Op1 = Builder->CreateAnd(Op1, Z);
3247 I.setOperand(0, Op1);
3248 I.setOperand(1, Constant::getNullValue(Op1->getType()));
3249 return &I;
3250 }
3251 }
3252
3253 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
3254 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
3255 ConstantInt *Cst1;
3256 if ((Op0->hasOneUse() && match(Op0, m_ZExt(m_Value(A))) &&
3257 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
3258 (Op1->hasOneUse() && match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
3259 match(Op1, m_ZExt(m_Value(A))))) {
3260 APInt Pow2 = Cst1->getValue() + 1;
3261 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
3262 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
3263 return new ICmpInst(I.getPredicate(), A,
3264 Builder->CreateTrunc(B, A->getType()));
3265 }
3266
3267 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
3268 // For lshr and ashr pairs.
3269 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3270 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
3271 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3272 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
3273 unsigned TypeBits = Cst1->getBitWidth();
3274 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3275 if (ShAmt < TypeBits && ShAmt != 0) {
3276 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
3277 ? ICmpInst::ICMP_UGE
3278 : ICmpInst::ICMP_ULT;
3279 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
3280 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
3281 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
3282 }
3283 }
3284
3285 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
3286 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
3287 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
3288 unsigned TypeBits = Cst1->getBitWidth();
3289 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3290 if (ShAmt < TypeBits && ShAmt != 0) {
3291 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
3292 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
3293 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
3294 I.getName() + ".mask");
3295 return new ICmpInst(I.getPredicate(), And,
3296 Constant::getNullValue(Cst1->getType()));
3297 }
3298 }
3299
3300 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
3301 // "icmp (and X, mask), cst"
3302 uint64_t ShAmt = 0;
3303 if (Op0->hasOneUse() &&
3304 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
3305 match(Op1, m_ConstantInt(Cst1)) &&
3306 // Only do this when A has multiple uses. This is most important to do
3307 // when it exposes other optimizations.
3308 !A->hasOneUse()) {
3309 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
3310
3311 if (ShAmt < ASize) {
3312 APInt MaskV =
3313 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
3314 MaskV <<= ShAmt;
3315
3316 APInt CmpV = Cst1->getValue().zext(ASize);
3317 CmpV <<= ShAmt;
3318
3319 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
3320 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
3321 }
3322 }
3323
3324 return nullptr;
3325}
3326
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003327/// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so
3328/// far.
Sanjay Patel43395062016-07-21 18:07:40 +00003329Instruction *InstCombiner::foldICmpWithCastAndCast(ICmpInst &ICmp) {
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003330 const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00003331 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003332 Type *SrcTy = LHSCIOp->getType();
3333 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00003334 Value *RHSCIOp;
3335
Jim Grosbach129c52a2011-09-30 18:09:53 +00003336 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00003337 // integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003338 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
3339 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00003340 Value *RHSOp = nullptr;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003341 if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
Michael Liaod266b922015-02-13 04:51:26 +00003342 Value *RHSCIOp = RHSC->getOperand(0);
3343 if (RHSCIOp->getType()->getPointerAddressSpace() ==
3344 LHSCIOp->getType()->getPointerAddressSpace()) {
3345 RHSOp = RHSC->getOperand(0);
3346 // If the pointer types don't match, insert a bitcast.
3347 if (LHSCIOp->getType() != RHSOp->getType())
3348 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
3349 }
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003350 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003351 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003352 }
Chris Lattner2188e402010-01-04 07:37:31 +00003353
3354 if (RHSOp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003355 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner2188e402010-01-04 07:37:31 +00003356 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003357
Chris Lattner2188e402010-01-04 07:37:31 +00003358 // The code below only handles extension cast instructions, so far.
3359 // Enforce this.
3360 if (LHSCI->getOpcode() != Instruction::ZExt &&
3361 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00003362 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003363
3364 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003365 bool isSignedCmp = ICmp.isSigned();
Chris Lattner2188e402010-01-04 07:37:31 +00003366
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003367 if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003368 // Not an extension from the same type?
3369 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003370 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00003371 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003372
Chris Lattner2188e402010-01-04 07:37:31 +00003373 // If the signedness of the two casts doesn't agree (i.e. one is a sext
3374 // and the other is a zext), then we can't handle this.
3375 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00003376 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003377
3378 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003379 if (ICmp.isEquality())
3380 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00003381
3382 // A signed comparison of sign extended values simplifies into a
3383 // signed comparison.
3384 if (isSignedCmp && isSignedExt)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003385 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00003386
3387 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003388 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00003389 }
3390
Sanjay Patel4c204232016-06-04 20:39:22 +00003391 // If we aren't dealing with a constant on the RHS, exit early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003392 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
3393 if (!C)
Craig Topperf40110f2014-04-25 05:29:35 +00003394 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003395
3396 // Compute the constant that would happen if we truncated to SrcTy then
Sanjay Patelc774f8c2016-06-04 21:20:44 +00003397 // re-extended to DestTy.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003398 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
Sanjay Patelc774f8c2016-06-04 21:20:44 +00003399 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattner2188e402010-01-04 07:37:31 +00003400
3401 // If the re-extended constant didn't change...
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003402 if (Res2 == C) {
Chris Lattner2188e402010-01-04 07:37:31 +00003403 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003404 if (ICmp.isEquality())
3405 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00003406
3407 // A signed comparison of sign extended values simplifies into a
3408 // signed comparison.
3409 if (isSignedExt && isSignedCmp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003410 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00003411
3412 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003413 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00003414 }
3415
Sanjay Patel6a333c32016-06-06 16:56:57 +00003416 // The re-extended constant changed, partly changed (in the case of a vector),
3417 // or could not be determined to be equal (in the case of a constant
3418 // expression), so the constant cannot be represented in the shorter type.
3419 // Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003420 // All the cases that fold to true or false will have already been handled
3421 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00003422
Sanjay Patel6a333c32016-06-06 16:56:57 +00003423 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
Craig Topperf40110f2014-04-25 05:29:35 +00003424 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003425
3426 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
3427 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003428
3429 // We're performing an unsigned comp with a sign extended value.
3430 // This is true if the input is >= 0. [aka >s -1]
3431 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003432 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00003433
3434 // Finally, return the value computed.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003435 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
3436 return replaceInstUsesWith(ICmp, Result);
Chris Lattner2188e402010-01-04 07:37:31 +00003437
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003438 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00003439 return BinaryOperator::CreateNot(Result);
3440}
3441
Sanjoy Dasb0984472015-04-08 04:27:22 +00003442bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
3443 Value *RHS, Instruction &OrigI,
3444 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00003445 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
3446 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003447
3448 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
3449 Result = OpResult;
3450 Overflow = OverflowVal;
3451 if (ReuseName)
3452 Result->takeName(&OrigI);
3453 return true;
3454 };
3455
Sanjoy Das6f5dca72015-08-28 19:09:31 +00003456 // If the overflow check was an add followed by a compare, the insertion point
3457 // may be pointing to the compare. We want to insert the new instructions
3458 // before the add in case there are uses of the add between the add and the
3459 // compare.
3460 Builder->SetInsertPoint(&OrigI);
3461
Sanjoy Dasb0984472015-04-08 04:27:22 +00003462 switch (OCF) {
3463 case OCF_INVALID:
3464 llvm_unreachable("bad overflow check kind!");
3465
3466 case OCF_UNSIGNED_ADD: {
3467 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
3468 if (OR == OverflowResult::NeverOverflows)
3469 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
3470 true);
3471
3472 if (OR == OverflowResult::AlwaysOverflows)
3473 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003474
3475 // Fall through uadd into sadd
3476 LLVM_FALLTHROUGH;
Sanjoy Dasb0984472015-04-08 04:27:22 +00003477 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00003478 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00003479 // X + 0 -> {X, false}
3480 if (match(RHS, m_Zero()))
3481 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003482
3483 // We can strength reduce this signed add into a regular add if we can prove
3484 // that it will never overflow.
3485 if (OCF == OCF_SIGNED_ADD)
3486 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
3487 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
3488 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00003489 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00003490 }
3491
3492 case OCF_UNSIGNED_SUB:
3493 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00003494 // X - 0 -> {X, false}
3495 if (match(RHS, m_Zero()))
3496 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003497
3498 if (OCF == OCF_SIGNED_SUB) {
3499 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
3500 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
3501 true);
3502 } else {
3503 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
3504 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
3505 true);
3506 }
3507 break;
3508 }
3509
3510 case OCF_UNSIGNED_MUL: {
3511 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
3512 if (OR == OverflowResult::NeverOverflows)
3513 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
3514 true);
3515 if (OR == OverflowResult::AlwaysOverflows)
3516 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003517 LLVM_FALLTHROUGH;
3518 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00003519 case OCF_SIGNED_MUL:
3520 // X * undef -> undef
3521 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00003522 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003523
David Majnemer27e89ba2015-05-21 23:04:21 +00003524 // X * 0 -> {0, false}
3525 if (match(RHS, m_Zero()))
3526 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003527
David Majnemer27e89ba2015-05-21 23:04:21 +00003528 // X * 1 -> {X, false}
3529 if (match(RHS, m_One()))
3530 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003531
3532 if (OCF == OCF_SIGNED_MUL)
3533 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
3534 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
3535 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00003536 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00003537 }
3538
3539 return false;
3540}
3541
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003542/// \brief Recognize and process idiom involving test for multiplication
3543/// overflow.
3544///
3545/// The caller has matched a pattern of the form:
3546/// I = cmp u (mul(zext A, zext B), V
3547/// The function checks if this is a test for overflow and if so replaces
3548/// multiplication with call to 'mul.with.overflow' intrinsic.
3549///
3550/// \param I Compare instruction.
3551/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
3552/// the compare instruction. Must be of integer type.
3553/// \param OtherVal The other argument of compare instruction.
3554/// \returns Instruction which must replace the compare instruction, NULL if no
3555/// replacement required.
Sanjay Pateld93c4c02016-09-15 18:22:25 +00003556static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003557 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00003558 // Don't bother doing this transformation for pointers, don't do it for
3559 // vectors.
3560 if (!isa<IntegerType>(MulVal->getType()))
3561 return nullptr;
3562
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003563 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
3564 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00003565 auto *MulInstr = dyn_cast<Instruction>(MulVal);
3566 if (!MulInstr)
3567 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003568 assert(MulInstr->getOpcode() == Instruction::Mul);
3569
David Majnemer634ca232014-11-01 23:46:05 +00003570 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
3571 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003572 assert(LHS->getOpcode() == Instruction::ZExt);
3573 assert(RHS->getOpcode() == Instruction::ZExt);
3574 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
3575
3576 // Calculate type and width of the result produced by mul.with.overflow.
3577 Type *TyA = A->getType(), *TyB = B->getType();
3578 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
3579 WidthB = TyB->getPrimitiveSizeInBits();
3580 unsigned MulWidth;
3581 Type *MulType;
3582 if (WidthB > WidthA) {
3583 MulWidth = WidthB;
3584 MulType = TyB;
3585 } else {
3586 MulWidth = WidthA;
3587 MulType = TyA;
3588 }
3589
3590 // In order to replace the original mul with a narrower mul.with.overflow,
3591 // all uses must ignore upper bits of the product. The number of used low
3592 // bits must be not greater than the width of mul.with.overflow.
3593 if (MulVal->hasNUsesOrMore(2))
3594 for (User *U : MulVal->users()) {
3595 if (U == &I)
3596 continue;
3597 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
3598 // Check if truncation ignores bits above MulWidth.
3599 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
3600 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00003601 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003602 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
3603 // Check if AND ignores bits above MulWidth.
3604 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00003605 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003606 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3607 const APInt &CVal = CI->getValue();
3608 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00003609 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003610 }
3611 } else {
3612 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00003613 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003614 }
3615 }
3616
3617 // Recognize patterns
3618 switch (I.getPredicate()) {
3619 case ICmpInst::ICMP_EQ:
3620 case ICmpInst::ICMP_NE:
3621 // Recognize pattern:
3622 // mulval = mul(zext A, zext B)
3623 // cmp eq/neq mulval, zext trunc mulval
3624 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
3625 if (Zext->hasOneUse()) {
3626 Value *ZextArg = Zext->getOperand(0);
3627 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
3628 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
3629 break; //Recognized
3630 }
3631
3632 // Recognize pattern:
3633 // mulval = mul(zext A, zext B)
3634 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
3635 ConstantInt *CI;
3636 Value *ValToMask;
3637 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
3638 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00003639 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003640 const APInt &CVal = CI->getValue() + 1;
3641 if (CVal.isPowerOf2()) {
3642 unsigned MaskWidth = CVal.logBase2();
3643 if (MaskWidth == MulWidth)
3644 break; // Recognized
3645 }
3646 }
Craig Topperf40110f2014-04-25 05:29:35 +00003647 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003648
3649 case ICmpInst::ICMP_UGT:
3650 // Recognize pattern:
3651 // mulval = mul(zext A, zext B)
3652 // cmp ugt mulval, max
3653 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3654 APInt MaxVal = APInt::getMaxValue(MulWidth);
3655 MaxVal = MaxVal.zext(CI->getBitWidth());
3656 if (MaxVal.eq(CI->getValue()))
3657 break; // Recognized
3658 }
Craig Topperf40110f2014-04-25 05:29:35 +00003659 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003660
3661 case ICmpInst::ICMP_UGE:
3662 // Recognize pattern:
3663 // mulval = mul(zext A, zext B)
3664 // cmp uge mulval, max+1
3665 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3666 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
3667 if (MaxVal.eq(CI->getValue()))
3668 break; // Recognized
3669 }
Craig Topperf40110f2014-04-25 05:29:35 +00003670 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003671
3672 case ICmpInst::ICMP_ULE:
3673 // Recognize pattern:
3674 // mulval = mul(zext A, zext B)
3675 // cmp ule mulval, max
3676 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3677 APInt MaxVal = APInt::getMaxValue(MulWidth);
3678 MaxVal = MaxVal.zext(CI->getBitWidth());
3679 if (MaxVal.eq(CI->getValue()))
3680 break; // Recognized
3681 }
Craig Topperf40110f2014-04-25 05:29:35 +00003682 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003683
3684 case ICmpInst::ICMP_ULT:
3685 // Recognize pattern:
3686 // mulval = mul(zext A, zext B)
3687 // cmp ule mulval, max + 1
3688 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00003689 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003690 if (MaxVal.eq(CI->getValue()))
3691 break; // Recognized
3692 }
Craig Topperf40110f2014-04-25 05:29:35 +00003693 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003694
3695 default:
Craig Topperf40110f2014-04-25 05:29:35 +00003696 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003697 }
3698
3699 InstCombiner::BuilderTy *Builder = IC.Builder;
3700 Builder->SetInsertPoint(MulInstr);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003701
3702 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
3703 Value *MulA = A, *MulB = B;
3704 if (WidthA < MulWidth)
3705 MulA = Builder->CreateZExt(A, MulType);
3706 if (WidthB < MulWidth)
3707 MulB = Builder->CreateZExt(B, MulType);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00003708 Value *F = Intrinsic::getDeclaration(I.getModule(),
3709 Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00003710 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003711 IC.Worklist.Add(MulInstr);
3712
3713 // If there are uses of mul result other than the comparison, we know that
3714 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00003715 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003716 if (MulVal->hasNUsesOrMore(2)) {
3717 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
3718 for (User *U : MulVal->users()) {
3719 if (U == &I || U == OtherVal)
3720 continue;
3721 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
3722 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
Sanjay Patel4b198802016-02-01 22:23:39 +00003723 IC.replaceInstUsesWith(*TI, Mul);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003724 else
3725 TI->setOperand(0, Mul);
3726 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
3727 assert(BO->getOpcode() == Instruction::And);
3728 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
3729 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
3730 APInt ShortMask = CI->getValue().trunc(MulWidth);
3731 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
3732 Instruction *Zext =
3733 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
3734 IC.Worklist.Add(Zext);
Sanjay Patel4b198802016-02-01 22:23:39 +00003735 IC.replaceInstUsesWith(*BO, Zext);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003736 } else {
3737 llvm_unreachable("Unexpected Binary operation");
3738 }
3739 IC.Worklist.Add(cast<Instruction>(U));
3740 }
3741 }
3742 if (isa<Instruction>(OtherVal))
3743 IC.Worklist.Add(cast<Instruction>(OtherVal));
3744
3745 // The original icmp gets replaced with the overflow value, maybe inverted
3746 // depending on predicate.
3747 bool Inverse = false;
3748 switch (I.getPredicate()) {
3749 case ICmpInst::ICMP_NE:
3750 break;
3751 case ICmpInst::ICMP_EQ:
3752 Inverse = true;
3753 break;
3754 case ICmpInst::ICMP_UGT:
3755 case ICmpInst::ICMP_UGE:
3756 if (I.getOperand(0) == MulVal)
3757 break;
3758 Inverse = true;
3759 break;
3760 case ICmpInst::ICMP_ULT:
3761 case ICmpInst::ICMP_ULE:
3762 if (I.getOperand(1) == MulVal)
3763 break;
3764 Inverse = true;
3765 break;
3766 default:
3767 llvm_unreachable("Unexpected predicate");
3768 }
3769 if (Inverse) {
3770 Value *Res = Builder->CreateExtractValue(Call, 1);
3771 return BinaryOperator::CreateNot(Res);
3772 }
3773
3774 return ExtractValueInst::Create(Call, 1);
3775}
3776
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003777/// When performing a comparison against a constant, it is possible that not all
3778/// the bits in the LHS are demanded. This helper method computes the mask that
3779/// IS demanded.
Sanjay Pateld93c4c02016-09-15 18:22:25 +00003780static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth,
3781 bool isSignCheck) {
Owen Andersond490c2d2011-01-11 00:36:45 +00003782 if (isSignCheck)
3783 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003784
Owen Andersond490c2d2011-01-11 00:36:45 +00003785 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3786 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00003787 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003788
Owen Andersond490c2d2011-01-11 00:36:45 +00003789 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003790 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00003791 // correspond to the trailing ones of the comparand. The value of these
3792 // bits doesn't impact the outcome of the comparison, because any value
3793 // greater than the RHS must differ in a bit higher than these due to carry.
3794 case ICmpInst::ICMP_UGT: {
3795 unsigned trailingOnes = RHS.countTrailingOnes();
3796 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
3797 return ~lowBitsSet;
3798 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003799
Owen Andersond490c2d2011-01-11 00:36:45 +00003800 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
3801 // Any value less than the RHS must differ in a higher bit because of carries.
3802 case ICmpInst::ICMP_ULT: {
3803 unsigned trailingZeros = RHS.countTrailingZeros();
3804 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
3805 return ~lowBitsSet;
3806 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003807
Owen Andersond490c2d2011-01-11 00:36:45 +00003808 default:
3809 return APInt::getAllOnesValue(BitWidth);
3810 }
Owen Andersond490c2d2011-01-11 00:36:45 +00003811}
Chris Lattner2188e402010-01-04 07:37:31 +00003812
Quentin Colombet5ab55552013-09-09 20:56:48 +00003813/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
3814/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00003815/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00003816/// as subtract operands and their positions in those instructions.
3817/// The rational is that several architectures use the same instruction for
3818/// both subtract and cmp, thus it is better if the order of those operands
3819/// match.
3820/// \return true if Op0 and Op1 should be swapped.
3821static bool swapMayExposeCSEOpportunities(const Value * Op0,
3822 const Value * Op1) {
3823 // Filter out pointer value as those cannot appears directly in subtract.
3824 // FIXME: we may want to go through inttoptrs or bitcasts.
3825 if (Op0->getType()->isPointerTy())
3826 return false;
3827 // Count every uses of both Op0 and Op1 in a subtract.
3828 // Each time Op0 is the first operand, count -1: swapping is bad, the
3829 // subtract has already the same layout as the compare.
3830 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00003831 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003832 // At the end, if the benefit is greater than 0, Op0 should come second to
3833 // expose more CSE opportunities.
3834 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003835 for (const User *U : Op0->users()) {
3836 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003837 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
3838 continue;
3839 // If Op0 is the first argument, this is not beneficial to swap the
3840 // arguments.
3841 int LocalSwapBenefits = -1;
3842 unsigned Op1Idx = 1;
3843 if (BinOp->getOperand(Op1Idx) == Op0) {
3844 Op1Idx = 0;
3845 LocalSwapBenefits = 1;
3846 }
3847 if (BinOp->getOperand(Op1Idx) != Op1)
3848 continue;
3849 GlobalSwapBenefits += LocalSwapBenefits;
3850 }
3851 return GlobalSwapBenefits > 0;
3852}
3853
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003854/// \brief Check that one use is in the same block as the definition and all
Sanjay Patel53523312016-09-12 14:25:46 +00003855/// other uses are in blocks dominated by a given block.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003856///
3857/// \param DI Definition
3858/// \param UI Use
3859/// \param DB Block that must dominate all uses of \p DI outside
3860/// the parent block
3861/// \return true when \p UI is the only use of \p DI in the parent block
3862/// and all other uses of \p DI are in blocks dominated by \p DB.
3863///
3864bool InstCombiner::dominatesAllUses(const Instruction *DI,
3865 const Instruction *UI,
3866 const BasicBlock *DB) const {
3867 assert(DI && UI && "Instruction not defined\n");
Sanjay Patel53523312016-09-12 14:25:46 +00003868 // Ignore incomplete definitions.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003869 if (!DI->getParent())
3870 return false;
Sanjay Patel53523312016-09-12 14:25:46 +00003871 // DI and UI must be in the same block.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003872 if (DI->getParent() != UI->getParent())
3873 return false;
Sanjay Patel53523312016-09-12 14:25:46 +00003874 // Protect from self-referencing blocks.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003875 if (DI->getParent() == DB)
3876 return false;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003877 for (const User *U : DI->users()) {
3878 auto *Usr = cast<Instruction>(U);
Justin Bogner99798402016-08-05 01:06:44 +00003879 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003880 return false;
3881 }
3882 return true;
3883}
3884
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003885/// Return true when the instruction sequence within a block is select-cmp-br.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003886static bool isChainSelectCmpBranch(const SelectInst *SI) {
3887 const BasicBlock *BB = SI->getParent();
3888 if (!BB)
3889 return false;
3890 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
3891 if (!BI || BI->getNumSuccessors() != 2)
3892 return false;
3893 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
3894 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
3895 return false;
3896 return true;
3897}
3898
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003899/// \brief True when a select result is replaced by one of its operands
3900/// in select-icmp sequence. This will eventually result in the elimination
3901/// of the select.
3902///
3903/// \param SI Select instruction
3904/// \param Icmp Compare instruction
3905/// \param SIOpd Operand that replaces the select
3906///
3907/// Notes:
3908/// - The replacement is global and requires dominator information
3909/// - The caller is responsible for the actual replacement
3910///
3911/// Example:
3912///
3913/// entry:
3914/// %4 = select i1 %3, %C* %0, %C* null
3915/// %5 = icmp eq %C* %4, null
3916/// br i1 %5, label %9, label %7
3917/// ...
3918/// ; <label>:7 ; preds = %entry
3919/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
3920/// ...
3921///
3922/// can be transformed to
3923///
3924/// %5 = icmp eq %C* %0, null
3925/// %6 = select i1 %3, i1 %5, i1 true
3926/// br i1 %6, label %9, label %7
3927/// ...
3928/// ; <label>:7 ; preds = %entry
3929/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
3930///
3931/// Similar when the first operand of the select is a constant or/and
3932/// the compare is for not equal rather than equal.
3933///
3934/// NOTE: The function is only called when the select and compare constants
3935/// are equal, the optimization can work only for EQ predicates. This is not a
3936/// major restriction since a NE compare should be 'normalized' to an equal
3937/// compare, which usually happens in the combiner and test case
Sanjay Patel53523312016-09-12 14:25:46 +00003938/// select-cmp-br.ll checks for it.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003939bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
3940 const ICmpInst *Icmp,
3941 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00003942 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003943 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
3944 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
3945 // The check for the unique predecessor is not the best that can be
Sanjay Patel53523312016-09-12 14:25:46 +00003946 // done. But it protects efficiently against cases like when SI's
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003947 // home block has two successors, Succ and Succ1, and Succ1 predecessor
3948 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
3949 // replaced can be reached on either path. So the uniqueness check
3950 // guarantees that the path all uses of SI (outside SI's parent) are on
3951 // is disjoint from all other paths out of SI. But that information
3952 // is more expensive to compute, and the trade-off here is in favor
3953 // of compile-time.
3954 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
3955 NumSel++;
3956 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
3957 return true;
3958 }
3959 }
3960 return false;
3961}
3962
Sanjay Patel3151dec2016-09-12 15:24:31 +00003963/// Try to fold the comparison based on range information we can get by checking
3964/// whether bits are known to be zero or one in the inputs.
3965Instruction *InstCombiner::foldICmpUsingKnownBits(ICmpInst &I) {
3966 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3967 Type *Ty = Op0->getType();
Sanjay Patel0531f0a2016-09-12 15:52:28 +00003968 ICmpInst::Predicate Pred = I.getPredicate();
Sanjay Patel3151dec2016-09-12 15:24:31 +00003969
3970 // Get scalar or pointer size.
3971 unsigned BitWidth = Ty->isIntOrIntVectorTy()
3972 ? Ty->getScalarSizeInBits()
3973 : DL.getTypeSizeInBits(Ty->getScalarType());
3974
3975 if (!BitWidth)
3976 return nullptr;
3977
3978 // If this is a normal comparison, it demands all bits. If it is a sign bit
3979 // comparison, it only demands the sign bit.
3980 bool IsSignBit = false;
Sanjay Patelf5887f12016-09-12 16:25:41 +00003981 const APInt *CmpC;
3982 if (match(Op1, m_APInt(CmpC))) {
Sanjay Patel3151dec2016-09-12 15:24:31 +00003983 bool UnusedBit;
Sanjay Patelf5887f12016-09-12 16:25:41 +00003984 IsSignBit = isSignBitCheck(Pred, *CmpC, UnusedBit);
Sanjay Patel3151dec2016-09-12 15:24:31 +00003985 }
3986
3987 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
3988 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
3989
3990 if (SimplifyDemandedBits(I.getOperandUse(0),
Sanjay Pateld93c4c02016-09-15 18:22:25 +00003991 getDemandedBitsLHSMask(I, BitWidth, IsSignBit),
Sanjay Patel3151dec2016-09-12 15:24:31 +00003992 Op0KnownZero, Op0KnownOne, 0))
3993 return &I;
3994
3995 if (SimplifyDemandedBits(I.getOperandUse(1), APInt::getAllOnesValue(BitWidth),
3996 Op1KnownZero, Op1KnownOne, 0))
3997 return &I;
3998
3999 // Given the known and unknown bits, compute a range that the LHS could be
4000 // in. Compute the Min, Max and RHS values based on the known bits. For the
4001 // EQ and NE we use unsigned values.
4002 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
4003 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
4004 if (I.isSigned()) {
Sanjay Pateld93c4c02016-09-15 18:22:25 +00004005 computeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, Op0Min,
Sanjay Patel3151dec2016-09-12 15:24:31 +00004006 Op0Max);
Sanjay Pateld93c4c02016-09-15 18:22:25 +00004007 computeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, Op1Min,
Sanjay Patel3151dec2016-09-12 15:24:31 +00004008 Op1Max);
4009 } else {
Sanjay Pateld93c4c02016-09-15 18:22:25 +00004010 computeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, Op0Min,
Sanjay Patel3151dec2016-09-12 15:24:31 +00004011 Op0Max);
Sanjay Pateld93c4c02016-09-15 18:22:25 +00004012 computeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, Op1Min,
Sanjay Patel3151dec2016-09-12 15:24:31 +00004013 Op1Max);
4014 }
4015
4016 // If Min and Max are known to be the same, then SimplifyDemandedBits
Sanjay Patel0531f0a2016-09-12 15:52:28 +00004017 // figured out that the LHS is a constant. Constant fold this now, so that
4018 // code below can assume that Min != Max.
Sanjay Patel3151dec2016-09-12 15:24:31 +00004019 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Sanjay Patel0531f0a2016-09-12 15:52:28 +00004020 return new ICmpInst(Pred, ConstantInt::get(Op0->getType(), Op0Min), Op1);
Sanjay Patel3151dec2016-09-12 15:24:31 +00004021 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Sanjay Patel0531f0a2016-09-12 15:52:28 +00004022 return new ICmpInst(Pred, Op0, ConstantInt::get(Op1->getType(), Op1Min));
Sanjay Patel3151dec2016-09-12 15:24:31 +00004023
4024 // Based on the range information we know about the LHS, see if we can
4025 // simplify this comparison. For example, (x&4) < 8 is always true.
Sanjay Patel0531f0a2016-09-12 15:52:28 +00004026 switch (Pred) {
Sanjay Patel3151dec2016-09-12 15:24:31 +00004027 default:
4028 llvm_unreachable("Unknown icmp opcode!");
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004029 case ICmpInst::ICMP_EQ:
Sanjay Patel3151dec2016-09-12 15:24:31 +00004030 case ICmpInst::ICMP_NE: {
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004031 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) {
4032 return Pred == CmpInst::ICMP_EQ
4033 ? replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()))
4034 : replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4035 }
Sanjay Patel3151dec2016-09-12 15:24:31 +00004036
Sanjay Patel0531f0a2016-09-12 15:52:28 +00004037 // If all bits are known zero except for one, then we know at most one bit
4038 // is set. If the comparison is against zero, then this is a check to see if
4039 // *that* bit is set.
Sanjay Patel3151dec2016-09-12 15:24:31 +00004040 APInt Op0KnownZeroInverted = ~Op0KnownZero;
4041 if (~Op1KnownZero == 0) {
4042 // If the LHS is an AND with the same constant, look through it.
4043 Value *LHS = nullptr;
Sanjay Patel7577a3d2016-09-15 14:15:47 +00004044 const APInt *LHSC;
4045 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
4046 *LHSC != Op0KnownZeroInverted)
Sanjay Patel3151dec2016-09-12 15:24:31 +00004047 LHS = Op0;
4048
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004049 Value *X;
Sanjay Patel3151dec2016-09-12 15:24:31 +00004050 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
4051 APInt ValToCheck = Op0KnownZeroInverted;
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004052 Type *XTy = X->getType();
Sanjay Patel3151dec2016-09-12 15:24:31 +00004053 if (ValToCheck.isPowerOf2()) {
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004054 // ((1 << X) & 8) == 0 -> X != 3
4055 // ((1 << X) & 8) != 0 -> X == 3
4056 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros());
4057 auto NewPred = ICmpInst::getInversePredicate(Pred);
4058 return new ICmpInst(NewPred, X, CmpC);
Sanjay Patel3151dec2016-09-12 15:24:31 +00004059 } else if ((++ValToCheck).isPowerOf2()) {
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004060 // ((1 << X) & 7) == 0 -> X >= 3
4061 // ((1 << X) & 7) != 0 -> X < 3
4062 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros());
4063 auto NewPred =
4064 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
4065 return new ICmpInst(NewPred, X, CmpC);
Sanjay Patel3151dec2016-09-12 15:24:31 +00004066 }
4067 }
4068
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004069 // 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 +00004070 const APInt *CI;
4071 if (Op0KnownZeroInverted == 1 &&
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00004072 match(LHS, m_LShr(m_Power2(CI), m_Value(X)))) {
4073 // ((8 >>u X) & 1) == 0 -> X != 3
4074 // ((8 >>u X) & 1) != 0 -> X == 3
4075 unsigned CmpVal = CI->countTrailingZeros();
4076 auto NewPred = ICmpInst::getInversePredicate(Pred);
4077 return new ICmpInst(NewPred, X, ConstantInt::get(X->getType(), CmpVal));
4078 }
Sanjay Patel3151dec2016-09-12 15:24:31 +00004079 }
4080 break;
4081 }
4082 case ICmpInst::ICMP_ULT: {
4083 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
4084 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4085 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
4086 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4087 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
4088 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4089
4090 const APInt *CmpC;
4091 if (match(Op1, m_APInt(CmpC))) {
4092 // A <u C -> A == C-1 if min(A)+1 == C
4093 if (Op1Max == Op0Min + 1) {
4094 Constant *CMinus1 = ConstantInt::get(Op0->getType(), *CmpC - 1);
4095 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, CMinus1);
4096 }
Sanjay Patel3151dec2016-09-12 15:24:31 +00004097 }
4098 break;
4099 }
4100 case ICmpInst::ICMP_UGT: {
4101 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
4102 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4103
4104 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
4105 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4106
4107 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
4108 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4109
4110 const APInt *CmpC;
4111 if (match(Op1, m_APInt(CmpC))) {
4112 // A >u C -> A == C+1 if max(a)-1 == C
4113 if (*CmpC == Op0Max - 1)
4114 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4115 ConstantInt::get(Op1->getType(), *CmpC + 1));
Sanjay Patel3151dec2016-09-12 15:24:31 +00004116 }
4117 break;
4118 }
4119 case ICmpInst::ICMP_SLT:
4120 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
4121 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4122 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
4123 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4124 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
4125 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4126 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4127 if (Op1Max == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
4128 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4129 Builder->getInt(CI->getValue() - 1));
4130 }
4131 break;
4132 case ICmpInst::ICMP_SGT:
4133 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
4134 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4135 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
4136 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4137
4138 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
4139 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4140 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4141 if (Op1Min == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
4142 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4143 Builder->getInt(CI->getValue() + 1));
4144 }
4145 break;
4146 case ICmpInst::ICMP_SGE:
4147 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
4148 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
4149 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4150 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
4151 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4152 break;
4153 case ICmpInst::ICMP_SLE:
4154 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
4155 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
4156 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4157 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
4158 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4159 break;
4160 case ICmpInst::ICMP_UGE:
4161 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
4162 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
4163 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4164 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
4165 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4166 break;
4167 case ICmpInst::ICMP_ULE:
4168 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
4169 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
4170 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4171 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
4172 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4173 break;
4174 }
4175
4176 // Turn a signed comparison into an unsigned one if both operands are known to
4177 // have the same sign.
4178 if (I.isSigned() &&
4179 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
4180 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
4181 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
4182
4183 return nullptr;
4184}
4185
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004186/// If we have an icmp le or icmp ge instruction with a constant operand, turn
4187/// it into the appropriate icmp lt or icmp gt instruction. This transform
4188/// allows them to be folded in visitICmpInst.
Sanjay Patele9b2c322016-05-17 00:57:57 +00004189static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
4190 ICmpInst::Predicate Pred = I.getPredicate();
4191 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE &&
4192 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE)
4193 return nullptr;
4194
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004195 Value *Op0 = I.getOperand(0);
4196 Value *Op1 = I.getOperand(1);
Sanjay Patele9b2c322016-05-17 00:57:57 +00004197 auto *Op1C = dyn_cast<Constant>(Op1);
4198 if (!Op1C)
4199 return nullptr;
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004200
Sanjay Patele9b2c322016-05-17 00:57:57 +00004201 // Check if the constant operand can be safely incremented/decremented without
4202 // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled
4203 // the edge cases for us, so we just assert on them. For vectors, we must
4204 // handle the edge cases.
4205 Type *Op1Type = Op1->getType();
4206 bool IsSigned = I.isSigned();
4207 bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE);
Sanjay Patel18254932016-05-17 01:12:31 +00004208 auto *CI = dyn_cast<ConstantInt>(Op1C);
4209 if (CI) {
Sanjay Patele9b2c322016-05-17 00:57:57 +00004210 // A <= MAX -> TRUE ; A >= MIN -> TRUE
4211 assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned));
4212 } else if (Op1Type->isVectorTy()) {
Sanjay Patelb79ab272016-05-13 15:10:46 +00004213 // TODO? If the edge cases for vectors were guaranteed to be handled as they
Sanjay Patele9b2c322016-05-17 00:57:57 +00004214 // are for scalar, we could remove the min/max checks. However, to do that,
4215 // we would have to use insertelement/shufflevector to replace edge values.
4216 unsigned NumElts = Op1Type->getVectorNumElements();
4217 for (unsigned i = 0; i != NumElts; ++i) {
4218 Constant *Elt = Op1C->getAggregateElement(i);
Benjamin Kramerca9a0fe2016-05-17 12:08:55 +00004219 if (!Elt)
4220 return nullptr;
4221
Sanjay Patele9b2c322016-05-17 00:57:57 +00004222 if (isa<UndefValue>(Elt))
4223 continue;
Sanjay Patel06b127a2016-09-15 14:37:50 +00004224
Sanjay Patele9b2c322016-05-17 00:57:57 +00004225 // Bail out if we can't determine if this constant is min/max or if we
4226 // know that this constant is min/max.
4227 auto *CI = dyn_cast<ConstantInt>(Elt);
4228 if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned)))
4229 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00004230 }
Sanjay Patele9b2c322016-05-17 00:57:57 +00004231 } else {
4232 // ConstantExpr?
4233 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00004234 }
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004235
Sanjay Patele9b2c322016-05-17 00:57:57 +00004236 // Increment or decrement the constant and set the new comparison predicate:
4237 // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT
Sanjay Patel22b01fe2016-05-17 20:20:40 +00004238 Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true);
Sanjay Patele9b2c322016-05-17 00:57:57 +00004239 CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT;
4240 NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred;
4241 return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne));
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004242}
4243
Chris Lattner2188e402010-01-04 07:37:31 +00004244Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4245 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00004246 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00004247 unsigned Op0Cplxity = getComplexity(Op0);
4248 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004249
Chris Lattner2188e402010-01-04 07:37:31 +00004250 /// Orders the operands of the compare so that they are listed from most
4251 /// complex to least complex. This puts constants before unary operators,
4252 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00004253 if (Op0Cplxity < Op1Cplxity ||
Sanjay Patel4c204232016-06-04 20:39:22 +00004254 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00004255 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00004256 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00004257 Changed = true;
4258 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004259
Jingyue Wu5e34ce32015-06-25 20:14:47 +00004260 if (Value *V =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004261 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004262 return replaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004263
Pete Cooperbc5c5242011-12-01 03:58:40 +00004264 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00004265 // ie, abs(val) != 0 -> val != 0
Sanjay Patel4c204232016-06-04 20:39:22 +00004266 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
Pete Cooperfdddc272011-12-01 19:13:26 +00004267 Value *Cond, *SelectTrue, *SelectFalse;
4268 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00004269 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00004270 if (Value *V = dyn_castNegVal(SelectTrue)) {
4271 if (V == SelectFalse)
4272 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
4273 }
4274 else if (Value *V = dyn_castNegVal(SelectFalse)) {
4275 if (V == SelectTrue)
4276 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00004277 }
4278 }
4279 }
4280
Chris Lattner229907c2011-07-18 04:54:35 +00004281 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00004282
4283 // icmp's with boolean values can always be turned into bitwise operations
Sanjay Patela6fbc822016-06-05 17:49:45 +00004284 if (Ty->getScalarType()->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00004285 switch (I.getPredicate()) {
4286 default: llvm_unreachable("Invalid icmp instruction!");
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004287 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
4288 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00004289 return BinaryOperator::CreateNot(Xor);
4290 }
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004291 case ICmpInst::ICMP_NE: // icmp ne i1 A, B -> A^B
Chris Lattner2188e402010-01-04 07:37:31 +00004292 return BinaryOperator::CreateXor(Op0, Op1);
4293
4294 case ICmpInst::ICMP_UGT:
4295 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004296 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004297 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
4298 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00004299 return BinaryOperator::CreateAnd(Not, Op1);
4300 }
4301 case ICmpInst::ICMP_SGT:
4302 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004303 LLVM_FALLTHROUGH;
Chris Lattner2188e402010-01-04 07:37:31 +00004304 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004305 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00004306 return BinaryOperator::CreateAnd(Not, Op0);
4307 }
4308 case ICmpInst::ICMP_UGE:
4309 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004310 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004311 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
4312 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00004313 return BinaryOperator::CreateOr(Not, Op1);
4314 }
4315 case ICmpInst::ICMP_SGE:
4316 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004317 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004318 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
4319 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00004320 return BinaryOperator::CreateOr(Not, Op0);
4321 }
4322 }
4323 }
4324
Sanjay Patele9b2c322016-05-17 00:57:57 +00004325 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004326 return NewICmp;
4327
Sanjay Patel06b127a2016-09-15 14:37:50 +00004328 if (Instruction *Res = foldICmpWithConstant(I))
4329 return Res;
Chris Lattner2188e402010-01-04 07:37:31 +00004330
Sanjay Patel3151dec2016-09-12 15:24:31 +00004331 if (Instruction *Res = foldICmpUsingKnownBits(I))
4332 return Res;
Chris Lattner2188e402010-01-04 07:37:31 +00004333
4334 // Test if the ICmpInst instruction is used exclusively by a select as
4335 // part of a minimum or maximum operation. If so, refrain from doing
4336 // any other folding. This helps out other analyses which understand
4337 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4338 // and CodeGen. And in this case, at least one of the comparison
4339 // operands has at least one user besides the compare (the select),
4340 // which would often largely negate the benefit of folding anyway.
4341 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00004342 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00004343 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4344 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00004345 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004346
Sanjay Patelfebcb9c2017-01-27 23:26:27 +00004347 // FIXME: We only do this after checking for min/max to prevent infinite
4348 // looping caused by a reverse canonicalization of these patterns for min/max.
4349 // FIXME: The organization of folds is a mess. These would naturally go into
4350 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
4351 // down here after the min/max restriction.
4352 ICmpInst::Predicate Pred = I.getPredicate();
4353 const APInt *C;
4354 if (match(Op1, m_APInt(C))) {
4355 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
4356 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
4357 Constant *Zero = Constant::getNullValue(Op0->getType());
4358 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
4359 }
4360
4361 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
4362 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
4363 Constant *AllOnes = Constant::getAllOnesValue(Op0->getType());
4364 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
4365 }
4366 }
4367
Sanjay Patelf58f68c2016-09-10 15:03:44 +00004368 if (Instruction *Res = foldICmpInstWithConstant(I))
Sanjay Patel1271bf92016-07-23 13:06:49 +00004369 return Res;
4370
Sanjay Patel10494b22016-09-16 16:10:22 +00004371 if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
4372 return Res;
Chris Lattner2188e402010-01-04 07:37:31 +00004373
4374 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
4375 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Sanjay Patel43395062016-07-21 18:07:40 +00004376 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner2188e402010-01-04 07:37:31 +00004377 return NI;
4378 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00004379 if (Instruction *NI = foldGEPICmp(GEP, Op0,
Chris Lattner2188e402010-01-04 07:37:31 +00004380 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
4381 return NI;
4382
Hans Wennborgf1f36512015-10-07 00:20:07 +00004383 // Try to optimize equality comparisons against alloca-based pointers.
4384 if (Op0->getType()->isPointerTy() && I.isEquality()) {
4385 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
4386 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00004387 if (Instruction *New = foldAllocaCmp(I, Alloca, Op1))
Hans Wennborgf1f36512015-10-07 00:20:07 +00004388 return New;
4389 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00004390 if (Instruction *New = foldAllocaCmp(I, Alloca, Op0))
Hans Wennborgf1f36512015-10-07 00:20:07 +00004391 return New;
4392 }
4393
Chris Lattner2188e402010-01-04 07:37:31 +00004394 // Test to see if the operands of the icmp are casted versions of other
4395 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
4396 // now.
4397 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00004398 if (Op0->getType()->isPointerTy() &&
4399 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00004400 // We keep moving the cast from the left operand over to the right
4401 // operand, where it can often be eliminated completely.
4402 Op0 = CI->getOperand(0);
4403
4404 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
4405 // so eliminate it as well.
4406 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
4407 Op1 = CI2->getOperand(0);
4408
4409 // If Op1 is a constant, we can fold the cast into the constant.
4410 if (Op0->getType() != Op1->getType()) {
4411 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4412 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
4413 } else {
4414 // Otherwise, cast the RHS right before the icmp
4415 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
4416 }
4417 }
4418 return new ICmpInst(I.getPredicate(), Op0, Op1);
4419 }
4420 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004421
Chris Lattner2188e402010-01-04 07:37:31 +00004422 if (isa<CastInst>(Op0)) {
4423 // Handle the special case of: icmp (cast bool to X), <cst>
4424 // This comes up when you have code like
4425 // int X = A < B;
4426 // if (X) ...
4427 // For generality, we handle any zero-extension of any operand comparison
4428 // with a constant or another cast from the same type.
4429 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00004430 if (Instruction *R = foldICmpWithCastAndCast(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004431 return R;
4432 }
Chris Lattner2188e402010-01-04 07:37:31 +00004433
Sanjay Patel10494b22016-09-16 16:10:22 +00004434 if (Instruction *Res = foldICmpBinOp(I))
4435 return Res;
Duncan Sandse5220012011-02-17 07:46:37 +00004436
Sanjay Pateldd46b522016-12-19 17:32:37 +00004437 if (Instruction *Res = foldICmpWithMinMax(I))
Sanjay Pateld6406412016-12-15 19:13:37 +00004438 return Res;
4439
Sanjay Patel10494b22016-09-16 16:10:22 +00004440 {
4441 Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00004442 // Transform (A & ~B) == 0 --> (A & B) != 0
4443 // and (A & ~B) != 0 --> (A & B) == 0
4444 // if A is a power of 2.
4445 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00004446 match(Op1, m_Zero()) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004447 isKnownToBeAPowerOfTwo(A, DL, false, 0, &AC, &I, &DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00004448 return new ICmpInst(I.getInversePredicate(),
4449 Builder->CreateAnd(A, B),
4450 Op1);
4451
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004452 // ~x < ~y --> y < x
4453 // ~x < cst --> ~cst < x
4454 if (match(Op0, m_Not(m_Value(A)))) {
4455 if (match(Op1, m_Not(m_Value(B))))
4456 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00004457 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004458 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
4459 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00004460
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004461 Instruction *AddI = nullptr;
4462 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
4463 m_Instruction(AddI))) &&
4464 isa<IntegerType>(A->getType())) {
4465 Value *Result;
4466 Constant *Overflow;
4467 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
4468 Overflow)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004469 replaceInstUsesWith(*AddI, Result);
4470 return replaceInstUsesWith(I, Overflow);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004471 }
4472 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004473
4474 // (zext a) * (zext b) --> llvm.umul.with.overflow.
4475 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
Sanjay Pateld93c4c02016-09-15 18:22:25 +00004476 if (Instruction *R = processUMulZExtIdiom(I, Op0, Op1, *this))
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004477 return R;
4478 }
4479 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
Sanjay Pateld93c4c02016-09-15 18:22:25 +00004480 if (Instruction *R = processUMulZExtIdiom(I, Op1, Op0, *this))
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004481 return R;
4482 }
Chris Lattner2188e402010-01-04 07:37:31 +00004483 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004484
Sanjay Patel10494b22016-09-16 16:10:22 +00004485 if (Instruction *Res = foldICmpEquality(I))
4486 return Res;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004487
David Majnemerc1eca5a2014-11-06 23:23:30 +00004488 // The 'cmpxchg' instruction returns an aggregate containing the old value and
4489 // an i1 which indicates whether or not we successfully did the swap.
4490 //
4491 // Replace comparisons between the old value and the expected value with the
4492 // indicator that 'cmpxchg' returns.
4493 //
4494 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
4495 // spuriously fail. In those cases, the old value may equal the expected
4496 // value but it is possible for the swap to not occur.
4497 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4498 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4499 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4500 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4501 !ACXI->isWeak())
4502 return ExtractValueInst::Create(ACXI, 1);
4503
Chris Lattner2188e402010-01-04 07:37:31 +00004504 {
4505 Value *X; ConstantInt *Cst;
4506 // icmp X+Cst, X
4507 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004508 return foldICmpAddOpConst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004509
4510 // icmp X, X+Cst
4511 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004512 return foldICmpAddOpConst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004513 }
Craig Topperf40110f2014-04-25 05:29:35 +00004514 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004515}
4516
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004517/// Fold fcmp ([us]itofp x, cst) if possible.
Sanjay Patel43395062016-07-21 18:07:40 +00004518Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
Chris Lattner2188e402010-01-04 07:37:31 +00004519 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00004520 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004521 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004522
Chris Lattner2188e402010-01-04 07:37:31 +00004523 // Get the width of the mantissa. We don't want to hack on conversions that
4524 // might lose information from the integer, e.g. "i64 -> float"
4525 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00004526 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004527
Matt Arsenault55e73122015-01-06 15:50:59 +00004528 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4529
Chris Lattner2188e402010-01-04 07:37:31 +00004530 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004531
Matt Arsenault55e73122015-01-06 15:50:59 +00004532 if (I.isEquality()) {
4533 FCmpInst::Predicate P = I.getPredicate();
4534 bool IsExact = false;
4535 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
4536 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
4537
4538 // If the floating point constant isn't an integer value, we know if we will
4539 // ever compare equal / not equal to it.
4540 if (!IsExact) {
4541 // TODO: Can never be -0.0 and other non-representable values
4542 APFloat RHSRoundInt(RHS);
4543 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
4544 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
4545 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00004546 return replaceInstUsesWith(I, Builder->getFalse());
Matt Arsenault55e73122015-01-06 15:50:59 +00004547
4548 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
Sanjay Patel4b198802016-02-01 22:23:39 +00004549 return replaceInstUsesWith(I, Builder->getTrue());
Matt Arsenault55e73122015-01-06 15:50:59 +00004550 }
4551 }
4552
4553 // TODO: If the constant is exactly representable, is it always OK to do
4554 // equality compares as integer?
4555 }
4556
Arch D. Robison8ed08542015-09-15 17:51:59 +00004557 // Check to see that the input is converted from an integer type that is small
4558 // enough that preserves all bits. TODO: check here for "known" sign bits.
4559 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4560 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00004561
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004562 // Following test does NOT adjust InputSize downwards for signed inputs,
4563 // because the most negative value still requires all the mantissa bits
Arch D. Robison8ed08542015-09-15 17:51:59 +00004564 // to distinguish it from one less than that value.
4565 if ((int)InputSize > MantissaWidth) {
4566 // Conversion would lose accuracy. Check if loss can impact comparison.
4567 int Exp = ilogb(RHS);
4568 if (Exp == APFloat::IEK_Inf) {
4569 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004570 if (MaxExponent < (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004571 // Conversion could create infinity.
4572 return nullptr;
4573 } else {
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004574 // Note that if RHS is zero or NaN, then Exp is negative
Arch D. Robison8ed08542015-09-15 17:51:59 +00004575 // and first condition is trivially false.
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004576 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004577 // Conversion could affect comparison.
4578 return nullptr;
4579 }
4580 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004581
Chris Lattner2188e402010-01-04 07:37:31 +00004582 // Otherwise, we can potentially simplify the comparison. We know that it
4583 // will always come through as an integer value and we know the constant is
4584 // not a NAN (it would have been previously simplified).
4585 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00004586
Chris Lattner2188e402010-01-04 07:37:31 +00004587 ICmpInst::Predicate Pred;
4588 switch (I.getPredicate()) {
4589 default: llvm_unreachable("Unexpected predicate!");
4590 case FCmpInst::FCMP_UEQ:
4591 case FCmpInst::FCMP_OEQ:
4592 Pred = ICmpInst::ICMP_EQ;
4593 break;
4594 case FCmpInst::FCMP_UGT:
4595 case FCmpInst::FCMP_OGT:
4596 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4597 break;
4598 case FCmpInst::FCMP_UGE:
4599 case FCmpInst::FCMP_OGE:
4600 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4601 break;
4602 case FCmpInst::FCMP_ULT:
4603 case FCmpInst::FCMP_OLT:
4604 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4605 break;
4606 case FCmpInst::FCMP_ULE:
4607 case FCmpInst::FCMP_OLE:
4608 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4609 break;
4610 case FCmpInst::FCMP_UNE:
4611 case FCmpInst::FCMP_ONE:
4612 Pred = ICmpInst::ICMP_NE;
4613 break;
4614 case FCmpInst::FCMP_ORD:
Sanjay Patel4b198802016-02-01 22:23:39 +00004615 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004616 case FCmpInst::FCMP_UNO:
Sanjay Patel4b198802016-02-01 22:23:39 +00004617 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004618 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004619
Chris Lattner2188e402010-01-04 07:37:31 +00004620 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004621
Chris Lattner2188e402010-01-04 07:37:31 +00004622 // See if the FP constant is too large for the integer. For example,
4623 // comparing an i8 to 300.0.
4624 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004625
Chris Lattner2188e402010-01-04 07:37:31 +00004626 if (!LHSUnsigned) {
4627 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4628 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004629 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004630 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4631 APFloat::rmNearestTiesToEven);
4632 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4633 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4634 Pred == ICmpInst::ICMP_SLE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004635 return replaceInstUsesWith(I, Builder->getTrue());
4636 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004637 }
4638 } else {
4639 // If the RHS value is > UnsignedMax, fold the comparison. This handles
4640 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004641 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004642 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4643 APFloat::rmNearestTiesToEven);
4644 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
4645 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
4646 Pred == ICmpInst::ICMP_ULE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004647 return replaceInstUsesWith(I, Builder->getTrue());
4648 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004649 }
4650 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004651
Chris Lattner2188e402010-01-04 07:37:31 +00004652 if (!LHSUnsigned) {
4653 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004654 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004655 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4656 APFloat::rmNearestTiesToEven);
4657 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4658 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4659 Pred == ICmpInst::ICMP_SGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004660 return replaceInstUsesWith(I, Builder->getTrue());
4661 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004662 }
Devang Patel698452b2012-02-13 23:05:18 +00004663 } else {
4664 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004665 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00004666 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
4667 APFloat::rmNearestTiesToEven);
4668 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
4669 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
4670 Pred == ICmpInst::ICMP_UGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004671 return replaceInstUsesWith(I, Builder->getTrue());
4672 return replaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00004673 }
Chris Lattner2188e402010-01-04 07:37:31 +00004674 }
4675
4676 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4677 // [0, UMAX], but it may still be fractional. See if it is fractional by
4678 // casting the FP value to the integer value and back, checking for equality.
4679 // Don't do this for zero, because -0.0 is not fractional.
4680 Constant *RHSInt = LHSUnsigned
4681 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4682 : ConstantExpr::getFPToSI(RHSC, IntTy);
4683 if (!RHS.isZero()) {
4684 bool Equal = LHSUnsigned
4685 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4686 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4687 if (!Equal) {
4688 // If we had a comparison against a fractional value, we have to adjust
4689 // the compare predicate and sometimes the value. RHSC is rounded towards
4690 // zero at this point.
4691 switch (Pred) {
4692 default: llvm_unreachable("Unexpected integer comparison!");
4693 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Sanjay Patel4b198802016-02-01 22:23:39 +00004694 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004695 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Sanjay Patel4b198802016-02-01 22:23:39 +00004696 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004697 case ICmpInst::ICMP_ULE:
4698 // (float)int <= 4.4 --> int <= 4
4699 // (float)int <= -4.4 --> false
4700 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004701 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004702 break;
4703 case ICmpInst::ICMP_SLE:
4704 // (float)int <= 4.4 --> int <= 4
4705 // (float)int <= -4.4 --> int < -4
4706 if (RHS.isNegative())
4707 Pred = ICmpInst::ICMP_SLT;
4708 break;
4709 case ICmpInst::ICMP_ULT:
4710 // (float)int < -4.4 --> false
4711 // (float)int < 4.4 --> int <= 4
4712 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004713 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004714 Pred = ICmpInst::ICMP_ULE;
4715 break;
4716 case ICmpInst::ICMP_SLT:
4717 // (float)int < -4.4 --> int < -4
4718 // (float)int < 4.4 --> int <= 4
4719 if (!RHS.isNegative())
4720 Pred = ICmpInst::ICMP_SLE;
4721 break;
4722 case ICmpInst::ICMP_UGT:
4723 // (float)int > 4.4 --> int > 4
4724 // (float)int > -4.4 --> true
4725 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004726 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004727 break;
4728 case ICmpInst::ICMP_SGT:
4729 // (float)int > 4.4 --> int > 4
4730 // (float)int > -4.4 --> int >= -4
4731 if (RHS.isNegative())
4732 Pred = ICmpInst::ICMP_SGE;
4733 break;
4734 case ICmpInst::ICMP_UGE:
4735 // (float)int >= -4.4 --> true
4736 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00004737 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004738 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004739 Pred = ICmpInst::ICMP_UGT;
4740 break;
4741 case ICmpInst::ICMP_SGE:
4742 // (float)int >= -4.4 --> int >= -4
4743 // (float)int >= 4.4 --> int > 4
4744 if (!RHS.isNegative())
4745 Pred = ICmpInst::ICMP_SGT;
4746 break;
4747 }
4748 }
4749 }
4750
4751 // Lower this FP comparison into an appropriate integer version of the
4752 // comparison.
4753 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4754}
4755
4756Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4757 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004758
Chris Lattner2188e402010-01-04 07:37:31 +00004759 /// Orders the operands of the compare so that they are listed from most
4760 /// complex to least complex. This puts constants before unary operators,
4761 /// before binary operators.
4762 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4763 I.swapOperands();
4764 Changed = true;
4765 }
4766
4767 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004768
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004769 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004770 I.getFastMathFlags(), DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004771 return replaceInstUsesWith(I, V);
Chris Lattner2188e402010-01-04 07:37:31 +00004772
4773 // Simplify 'fcmp pred X, X'
4774 if (Op0 == Op1) {
4775 switch (I.getPredicate()) {
4776 default: llvm_unreachable("Unknown predicate!");
4777 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4778 case FCmpInst::FCMP_ULT: // True if unordered or less than
4779 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4780 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4781 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4782 I.setPredicate(FCmpInst::FCMP_UNO);
4783 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4784 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004785
Chris Lattner2188e402010-01-04 07:37:31 +00004786 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4787 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4788 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4789 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4790 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4791 I.setPredicate(FCmpInst::FCMP_ORD);
4792 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4793 return &I;
4794 }
4795 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004796
James Molloy2b21a7c2015-05-20 18:41:25 +00004797 // Test if the FCmpInst instruction is used exclusively by a select as
4798 // part of a minimum or maximum operation. If so, refrain from doing
4799 // any other folding. This helps out other analyses which understand
4800 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4801 // and CodeGen. And in this case, at least one of the comparison
4802 // operands has at least one user besides the compare (the select),
4803 // which would often largely negate the benefit of folding anyway.
4804 if (I.hasOneUse())
4805 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4806 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4807 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4808 return nullptr;
4809
Chris Lattner2188e402010-01-04 07:37:31 +00004810 // Handle fcmp with constant RHS
4811 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4812 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4813 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004814 case Instruction::FPExt: {
4815 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4816 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4817 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4818 if (!RHSF)
4819 break;
4820
4821 const fltSemantics *Sem;
4822 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004823 if (LHSExt->getSrcTy()->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004824 Sem = &APFloat::IEEEhalf();
Dan Gohman518cda42011-12-17 00:04:22 +00004825 else if (LHSExt->getSrcTy()->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004826 Sem = &APFloat::IEEEsingle();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004827 else if (LHSExt->getSrcTy()->isDoubleTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004828 Sem = &APFloat::IEEEdouble();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004829 else if (LHSExt->getSrcTy()->isFP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004830 Sem = &APFloat::IEEEquad();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004831 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004832 Sem = &APFloat::x87DoubleExtended();
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004833 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004834 Sem = &APFloat::PPCDoubleDouble();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004835 else
4836 break;
4837
4838 bool Lossy;
4839 APFloat F = RHSF->getValueAPF();
4840 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4841
Jim Grosbach24ff8342011-09-30 18:45:50 +00004842 // Avoid lossy conversions and denormals. Zero is a special case
4843 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004844 APFloat Fabs = F;
4845 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004846 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004847 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4848 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004849
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004850 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4851 ConstantFP::get(RHSC->getContext(), F));
4852 break;
4853 }
Chris Lattner2188e402010-01-04 07:37:31 +00004854 case Instruction::PHI:
4855 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4856 // block. If in the same block, we're encouraging jump threading. If
4857 // not, we are just pessimizing the code by making an i1 phi.
4858 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004859 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004860 return NV;
4861 break;
4862 case Instruction::SIToFP:
4863 case Instruction::UIToFP:
Sanjay Patel43395062016-07-21 18:07:40 +00004864 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
Chris Lattner2188e402010-01-04 07:37:31 +00004865 return NV;
4866 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004867 case Instruction::FSub: {
4868 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4869 Value *Op;
4870 if (match(LHSI, m_FNeg(m_Value(Op))))
4871 return new FCmpInst(I.getSwappedPredicate(), Op,
4872 ConstantExpr::getFNeg(RHSC));
4873 break;
4874 }
Dan Gohman94732022010-02-24 06:46:09 +00004875 case Instruction::Load:
4876 if (GetElementPtrInst *GEP =
4877 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4878 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4879 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4880 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00004881 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Dan Gohman94732022010-02-24 06:46:09 +00004882 return Res;
4883 }
4884 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004885 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004886 if (!RHSC->isNullValue())
4887 break;
4888
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004889 CallInst *CI = cast<CallInst>(LHSI);
Justin Bogner99798402016-08-05 01:06:44 +00004890 Intrinsic::ID IID = getIntrinsicForCallSite(CI, &TLI);
David Majnemer2e02ba72016-04-15 17:21:03 +00004891 if (IID != Intrinsic::fabs)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004892 break;
4893
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004894 // Various optimization for fabs compared with zero.
David Majnemer2e02ba72016-04-15 17:21:03 +00004895 switch (I.getPredicate()) {
4896 default:
4897 break;
4898 // fabs(x) < 0 --> false
4899 case FCmpInst::FCMP_OLT:
4900 llvm_unreachable("handled by SimplifyFCmpInst");
4901 // fabs(x) > 0 --> x != 0
4902 case FCmpInst::FCMP_OGT:
4903 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
4904 // fabs(x) <= 0 --> x == 0
4905 case FCmpInst::FCMP_OLE:
4906 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
4907 // fabs(x) >= 0 --> !isnan(x)
4908 case FCmpInst::FCMP_OGE:
4909 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
4910 // fabs(x) == 0 --> x == 0
4911 // fabs(x) != 0 --> x != 0
4912 case FCmpInst::FCMP_OEQ:
4913 case FCmpInst::FCMP_UEQ:
4914 case FCmpInst::FCMP_ONE:
4915 case FCmpInst::FCMP_UNE:
4916 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004917 }
4918 }
Chris Lattner2188e402010-01-04 07:37:31 +00004919 }
Chris Lattner2188e402010-01-04 07:37:31 +00004920 }
4921
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004922 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004923 Value *X, *Y;
4924 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004925 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004926
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004927 // fcmp (fpext x), (fpext y) -> fcmp x, y
4928 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4929 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4930 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4931 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4932 RHSExt->getOperand(0));
4933
Craig Topperf40110f2014-04-25 05:29:35 +00004934 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004935}